Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40fcb80a7d | ||
|
|
ff64548085 | ||
|
|
042f02b852 | ||
|
|
5fc85c1699 | ||
|
|
c01c6cf457 | ||
|
|
22780881e1 | ||
|
|
201e204290 | ||
|
|
eb8434e508 | ||
|
|
597b13e2db | ||
|
|
946b333109 | ||
|
|
8b3731b22f | ||
|
|
b76ba7a314 | ||
|
|
2c15bd4207 | ||
|
|
949add15b1 | ||
|
|
6a93d13ecb | ||
|
|
cbc02bb407 | ||
|
|
525f6b5fc0 | ||
|
|
de8f5558c2 | ||
|
|
58e8b1edb6 | ||
|
|
adcf4ded79 | ||
|
|
05d6ee4d7c | ||
|
|
d42fa91698 | ||
|
|
41cbafddba | ||
|
|
a2be512c45 | ||
|
|
6a66710763 | ||
|
|
8632ced503 | ||
|
|
ae18bbee24 | ||
|
|
9690071e7d | ||
|
|
698b45cbb3 | ||
|
|
afa875d89f | ||
|
|
aff758fb99 | ||
|
|
8625963846 | ||
|
|
d367cd3a24 | ||
|
|
6f0948ca01 | ||
|
|
541a7c078d | ||
|
|
e0b726de85 | ||
|
|
105da550e7 | ||
|
|
febc26fe35 | ||
|
|
28a906215d | ||
|
|
dbf71a87f4 | ||
|
|
95ed8e6edb | ||
|
|
d26bf6c25b | ||
|
|
181e10f2ad | ||
|
|
857a1551f3 | ||
|
|
00052d20d9 |
@@ -101,6 +101,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -85,6 +85,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -15,6 +15,7 @@ contract here and in `RELEASE.md`.
|
||||
- Contributor setup → **[CONTRIBUTING.md](CONTRIBUTING.md)**
|
||||
- Gateway/session/reconnect testing → **[docs/gateway-contract-testing.md](docs/gateway-contract-testing.md)**
|
||||
- Android local/cloud verification → **[docs/android-build-lane.md](docs/android-build-lane.md)**
|
||||
- Android emulator lanes → **[docs/android-emulator-testing.md](docs/android-emulator-testing.md)** — suggest the smallest relevant API 36 lanes; never run the full matrix automatically
|
||||
- `android_*` toolset + MCP → **[docs/mcp-tooling.md](docs/mcp-tooling.md)**
|
||||
- Follow-ups / deferred work / known gaps → **[TODO.md](TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
|
||||
|
||||
@@ -64,8 +65,10 @@ PR; never resolve those cases by choosing a side automatically.
|
||||
|
||||
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
|
||||
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
||||
and Vanilla Hermes voice. The API server is an optional automatic fallback and
|
||||
advanced headless-compatibility surface; Relay adds optional extensions. This
|
||||
and Vanilla Hermes voice. The API server is an explicit API-only/headless
|
||||
compatibility surface; Relay adds optional extensions. A Gateway-owned
|
||||
conversation never changes transport because Gateway auth or reachability
|
||||
changes. This
|
||||
path must work against unmodified upstream hermes-agent. Server-side needs go
|
||||
through upstream PRs or the optional relay plugin, never fork patches.
|
||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||
|
||||
@@ -8,11 +8,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android Supervised Mode uses app-specific parent access.** Parents choose a six-digit PIN or password, receive a shareable six-word recovery phrase, and can remove the credential without losing their supervised profile, capability, appearance, visibility, session, or relock settings. Android device credentials and biometrics no longer grant parent access.
|
||||
- **Android What's New now provides a readable, complete release record.** One overall title and summary lead into selected highlights, every remaining user-visible addition, improvement, and fix, and relevant compatibility boundaries. Toast counts and previews are derived from that same inventory, so View all no longer promises details the expanded dialog and history cannot show.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Passively observed Desktop/TUI turns now show live activity in the Android session drawer.** A uniquely matched selected session projects Working or Waiting without Android resuming, activating, or interrupting the external runtime; ambiguous cross-profile matches remain neutral. (Related: #365)
|
||||
- **Hermes-Relay Plugin installs through the native Hermes command again.** The manifest remains fully described for current hosts while avoiding the installer/runtime schema mismatch in affected Hermes releases.
|
||||
- **Android Chat keeps one transport owner through sign-out and outages.** Dashboard/Gateway conversations now preserve their transcript, draft, profile, and session for sign-in or retry instead of silently sending the next turn to a reachable Direct API database. Legacy API-only connections and explicitly selected Direct API chats remain supported.
|
||||
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
|
||||
- **Android keeps long-running context compaction alive.** A client-visible compaction status extends and refreshes the Gateway turn watchdog instead of interrupting healthy compression after the ordinary idle window. (Supersedes #484.)
|
||||
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
|
||||
- **Android Chat settles an owned Gateway turn when its terminal frame is lost.** An exact idle `session.active_list` snapshot now completes the matching local stream, reconciles durable history, and drains its queued follow-up without interrupting or claiming Desktop/TUI work.
|
||||
- **Supervised Gateway setup stays parent-owned.** Add Gateway is single-flight and checks live parent authority before allocating a draft, relock/back cancels the exact pending setup, and the locked Chat footer no longer attempts protected navigation.
|
||||
- **Generated images stay visible and use their intended Chat animation.** Completed image media survives a marker-lagging history refresh, and both the built-in `image_generate` tool and profile tools ending in `_create_image` use the image-generation presentation.
|
||||
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-08-31 — Android Gateway compaction watchdog lease
|
||||
|
||||
Gateway turns now recognize the upstream `status.update` payload kind
|
||||
`compacting` and arm a ten-minute idle lease instead of the ordinary
|
||||
three-minute watchdog. A single current-Gateway status protects silent
|
||||
compaction, while repeated status heartbeats from newer gateways refresh the
|
||||
same lease. Other status payloads retain the ordinary watchdog.
|
||||
|
||||
Focused Gateway client coverage uses shortened timeout seams to prove the
|
||||
single-status, repeated-heartbeat, ordinary-silence, and payload-fencing paths
|
||||
without waiting production minutes. The declarative vanilla-Gateway fixture
|
||||
also models repeated compaction status before terminal completion.
|
||||
|
||||
## 2026-08-31 — Complete, readable Android release notes
|
||||
|
||||
Android release metadata now keeps one overall title and summary plus a complete
|
||||
|
||||
@@ -99,7 +99,7 @@ The wizard probes everything and finishes with a capability card:
|
||||
| **Chat** | Dashboard/Gateway ready — you can talk |
|
||||
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
||||
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
|
||||
| **API fallback** | Optional API route available/unavailable |
|
||||
| **Direct API** | Optional API-only compatibility route available/unavailable |
|
||||
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
|
||||
|
||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
||||
@@ -140,7 +140,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
[Desktop CLI pairing](https://hermes-relay.dev/docs/desktop/pairing) ·
|
||||
[server, TLS, legacy install, and uninstall reference](https://hermes-relay.dev/docs/reference/relay-server)
|
||||
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. The API fallback is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. Direct API is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -240,13 +240,13 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
||||
|
||||
```
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
||||
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
||||
```
|
||||
|
||||
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
|
||||
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
|
||||
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
|
||||
connections use the upstream Direct API SSE path with an API key. Manage and Vanilla Hermes
|
||||
voice ride the Hermes dashboard with its own one-time sign-in, so a vanilla
|
||||
install needs no plugin for either. The optional relay on `:8767` adds the power
|
||||
surfaces: terminal, bridge phone control, media handoff, machine tools, and
|
||||
|
||||
@@ -6,6 +6,31 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Restore the plugin manifest v2 declaration after the Hermes installer fix ships
|
||||
|
||||
Hermes installers in affected stable releases reject `manifest_version: 2`
|
||||
before the v2-capable runtime loader can inspect the plugin. Track upstream
|
||||
[PR #85893](https://github.com/NousResearch/hermes-agent/pull/85893). Restore
|
||||
`plugin/plugin.yaml` to `manifest_version: 2` only after that fix ships in a
|
||||
stable Hermes release that Hermes-Relay can treat as its minimum supported
|
||||
version. Until then, keep the v1 compatibility declaration and the additive
|
||||
metadata consumed by newer hosts.
|
||||
|
||||
---
|
||||
|
||||
## Consider hosted Android emulator execution
|
||||
|
||||
The local API 36 Gradle Managed Device lanes are intentionally on demand and
|
||||
individually selected. The current Android On-Demand workflow covers hosted
|
||||
source, unit, lint, and build verification only; it does not run emulators. If
|
||||
local emulator capacity becomes a recurring constraint, evaluate a separately
|
||||
approved hosted-emulator design with explicit cost, concurrency, artifact
|
||||
retention, and trigger policy. Do not schedule the full form-factor matrix or
|
||||
add a device farm until that policy is approved; keep live-server mutation tests
|
||||
outside any automatic matrix.
|
||||
|
||||
---
|
||||
|
||||
## Upstream a public Dashboard plugin WebSocket admission seam
|
||||
|
||||
The same-origin Relay ingress follows current upstream's bundled Dashboard
|
||||
@@ -28,8 +53,11 @@ and older Gateways without `session.active_list`. Before calling the status
|
||||
model device-certified:
|
||||
|
||||
- Exercise working, quiet tool-heavy work, each pending-input surface, normal
|
||||
completion, Stop, reconnect, app restart, and process recreation against
|
||||
current vanilla upstream.
|
||||
completion, a lost terminal followed by an exact active-list Idle row, Stop,
|
||||
reconnect, app restart, and process recreation against current vanilla
|
||||
upstream. Confirm the lost-terminal path preserves the partial transcript,
|
||||
settles composer/steering state, and drains or cancels queued corrections
|
||||
exactly once according to the owning turn outcome.
|
||||
- Verify All Profiles with duplicate session ids across two profiles and two
|
||||
saved connections; no late snapshot or old socket generation may mark the
|
||||
wrong row live.
|
||||
|
||||
@@ -249,6 +249,58 @@ android {
|
||||
it.systemProperty("roborazzi.test.record", "true")
|
||||
it.maxHeapSize = "2g"
|
||||
}
|
||||
|
||||
// On-demand only. Keep each form factor as an individually selected
|
||||
// Gradle-managed device; there is deliberately no aggregate matrix
|
||||
// task or scheduled emulator job. See docs/android-emulator-testing.md.
|
||||
managedDevices {
|
||||
localDevices {
|
||||
create("compactPhoneApi36") {
|
||||
device = "Pixel 2"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("standardPhoneApi36") {
|
||||
device = "Pixel 6"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("largePhoneApi36") {
|
||||
device = "Pixel 7 Pro"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("foldableApi36") {
|
||||
device = "Pixel Fold"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("tabletApi36") {
|
||||
device = "Pixel Tablet"
|
||||
apiLevel = 36
|
||||
systemImageSource = "aosp"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
}
|
||||
create("futureApi37Ps16k") {
|
||||
device = "Pixel 7 Pro"
|
||||
apiLevel = 37
|
||||
systemImageSource = "google_apis_playstore"
|
||||
require64Bit = true
|
||||
testedAbi = "x86_64"
|
||||
pageAlignment =
|
||||
com.android.build.api.dsl.ManagedVirtualDevice.PageAlignment.FORCE_16KB_PAGES
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,6 +442,12 @@ dependencies {
|
||||
// Konsist — enforces the ADR 34 upstream/relay/shared package fence as a JUnit test
|
||||
testImplementation(libs.konsist)
|
||||
androidTestImplementation(libs.compose.ui.test.junit4)
|
||||
// Compose UI Test still declares Espresso 3.5.0 transitively. API 37
|
||||
// removed the reflected InputManager.getInstance() seam; Espresso 3.7.0
|
||||
// uses Context.getSystemService and is the current stable AndroidX line.
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
androidTestImplementation("androidx.test:runner:1.7.0")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
// On-device vanilla-Gateway contract tests exercise the production
|
||||
// Dashboard ticket + WebSocket stack over real loopback sockets.
|
||||
androidTestImplementation(libs.okhttp.mockwebserver)
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
|
||||
+241
-7
@@ -4,6 +4,7 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -17,6 +18,11 @@ import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.ChatTurnAssistantCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
|
||||
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
@@ -27,6 +33,7 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
@@ -44,6 +51,7 @@ import okhttp3.mockwebserver.RecordedRequest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
@@ -74,10 +82,11 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
|
||||
@Volatile
|
||||
private var persistedHistory: List<MessageItem> = emptyList()
|
||||
private val historySignInRequired = MutableStateFlow(false)
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
fixture = AndroidGatewayContractFixture().also { it.profileName = PROFILE_NAME }
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
@@ -97,6 +106,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
handler,
|
||||
)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setSessionProfileNameProvider { PROFILE_NAME }
|
||||
it.setProfileMessageLoader { Result.success(persistedHistory) }
|
||||
it.updateGatewayClient(gatewayClient)
|
||||
it.setChatVisible(true)
|
||||
@@ -105,6 +115,7 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
compose.setContent {
|
||||
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
||||
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
|
||||
MaterialTheme {
|
||||
Column(Modifier.testTag("contract-transcript")) {
|
||||
Text(
|
||||
@@ -117,6 +128,14 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
modifier = Modifier.testTag("message-${message.id}"),
|
||||
)
|
||||
}
|
||||
if (signInRequired) {
|
||||
Button(
|
||||
onClick = {},
|
||||
modifier = Modifier.testTag("dashboard-sign-in-recovery"),
|
||||
) {
|
||||
Text("SIGN IN")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,6 +258,46 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActiveList_settlesExactOwnedTurnAndRendersAuthoritativeHistory() {
|
||||
viewModel.sendMessage("Run an Android-owned task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", PARTIAL_ANSWER) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
compose.waitUntil(5_000) { handler.isStreaming.value }
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("STREAMING")
|
||||
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = PERSISTED_ANSWER_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(AUTHORITATIVE_ANSWER),
|
||||
),
|
||||
)
|
||||
fixture.activeSessionStatus = "idle"
|
||||
runBlocking { gatewayClient.listActiveSessions() }
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
!handler.isStreaming.value &&
|
||||
!gatewayClient.hasActiveTurn() &&
|
||||
handler.messages.value.singleOrNull()?.id == PERSISTED_ANSWER_ID
|
||||
}
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("message-$PERSISTED_ANSWER_ID")
|
||||
.assertTextEquals("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
assertEquals(0, fixture.rpcCount("session.interrupt"))
|
||||
assertEquals(0, fixture.rpcCount("session.activate"))
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
@@ -252,9 +311,6 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val baselineActiveList = fixture.rpcCount("session.active_list")
|
||||
fixture.activeSessionStatus = "working"
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
@@ -269,6 +325,17 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
assertTrue(runBlocking { gatewayClient.observeAwait() })
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
|
||||
STORED_SESSION_ID,
|
||||
)
|
||||
viewModel.updateSessionActivityDirectory(listOf(PROFILE_NAME to STORED_SESSION_ID))
|
||||
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val baselineActiveList = fixture.rpcCount("session.active_list")
|
||||
fixture.activeSessionStatus = "working"
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
@@ -293,6 +360,141 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalCompletion_genericHistory401RetainsTranscriptAndRequiresProfileSignIn() {
|
||||
bindDashboardHistoryFailure(
|
||||
body = "Unauthorized",
|
||||
profileName = PROFILE_NAME,
|
||||
)
|
||||
|
||||
viewModel.sendMessage("Keep this local transcript")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", LOCAL_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", LOCAL_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
compose.waitUntil(15_000) {
|
||||
historySignInRequired.value &&
|
||||
!handler.isStreaming.value &&
|
||||
handler.messages.value.any { it.content == LOCAL_COMPLETION }
|
||||
}
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
|
||||
assertFalse(viewModel.isLoadingHistory.value)
|
||||
assertTrue(handler.messages.value.any { it.content == "Keep this local transcript" })
|
||||
assertTrue(handler.messages.value.any { it.content == LOCAL_COMPLETION })
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
assertExactProfileHistoryOnly(PROFILE_NAME)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveredCompletion_sessionExpiredHistoryRetainsSettledTranscript() {
|
||||
bindDashboardHistoryFailure(
|
||||
body = """{"reason":"session_expired"}""",
|
||||
profileName = PROFILE_NAME,
|
||||
)
|
||||
val now = System.currentTimeMillis()
|
||||
val contextKey = AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME)
|
||||
viewModel.setChatTurnCheckpointStore(
|
||||
MemoryCheckpointStore(
|
||||
ChatTurnCheckpoint(
|
||||
contextKey = contextKey,
|
||||
profileKey = PROFILE_NAME,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
liveSessionId = LIVE_SESSION_ID,
|
||||
transport = "gateway",
|
||||
user = ChatTurnUserCheckpoint("recovered-user", "Resume this turn", now - 2_000L),
|
||||
assistant = ChatTurnAssistantCheckpoint(
|
||||
id = "recovered-assistant",
|
||||
content = "Recovered partial",
|
||||
timestamp = now - 1_900L,
|
||||
),
|
||||
priorUserMessageCount = 0,
|
||||
baselineAssistantCount = 0,
|
||||
startedAt = now - 2_000L,
|
||||
updatedAt = now,
|
||||
),
|
||||
),
|
||||
)
|
||||
fixture.recoveryRunning = true
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
|
||||
fixture.awaitRpc("session.activate")
|
||||
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", RECOVERED_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", RECOVERED_COMPLETION) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
|
||||
compose.waitUntil(15_000) {
|
||||
historySignInRequired.value && !handler.isStreaming.value
|
||||
}
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
|
||||
compose.onNodeWithTag("contract-transcript").assertIsDisplayed()
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("dashboard-sign-in-recovery").assertIsDisplayed()
|
||||
assertFalse(viewModel.isLoadingHistory.value)
|
||||
assertTrue(
|
||||
"recovered completion was not retained: ${handler.messages.value}",
|
||||
handler.messages.value.any { it.content.contains(RECOVERED_COMPLETION.trim()) },
|
||||
)
|
||||
assertFalse(handler.messages.value.any { it.isStreaming || it.isThinkingStreaming })
|
||||
assertNull(viewModel.chatFailure.value)
|
||||
assertExactProfileHistoryOnly(PROFILE_NAME)
|
||||
}
|
||||
|
||||
private fun bindDashboardHistoryFailure(body: String, profileName: String) {
|
||||
fixture.profileName = profileName
|
||||
fixture.historyFailureBody = body
|
||||
val dashboard = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = OkHttpClient(),
|
||||
)
|
||||
viewModel.setProfileMessageLoaderWithMode { profile, sessionId, mode ->
|
||||
dashboard.getSessionMessages(sessionId, profile, mode)
|
||||
}
|
||||
viewModel.setDashboardSignInRequiredHandler {
|
||||
historySignInRequired.value = true
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertExactProfileHistoryOnly(profileName: String) {
|
||||
val historyRequests = fixture.historyRequestPaths()
|
||||
assertTrue("no Dashboard history request was observed", historyRequests.isNotEmpty())
|
||||
assertTrue(
|
||||
"history escaped the exact profile: $historyRequests",
|
||||
historyRequests.all { it.contains("profile=$profileName") },
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
@@ -301,6 +503,23 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
const val PARTIAL_ANSWER = "Partial foreground answer"
|
||||
const val AUTHORITATIVE_ANSWER = "Foreground task finished."
|
||||
const val FOREIGN_ANSWER = "Wrong session content"
|
||||
const val PROFILE_NAME = "research"
|
||||
const val LOCAL_COMPLETION = "Completed before Dashboard auth expired."
|
||||
const val RECOVERED_COMPLETION = " and then recovered to completion."
|
||||
}
|
||||
}
|
||||
|
||||
private class MemoryCheckpointStore(
|
||||
private var checkpoint: ChatTurnCheckpoint?,
|
||||
) : ChatTurnCheckpointStore {
|
||||
override suspend fun read(): ChatTurnCheckpoint? = checkpoint
|
||||
|
||||
override suspend fun write(checkpoint: ChatTurnCheckpoint) {
|
||||
this.checkpoint = checkpoint
|
||||
}
|
||||
|
||||
override suspend fun clear() {
|
||||
checkpoint = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +539,12 @@ internal class AndroidGatewayContractFixture {
|
||||
@Volatile
|
||||
var activeSessionStatus: String? = null
|
||||
|
||||
@Volatile
|
||||
var historyFailureBody: String? = null
|
||||
|
||||
@Volatile
|
||||
var profileName: String = "default"
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
sockets.add(webSocket)
|
||||
@@ -377,6 +602,11 @@ internal class AndroidGatewayContractFixture {
|
||||
"""{"ticket":"device-${ticketCount.incrementAndGet()}","ttl_seconds":30}""",
|
||||
)
|
||||
path.startsWith("/api/ws") -> MockResponse().withWebSocketUpgrade(listener)
|
||||
path.startsWith("/api/sessions/") && path.contains("/messages") &&
|
||||
historyFailureBody != null -> MockResponse()
|
||||
.setResponseCode(401)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(historyFailureBody.orEmpty())
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
@@ -388,7 +618,7 @@ internal class AndroidGatewayContractFixture {
|
||||
put("session_id", sessionId)
|
||||
put("running", recoveryRunning)
|
||||
put("status", if (recoveryRunning) "streaming" else "idle")
|
||||
put("info", buildJsonObject { put("profile_name", "default") })
|
||||
put("info", buildJsonObject { put("profile_name", profileName) })
|
||||
}
|
||||
|
||||
fun event(type: String, payload: JsonObject?, sessionId: String?): String =
|
||||
@@ -406,7 +636,7 @@ internal class AndroidGatewayContractFixture {
|
||||
sockets.poll(5, TimeUnit.SECONDS) ?: error("Gateway WebSocket did not open")
|
||||
|
||||
fun awaitRpc(method: String): JsonObject {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
|
||||
while (System.nanoTime() < deadline) {
|
||||
rpcLog.firstOrNull { it.first == method }?.let { return it.second }
|
||||
Thread.sleep(20)
|
||||
@@ -415,7 +645,7 @@ internal class AndroidGatewayContractFixture {
|
||||
}
|
||||
|
||||
fun awaitRpcCount(method: String, count: Int) {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15)
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (rpcCount(method) >= count) return
|
||||
Thread.sleep(20)
|
||||
@@ -425,6 +655,10 @@ internal class AndroidGatewayContractFixture {
|
||||
|
||||
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
|
||||
|
||||
fun historyRequestPaths(): List<String> = requestPaths.filter {
|
||||
it.startsWith("/api/sessions/") && it.contains("/messages")
|
||||
}
|
||||
|
||||
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
|
||||
|
||||
fun shutdown() {
|
||||
|
||||
@@ -29,3 +29,24 @@ val Connection.capabilities: ConnectionCapabilities
|
||||
apiServerConfigured = apiServerUrl.isNotBlank(),
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Stable owner for an Auto chat before a conversation is opened.
|
||||
*
|
||||
* A legacy API-only record has no persisted Dashboard route; the conventional
|
||||
* same-host `:9119` derivation remains useful for an explicit upgrade, but it
|
||||
* must not silently turn that compatibility record into a Gateway-owned chat.
|
||||
* Once a Dashboard route (or authenticated Dashboard origin) is persisted,
|
||||
* standard Chat belongs to Gateway even while that route is signed out or
|
||||
* temporarily unreachable.
|
||||
*/
|
||||
val Connection.automaticChatTransport: SessionTransport
|
||||
get() {
|
||||
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
|
||||
!authenticatedDashboardOrigin.isNullOrBlank()
|
||||
return if (dashboardPersisted) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
}
|
||||
|
||||
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
|
||||
if (preference == "auto") automaticChatTransport
|
||||
else SessionTransport.forEndpoint(preference)
|
||||
|
||||
@@ -124,7 +124,7 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||
"API / sessions", "API fallback" -> "api"
|
||||
"API / sessions", "API fallback", "Direct API" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fun computeConnectionSecurity(
|
||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "API fallback",
|
||||
label = "Direct API",
|
||||
url = it,
|
||||
activeEndpoint = apiEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
|
||||
@@ -81,6 +81,24 @@ class SupervisedModeStore private constructor(
|
||||
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
|
||||
}
|
||||
|
||||
/** Disable every policy while preserving its configured controls and remove the parent credential atomically. */
|
||||
internal suspend fun disableAllAndRemoveCredential(
|
||||
parentCredentialKey: Preferences.Key<String>,
|
||||
) {
|
||||
dataStore.edit { preferences ->
|
||||
val decoded = decode(preferences[KEY_POLICIES])
|
||||
if (decoded.corrupt || decoded.policies.isEmpty()) {
|
||||
preferences.remove(KEY_POLICIES)
|
||||
} else {
|
||||
val disabled = decoded.policies.mapValues { (_, policy) ->
|
||||
policy.copy(enabled = false).normalized()
|
||||
}
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, disabled)
|
||||
}
|
||||
preferences.remove(parentCredentialKey)
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodeResult {
|
||||
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
|
||||
return try {
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** Availability of the app-specific parent credential. */
|
||||
enum class SupervisedParentAuthStatus {
|
||||
Missing,
|
||||
Configured,
|
||||
Corrupt,
|
||||
}
|
||||
|
||||
/** Input method selected for the app-specific parent credential. */
|
||||
@Serializable
|
||||
enum class SupervisedParentCredentialType {
|
||||
Legacy,
|
||||
Pin,
|
||||
Password,
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private enum class SupervisedRecoveryFormat {
|
||||
LegacyCode,
|
||||
WordPhrase,
|
||||
}
|
||||
|
||||
/** Result of a parent-secret or recovery-phrase verification attempt. */
|
||||
sealed interface SupervisedParentAuthResult {
|
||||
data object Success : SupervisedParentAuthResult
|
||||
data class Invalid(val attemptsBeforeDelay: Int) : SupervisedParentAuthResult
|
||||
data class Throttled(val retryAfterMillis: Long) : SupervisedParentAuthResult
|
||||
data object Missing : SupervisedParentAuthResult
|
||||
data object Corrupt : SupervisedParentAuthResult
|
||||
}
|
||||
|
||||
/** Successful enrollment returns a recovery phrase which is shown once and never persisted. */
|
||||
data class SupervisedParentEnrollment(val recoveryPhrase: String)
|
||||
|
||||
/** Validation result for a new parent PIN or password. */
|
||||
data class SupervisedParentSecretValidation(
|
||||
val valid: Boolean,
|
||||
val message: String? = null,
|
||||
)
|
||||
|
||||
/** Narrow authentication surface consumed by Compose dialogs and test fakes. */
|
||||
interface SupervisedParentAuthenticator {
|
||||
val credentialTypeFlow: Flow<SupervisedParentCredentialType?>
|
||||
suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun verify(secret: CharArray): SupervisedParentAuthResult
|
||||
suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment>
|
||||
}
|
||||
|
||||
/**
|
||||
* App-specific parent authentication for Supervised Mode.
|
||||
*
|
||||
* This store deliberately does not delegate to Android's device credential: a
|
||||
* child can legitimately own the PIN or biometrics on their Android profile.
|
||||
* Only salted PBKDF2 verifiers and bounded failure state are stored. The parent
|
||||
* secret and recovery phrase are never persisted.
|
||||
*/
|
||||
class SupervisedParentAuthStore private constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
private val iterations: Int,
|
||||
private val minimumAcceptedIterations: Int,
|
||||
private val random: SecureRandom,
|
||||
private val nowMillis: () -> Long,
|
||||
) : SupervisedParentAuthenticator {
|
||||
constructor(context: Context) : this(
|
||||
dataStore = context.applicationContext.relayDataStore,
|
||||
iterations = DEFAULT_PBKDF2_ITERATIONS,
|
||||
minimumAcceptedIterations = MIN_ACCEPTED_ITERATIONS,
|
||||
random = SecureRandom(),
|
||||
nowMillis = System::currentTimeMillis,
|
||||
)
|
||||
|
||||
private val json = Json { encodeDefaults = true; ignoreUnknownKeys = false }
|
||||
val statusFlow: Flow<SupervisedParentAuthStatus> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).status
|
||||
}
|
||||
override val credentialTypeFlow: Flow<SupervisedParentCredentialType?> = dataStore.data.map { preferences ->
|
||||
decode(preferences[KEY_RECORD]).record?.credentialType
|
||||
}
|
||||
|
||||
override suspend fun enroll(
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
if (decode(dataStore.data.first()[KEY_RECORD]).status != SupervisedParentAuthStatus.Missing) {
|
||||
return Result.failure(IllegalStateException("Parent access is already configured or unavailable."))
|
||||
}
|
||||
runCatching { enrollLocked(newSecret, credentialType) }
|
||||
}
|
||||
|
||||
override suspend fun verify(secret: CharArray): SupervisedParentAuthResult = processMutex.withLock {
|
||||
verifyLocked(secret, AuthTarget.ParentSecret)
|
||||
}
|
||||
|
||||
override suspend fun change(
|
||||
currentSecret: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
when (val verified = verifyLocked(currentSecret, AuthTarget.ParentSecret)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetWithRecoveryPhrase(
|
||||
recoveryPhrase: CharArray,
|
||||
newSecret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): Result<SupervisedParentEnrollment> = processMutex.withLock {
|
||||
val validation = validateNewSecret(newSecret, credentialType)
|
||||
if (!validation.valid) {
|
||||
return Result.failure(IllegalArgumentException(validation.message))
|
||||
}
|
||||
val record = decode(dataStore.data.first()[KEY_RECORD]).record
|
||||
?: return Result.failure(ParentAuthenticationException(SupervisedParentAuthResult.Missing))
|
||||
val normalizedRecovery = normalizeRecoveryPhrase(recoveryPhrase, record.recoveryFormat)
|
||||
try {
|
||||
when (val verified = verifyLocked(normalizedRecovery, AuthTarget.RecoveryCode)) {
|
||||
SupervisedParentAuthResult.Success -> runCatching { enrollLocked(newSecret, credentialType) }
|
||||
else -> Result.failure(ParentAuthenticationException(verified))
|
||||
}
|
||||
} finally {
|
||||
normalizedRecovery.fill('\u0000')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated escape hatch used by the parent controls.
|
||||
*
|
||||
* The app-global credential cannot be removed while leaving any supervised
|
||||
* policy enabled. Every policy is disabled, but its configuration is retained,
|
||||
* in the same transaction that removes the credential.
|
||||
*/
|
||||
suspend fun clearCredentialAndDisablePolicies(): Result<Unit> = processMutex.withLock {
|
||||
runCatching {
|
||||
SupervisedModeStore.forTesting(dataStore).disableAllAndRemoveCredential(KEY_RECORD)
|
||||
Unit
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun enrollLocked(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentEnrollment {
|
||||
require(credentialType != SupervisedParentCredentialType.Legacy)
|
||||
val recoveryChars = generateRecoveryPhrase().toCharArray()
|
||||
val parentSalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
val recoverySalt = ByteArray(SALT_BYTES).also(random::nextBytes)
|
||||
var parentVerifier = ByteArray(0)
|
||||
var recoveryVerifier = ByteArray(0)
|
||||
try {
|
||||
parentVerifier = derive(secret, parentSalt, iterations)
|
||||
recoveryVerifier = derive(recoveryChars, recoverySalt, iterations)
|
||||
val record = PersistedParentAuth(
|
||||
iterations = iterations,
|
||||
parentSalt = encode(parentSalt),
|
||||
parentVerifier = encode(parentVerifier),
|
||||
recoverySalt = encode(recoverySalt),
|
||||
recoveryVerifier = encode(recoveryVerifier),
|
||||
credentialType = credentialType,
|
||||
recoveryFormat = SupervisedRecoveryFormat.WordPhrase,
|
||||
)
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
return SupervisedParentEnrollment(recoveryChars.concatToString())
|
||||
} finally {
|
||||
recoveryChars.fill('\u0000')
|
||||
parentSalt.fill(0)
|
||||
recoverySalt.fill(0)
|
||||
parentVerifier.fill(0)
|
||||
recoveryVerifier.fill(0)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun verifyLocked(
|
||||
candidate: CharArray,
|
||||
target: AuthTarget,
|
||||
): SupervisedParentAuthResult {
|
||||
val decoded = decode(dataStore.data.first()[KEY_RECORD])
|
||||
val record = decoded.record ?: return when (decoded.status) {
|
||||
SupervisedParentAuthStatus.Missing -> SupervisedParentAuthResult.Missing
|
||||
else -> SupervisedParentAuthResult.Corrupt
|
||||
}
|
||||
val now = nowMillis()
|
||||
if (record.blockedUntilEpochMillis > now) {
|
||||
return SupervisedParentAuthResult.Throttled(record.blockedUntilEpochMillis - now)
|
||||
}
|
||||
|
||||
val saltText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentSalt
|
||||
AuthTarget.RecoveryCode -> record.recoverySalt
|
||||
}
|
||||
val verifierText = when (target) {
|
||||
AuthTarget.ParentSecret -> record.parentVerifier
|
||||
AuthTarget.RecoveryCode -> record.recoveryVerifier
|
||||
}
|
||||
val salt = decodeBytes(saltText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val expected = decodeBytes(verifierText) ?: return SupervisedParentAuthResult.Corrupt
|
||||
val actual = try {
|
||||
derive(candidate, salt, record.iterations)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to derive supervised parent verifier", error)
|
||||
return SupervisedParentAuthResult.Corrupt
|
||||
} finally {
|
||||
salt.fill(0)
|
||||
}
|
||||
val matches = try {
|
||||
MessageDigest.isEqual(expected, actual)
|
||||
} finally {
|
||||
expected.fill(0)
|
||||
actual.fill(0)
|
||||
}
|
||||
|
||||
if (matches) {
|
||||
if (record.failedAttempts != 0 || record.blockedUntilEpochMillis != 0L) {
|
||||
save(record.copy(failedAttempts = 0, blockedUntilEpochMillis = 0L))
|
||||
}
|
||||
return SupervisedParentAuthResult.Success
|
||||
}
|
||||
|
||||
val failures = (record.failedAttempts + 1).coerceAtMost(MAX_TRACKED_FAILURES)
|
||||
val delayMillis = backoffMillis(failures)
|
||||
save(
|
||||
record.copy(
|
||||
failedAttempts = failures,
|
||||
blockedUntilEpochMillis = if (delayMillis == 0L) 0L else now + delayMillis,
|
||||
),
|
||||
)
|
||||
return if (delayMillis == 0L) {
|
||||
SupervisedParentAuthResult.Invalid(
|
||||
attemptsBeforeDelay = (FAILURES_BEFORE_BACKOFF - failures).coerceAtLeast(0),
|
||||
)
|
||||
} else {
|
||||
SupervisedParentAuthResult.Throttled(delayMillis)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun save(record: PersistedParentAuth) {
|
||||
dataStore.edit { it[KEY_RECORD] = json.encodeToString(record) }
|
||||
}
|
||||
|
||||
private suspend fun derive(secret: CharArray, salt: ByteArray, rounds: Int): ByteArray =
|
||||
withContext(Dispatchers.Default) {
|
||||
val spec = PBEKeySpec(secret, salt, rounds, KEY_BITS)
|
||||
try {
|
||||
SecretKeyFactory.getInstance(KDF_ALGORITHM).generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodedRecord {
|
||||
if (raw.isNullOrBlank()) {
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Missing, null)
|
||||
}
|
||||
val record = runCatching { json.decodeFromString<PersistedParentAuth>(raw) }
|
||||
.getOrElse {
|
||||
Log.w(TAG, "Unable to decode supervised parent authentication; failing closed", it)
|
||||
return DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
val valid = record.version == RECORD_VERSION &&
|
||||
record.algorithm == KDF_ALGORITHM &&
|
||||
record.iterations in minimumAcceptedIterations..MAX_ACCEPTED_ITERATIONS &&
|
||||
decodeBytes(record.parentSalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.parentVerifier)?.size == KEY_BITS / 8 &&
|
||||
decodeBytes(record.recoverySalt)?.size == SALT_BYTES &&
|
||||
decodeBytes(record.recoveryVerifier)?.size == KEY_BITS / 8 &&
|
||||
record.failedAttempts in 0..MAX_TRACKED_FAILURES &&
|
||||
record.blockedUntilEpochMillis >= 0
|
||||
return if (valid) {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Configured, record)
|
||||
} else {
|
||||
DecodedRecord(SupervisedParentAuthStatus.Corrupt, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateRecoveryPhrase(): String {
|
||||
val available = RECOVERY_WORDS.toMutableList()
|
||||
val selected = buildList(RECOVERY_WORD_COUNT) {
|
||||
repeat(RECOVERY_WORD_COUNT) {
|
||||
add(available.removeAt(random.nextInt(available.size)))
|
||||
}
|
||||
}
|
||||
return selected.joinToString("-")
|
||||
}
|
||||
|
||||
private fun encode(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
|
||||
|
||||
private fun decodeBytes(value: String): ByteArray? =
|
||||
runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull()
|
||||
|
||||
private fun backoffMillis(failures: Int): Long = when (failures) {
|
||||
in 0 until FAILURES_BEFORE_BACKOFF -> 0L
|
||||
FAILURES_BEFORE_BACKOFF -> 30_000L
|
||||
FAILURES_BEFORE_BACKOFF + 1 -> 60_000L
|
||||
FAILURES_BEFORE_BACKOFF + 2 -> 120_000L
|
||||
FAILURES_BEFORE_BACKOFF + 3 -> 300_000L
|
||||
else -> MAX_BACKOFF_MILLIS
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class PersistedParentAuth(
|
||||
val version: Int = RECORD_VERSION,
|
||||
val algorithm: String = KDF_ALGORITHM,
|
||||
val iterations: Int,
|
||||
val parentSalt: String,
|
||||
val parentVerifier: String,
|
||||
val recoverySalt: String,
|
||||
val recoveryVerifier: String,
|
||||
val credentialType: SupervisedParentCredentialType = SupervisedParentCredentialType.Legacy,
|
||||
val recoveryFormat: SupervisedRecoveryFormat = SupervisedRecoveryFormat.LegacyCode,
|
||||
val failedAttempts: Int = 0,
|
||||
val blockedUntilEpochMillis: Long = 0L,
|
||||
)
|
||||
|
||||
private data class DecodedRecord(
|
||||
val status: SupervisedParentAuthStatus,
|
||||
val record: PersistedParentAuth?,
|
||||
)
|
||||
|
||||
private enum class AuthTarget { ParentSecret, RecoveryCode }
|
||||
|
||||
class ParentAuthenticationException(
|
||||
val authResult: SupervisedParentAuthResult,
|
||||
) : IllegalStateException("Parent authentication failed: $authResult")
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SupervisedParentAuth"
|
||||
private const val RECORD_VERSION = 1
|
||||
private const val KDF_ALGORITHM = "PBKDF2WithHmacSHA256"
|
||||
private const val DEFAULT_PBKDF2_ITERATIONS = 310_000
|
||||
private const val MIN_ACCEPTED_ITERATIONS = 100_000
|
||||
private const val MAX_ACCEPTED_ITERATIONS = 1_000_000
|
||||
private const val SALT_BYTES = 16
|
||||
private const val KEY_BITS = 256
|
||||
private const val FAILURES_BEFORE_BACKOFF = 5
|
||||
private const val MAX_TRACKED_FAILURES = 9
|
||||
private const val MAX_BACKOFF_MILLIS = 15 * 60_000L
|
||||
private const val RECOVERY_WORD_COUNT = 6
|
||||
private val KEY_RECORD = stringPreferencesKey("supervised_parent_auth_v1")
|
||||
private val processMutex = Mutex()
|
||||
|
||||
fun validateNewSecret(
|
||||
secret: CharArray,
|
||||
credentialType: SupervisedParentCredentialType,
|
||||
): SupervisedParentSecretValidation {
|
||||
if (secret.size > 64) {
|
||||
return SupervisedParentSecretValidation(false, "Use at most 64 characters.")
|
||||
}
|
||||
if (credentialType == SupervisedParentCredentialType.Pin) {
|
||||
return if (secret.size == 6 && secret.all(Char::isDigit)) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use exactly 6 digits.")
|
||||
}
|
||||
}
|
||||
return if (
|
||||
credentialType == SupervisedParentCredentialType.Password &&
|
||||
secret.size >= 8 && secret.any { !it.isWhitespace() }
|
||||
) {
|
||||
SupervisedParentSecretValidation(true)
|
||||
} else {
|
||||
SupervisedParentSecretValidation(false, "Use a password with at least 8 characters.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun normalizeRecoveryPhrase(
|
||||
value: CharArray,
|
||||
format: SupervisedRecoveryFormat,
|
||||
): CharArray = when (format) {
|
||||
SupervisedRecoveryFormat.LegacyCode -> value
|
||||
.filterNot { it == '-' || it.isWhitespace() }
|
||||
.joinToString("")
|
||||
.uppercase()
|
||||
.toCharArray()
|
||||
SupervisedRecoveryFormat.WordPhrase -> value.concatToString()
|
||||
.trim()
|
||||
.lowercase()
|
||||
.split(Regex("[-\\s]+"))
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString("-")
|
||||
.toCharArray()
|
||||
}
|
||||
|
||||
private val RECOVERY_WORDS = listOf(
|
||||
"acorn", "amber", "apple", "april", "arrow", "beach", "berry", "birch",
|
||||
"blue", "breeze", "brook", "button", "cabin", "cactus", "candle", "cedar",
|
||||
"cherry", "cloud", "clover", "cobalt", "comet", "coral", "cotton", "cove",
|
||||
"daisy", "dawn", "delta", "drift", "eagle", "earth", "ember", "fern",
|
||||
"field", "finch", "forest", "frost", "garden", "ginger", "glade", "gold",
|
||||
"grape", "green", "harbor", "hazel", "heron", "honey", "island", "ivory",
|
||||
"jade", "juniper", "kite", "lagoon", "lake", "lantern", "lark", "leaf",
|
||||
"lemon", "lilac", "lotus", "maple", "meadow", "mint", "moon", "morning",
|
||||
"moss", "oasis", "ocean", "olive", "orchid", "otter", "peach", "pearl",
|
||||
"pebble", "pine", "plum", "pond", "poppy", "quartz", "rain", "reed",
|
||||
"river", "robin", "rose", "saffron", "sage", "sand", "shell", "silver",
|
||||
"sky", "snow", "sparrow", "spring", "spruce", "star", "stone", "summer",
|
||||
"sun", "sunset", "teal", "thistle", "tide", "tulip", "valley", "violet",
|
||||
"willow", "wind", "winter", "wood", "wren", "yellow", "zephyr", "zinnia",
|
||||
"anchor", "bamboo", "copper", "cricket", "feather", "harvest", "marble", "ribbon",
|
||||
"rocket", "shadow", "timber", "whistle", "yarrow", "almond", "badger", "canvas",
|
||||
)
|
||||
|
||||
internal fun forTesting(
|
||||
dataStore: DataStore<Preferences>,
|
||||
iterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
minimumAcceptedIterations: Int = MIN_ACCEPTED_ITERATIONS,
|
||||
random: SecureRandom = SecureRandom(),
|
||||
nowMillis: () -> Long = System::currentTimeMillis,
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore(
|
||||
dataStore = dataStore,
|
||||
iterations = iterations,
|
||||
minimumAcceptedIterations = minimumAcceptedIterations,
|
||||
random = random,
|
||||
nowMillis = nowMillis,
|
||||
)
|
||||
|
||||
internal val recordKeyForTesting: Preferences.Key<String> = KEY_RECORD
|
||||
}
|
||||
}
|
||||
@@ -2436,6 +2436,10 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
java.util.IdentityHashMap<Throwable, Boolean>(),
|
||||
)
|
||||
while (current != null && seen.add(current)) {
|
||||
// Every 401 from an authenticated Dashboard route means the saved
|
||||
// browser/native session can no longer authorize this request. Older
|
||||
// gateways used `no_cookie`/`unauthenticated`; current builds may return
|
||||
// reason codes such as `session_expired`, or no structured body at all.
|
||||
if (current is DashboardHttpException && current.statusCode == 401) {
|
||||
return true
|
||||
}
|
||||
|
||||
+144
-11
@@ -119,6 +119,8 @@ class GatewayChatClient(
|
||||
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
||||
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
||||
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
|
||||
/** Test seam — compaction idle lease. Production keeps [COMPACTING_TIMEOUT_MS]. */
|
||||
private val compactingTimeoutMs: Long = COMPACTING_TIMEOUT_MS,
|
||||
/** Random source for ordinary reconnect full-jitter. */
|
||||
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
||||
) : GatewayProfileEditorClient {
|
||||
@@ -159,6 +161,19 @@ class GatewayChatClient(
|
||||
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
|
||||
private const val ASK_UNBOUNDED_TIMEOUT_MS = 600_000L
|
||||
|
||||
/**
|
||||
* Server-side context compaction summarizes the transcript through a
|
||||
* (possibly slow) model with NO deltas or tool events flowing until it
|
||||
* finishes — near the context ceiling that silence routinely exceeds
|
||||
* [TURN_TIMEOUT_MS], so the idle watchdog would `session.interrupt` a
|
||||
* healthy compression, roll back its work, and retrigger on the next
|
||||
* prompt forever. A `status.update` event with kind `compacting`
|
||||
* (emitted at compaction start, and periodically by newer gateways)
|
||||
* arms this longer leash instead; any regular event rearms
|
||||
* [TURN_TIMEOUT_MS].
|
||||
*/
|
||||
private const val COMPACTING_TIMEOUT_MS = 600_000L
|
||||
|
||||
private const val RPC_TIMEOUT_MS = 15_000L
|
||||
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
|
||||
|
||||
@@ -263,7 +278,7 @@ class GatewayChatClient(
|
||||
.newBuilder()
|
||||
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
||||
// reached over Tailscale (DERP cold start) can take longer to complete
|
||||
// the WS upgrade. A failed connect drops chat to the SSE fallback and a
|
||||
// the WS upgrade. A failed connect leaves Android on its Gateway owner and a
|
||||
// 5s cooldown, so give the first remote handshake room.
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.pingInterval(30, TimeUnit.SECONDS)
|
||||
@@ -548,6 +563,28 @@ class GatewayChatClient(
|
||||
val terminalRequired: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* One exact turn settled from authoritative session state may still receive
|
||||
* the terminal frame that was already in flight. Consume only that terminal
|
||||
* so it cannot be reported as a second unmatched completion. A subsequent
|
||||
* message.start clears the drain because it establishes the next turn on
|
||||
* the same live runtime.
|
||||
*/
|
||||
@Volatile
|
||||
private var settledTurnDrain: SettledTurnDrain? = null
|
||||
|
||||
private data class SettledTurnDrain(
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
)
|
||||
|
||||
private data class ActiveTurnLivenessProbe(
|
||||
val turn: GatewayTurn,
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
val progressGeneration: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates UI callbacks when the server starts a turn that has no matching
|
||||
* [sendTurn] call (for example a background-process completion). The
|
||||
@@ -677,6 +714,7 @@ class GatewayChatClient(
|
||||
): ActiveTurnHandle {
|
||||
val turn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
androidOwned = true,
|
||||
onTransportAccepted = onTransportAccepted,
|
||||
)
|
||||
// Warm = the connection-establish phases are skipped this turn (socket
|
||||
@@ -724,6 +762,10 @@ class GatewayChatClient(
|
||||
cleanupStagedAttachments(stagedImagePaths)
|
||||
return@launch
|
||||
}
|
||||
// A newly accepted Android send is a distinct generation on
|
||||
// this runtime. Its terminal must never be consumed by the
|
||||
// prior turn's optional late-terminal drain.
|
||||
settledTurnDrain = null
|
||||
activeTurn = turn
|
||||
turn.armWatchdog()
|
||||
// Generic `file.attach` uploads are staged artifacts, not
|
||||
@@ -758,7 +800,7 @@ class GatewayChatClient(
|
||||
// Once this turn's own events are flowing (or it already
|
||||
// finished), the prompt provably reached the server — a
|
||||
// slow, lost, or socket-severed ack must NOT preflight-fail
|
||||
// into the SSE fallback, which would resubmit the same
|
||||
// into a second transport, which would resubmit the same
|
||||
// prompt as a duplicate turn. Recovery belongs to the
|
||||
// stream: the watchdog and mid-turn rejoin own it.
|
||||
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
|
||||
@@ -1363,6 +1405,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1486,6 +1529,7 @@ class GatewayChatClient(
|
||||
boundTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1519,6 +1563,7 @@ class GatewayChatClient(
|
||||
val queuedTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
// recoverTurn is resumed on its caller's coroutine context;
|
||||
// ChatViewModel calls it from Main, so this admission runs
|
||||
@@ -2414,6 +2459,7 @@ class GatewayChatClient(
|
||||
} catch (error: Exception) {
|
||||
return GatewayActiveSessionsResult.TransientFailure(error)
|
||||
}
|
||||
val livenessProbe = captureActiveTurnLivenessProbe()
|
||||
val result = rpc(
|
||||
"session.active_list",
|
||||
buildJsonObject {
|
||||
@@ -2433,12 +2479,58 @@ class GatewayChatClient(
|
||||
val payload = result.getOrThrow()
|
||||
val rows = payload["sessions"] as? JsonArray
|
||||
?: throw GatewayRpcException("session.active_list returned no sessions array")
|
||||
GatewayActiveSessionsResult.Success(rows.map(::parseGatewayActiveSession))
|
||||
val sessions = rows.map(::parseGatewayActiveSession)
|
||||
reconcileActiveTurnFromSnapshot(livenessProbe, sessions)
|
||||
GatewayActiveSessionsResult.Success(sessions)
|
||||
} catch (parseError: Exception) {
|
||||
GatewayActiveSessionsResult.TransientFailure(parseError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture only a locally submitted/recovered turn. Merely observing an
|
||||
* exact session through the shared Gateway socket never grants Android
|
||||
* authority to settle Desktop/TUI work.
|
||||
*/
|
||||
private fun captureActiveTurnLivenessProbe(): ActiveTurnLivenessProbe? {
|
||||
val turn = activeTurn ?: return null
|
||||
val generation = turn.captureLivenessGeneration() ?: return null
|
||||
val storedId = storedSessionId ?: return null
|
||||
val liveId = liveSessionId ?: return null
|
||||
return ActiveTurnLivenessProbe(turn, storedId, liveId, generation)
|
||||
}
|
||||
|
||||
/**
|
||||
* `session.active_list` is process-wide, but a row naming both identifiers
|
||||
* already owned by this client is authoritative for that exact runtime.
|
||||
* Fence the delayed snapshot by turn identity and progress generation so an
|
||||
* old idle result cannot settle a newer turn or race newer live events.
|
||||
*/
|
||||
private fun reconcileActiveTurnFromSnapshot(
|
||||
probe: ActiveTurnLivenessProbe?,
|
||||
sessions: List<GatewayActiveSession>,
|
||||
) {
|
||||
probe ?: return
|
||||
if (activeTurn !== probe.turn ||
|
||||
storedSessionId != probe.storedSessionId ||
|
||||
liveSessionId != probe.liveSessionId
|
||||
) return
|
||||
val exact = sessions.singleOrNull { row ->
|
||||
row.runtimeSessionId == probe.liveSessionId &&
|
||||
row.storedSessionId == probe.storedSessionId
|
||||
} ?: return
|
||||
if (exact.status != GatewayActiveSessionStatus.Idle) return
|
||||
if (probe.turn.settleFromAuthoritativeSessionState(
|
||||
running = false,
|
||||
source = "session.active_list",
|
||||
expectedProgressGeneration = probe.progressGeneration,
|
||||
)
|
||||
) {
|
||||
if (activeTurn === probe.turn) activeTurn = null
|
||||
if (!AppForegroundTracker.isForeground.value) scheduleBackgroundClose()
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop one process owned by the current live gateway session. */
|
||||
suspend fun killProcess(processId: String): Result<Unit> {
|
||||
if (processId.isBlank()) {
|
||||
@@ -2831,6 +2923,7 @@ class GatewayChatClient(
|
||||
activeTurn = null
|
||||
backgroundTurns.clear()
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
unsolicitedTurnProvider = null
|
||||
coldPrewarmSessionReadyListener = null
|
||||
unmatchedTurnCompleteListener = null
|
||||
@@ -3267,6 +3360,7 @@ class GatewayChatClient(
|
||||
val requestedProfile = currentSessionProfile()
|
||||
if (requestedStoredId != null && requestedStoredId != storedSessionId) {
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
}
|
||||
if (
|
||||
liveSessionId != null &&
|
||||
@@ -3336,6 +3430,7 @@ class GatewayChatClient(
|
||||
storedSessionId = stored
|
||||
liveSessionProfile = requestedProfile
|
||||
if (cancelledTurnDrain?.storedSessionId != stored) cancelledTurnDrain = null
|
||||
if (settledTurnDrain?.storedSessionId != stored) settledTurnDrain = null
|
||||
turn.callbacks.onSessionId(stored)
|
||||
}
|
||||
|
||||
@@ -3713,6 +3808,7 @@ class GatewayChatClient(
|
||||
}
|
||||
dispatchProcessEvent(type, payload, eventSessionId)
|
||||
if (consumeCancelledTurnEvent(type, eventSessionId)) return
|
||||
if (consumeSettledTurnTerminal(type, eventSessionId)) return
|
||||
var turn = activeTurn
|
||||
if (turn == null && type == "message.start") {
|
||||
// Unsolicited turns are accepted only with an explicit exact live-
|
||||
@@ -4226,10 +4322,12 @@ class GatewayChatClient(
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
|
||||
private fun watchdogTimeoutFor(eventType: String): Long = when (eventType) {
|
||||
"clarify.request", "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
"sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
"approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
private fun watchdogTimeoutFor(eventType: String, payload: JsonObject? = null): Long = when {
|
||||
eventType == "clarify.request" || eventType == "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
eventType == "sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
eventType == "approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
eventType == "status.update" &&
|
||||
payload?.stringField("kind") == "compacting" -> compactingTimeoutMs
|
||||
else -> turnIdleTimeoutMs
|
||||
}
|
||||
|
||||
@@ -4237,6 +4335,7 @@ class GatewayChatClient(
|
||||
val callbacks: GatewayTurnCallbacks,
|
||||
dedupeAdjacentMessageStarts: Boolean = false,
|
||||
deferEvents: Boolean = false,
|
||||
private val androidOwned: Boolean = false,
|
||||
private val onTransportAccepted: () -> Unit = { },
|
||||
) : ActiveTurnHandle {
|
||||
private val mapper = GatewayEventMapper(callbacks, dedupeAdjacentMessageStarts)
|
||||
@@ -4263,6 +4362,7 @@ class GatewayChatClient(
|
||||
|
||||
private val rejoinAttempts = java.util.concurrent.atomic.AtomicInteger(0)
|
||||
private val transportAccepted = AtomicBoolean(false)
|
||||
private val progressGeneration = java.util.concurrent.atomic.AtomicLong(0L)
|
||||
|
||||
fun markTransportAccepted() {
|
||||
if (transportAccepted.compareAndSet(false, true)) {
|
||||
@@ -4339,6 +4439,7 @@ class GatewayChatClient(
|
||||
if (settledWithoutTerminalFrame) return
|
||||
if (type != "session.info") {
|
||||
started = true
|
||||
progressGeneration.incrementAndGet()
|
||||
markTransportAccepted()
|
||||
}
|
||||
tracer.mark("ttfe")
|
||||
@@ -4348,7 +4449,7 @@ class GatewayChatClient(
|
||||
// Reset on every event — long tool runs keep the turn alive.
|
||||
// Ask requests block with no further events, so they arm with
|
||||
// their own (longer) duration via watchdogTimeoutFor.
|
||||
armWatchdog(watchdogTimeoutFor(type))
|
||||
armWatchdog(watchdogTimeoutFor(type, payload))
|
||||
// Queue this immediately before the terminal callbacks. Both are
|
||||
// marshalled through the same dispatcher, preserving callback order
|
||||
// even when the WebSocket reader and reconnect coroutine differ.
|
||||
@@ -4368,10 +4469,20 @@ class GatewayChatClient(
|
||||
* exact turn has proved it went live. A pre-start `running=false`
|
||||
* heartbeat can race `prompt.submit` and is not a completion boundary.
|
||||
*/
|
||||
fun settleFromAuthoritativeSessionState(running: Boolean?, source: String): Boolean {
|
||||
fun captureLivenessGeneration(): Long? =
|
||||
if (androidOwned && started && !ended) progressGeneration.get() else null
|
||||
|
||||
fun settleFromAuthoritativeSessionState(
|
||||
running: Boolean?,
|
||||
source: String,
|
||||
expectedProgressGeneration: Long? = null,
|
||||
): Boolean {
|
||||
if (running != false || !started) return false
|
||||
val settled = synchronized(deferredEventLock) {
|
||||
if (ended) {
|
||||
if (ended ||
|
||||
(expectedProgressGeneration != null &&
|
||||
progressGeneration.get() != expectedProgressGeneration)
|
||||
) {
|
||||
false
|
||||
} else {
|
||||
settledWithoutTerminalFrame = true
|
||||
@@ -4382,6 +4493,7 @@ class GatewayChatClient(
|
||||
if (!settled) return false
|
||||
|
||||
disarmWatchdog()
|
||||
armSettledTurnDrain()
|
||||
Log.i(TAG, "Gateway turn settled from $source after missing terminal frame")
|
||||
callbacks.onReconcileRequired()
|
||||
callbacks.onComplete()
|
||||
@@ -4402,6 +4514,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4529,6 +4642,26 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
|
||||
private fun armSettledTurnDrain() {
|
||||
val storedId = storedSessionId ?: return
|
||||
val liveId = liveSessionId ?: return
|
||||
settledTurnDrain = SettledTurnDrain(storedId, liveId)
|
||||
}
|
||||
|
||||
/** Consume one late terminal from a turn already settled by session state. */
|
||||
private fun consumeSettledTurnTerminal(type: String, eventSessionId: String?): Boolean {
|
||||
val drain = settledTurnDrain ?: return false
|
||||
if (eventSessionId != drain.liveSessionId) return false
|
||||
if (type == "message.start") {
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
return false
|
||||
}
|
||||
if (type != "message.complete" && type != "error") return false
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
Log.d(TAG, "Ignored late terminal for gateway turn settled from session state")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun updateCancelledDrainLiveSession(storedId: String, liveId: String) {
|
||||
val drain = cancelledTurnDrain ?: return
|
||||
if (drain.storedSessionId == storedId) {
|
||||
@@ -4707,7 +4840,7 @@ data class GatewayAttachment(
|
||||
val sizeBytes: Long? = null,
|
||||
)
|
||||
|
||||
/** Connect/auth/submit failed before the turn started — safe to fall back to SSE. */
|
||||
/** Connect/auth/submit failed before the turn started; the caller retains transport ownership. */
|
||||
internal class GatewayPreflightException(message: String) : Exception(message)
|
||||
|
||||
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
||||
|
||||
@@ -91,26 +91,19 @@ enum class GatewayApprovalModeCapability {
|
||||
* is unit-testable without an AndroidViewModel. ConnectionViewModel
|
||||
* delegates here with its live state.
|
||||
*
|
||||
* Manual picks pass through untouched (ChatViewModel handles per-turn
|
||||
* fallback when a "gateway" pick can't serve a send); "auto" prefers the
|
||||
* gateway while the dashboard probe is unresolved or ready. A capability-
|
||||
* preferred SSE fallback is selected only after a definitive unavailable,
|
||||
* unsupported, or sign-in-required verdict.
|
||||
* Manual picks pass through untouched. "auto" follows the saved connection's
|
||||
* stable owner: Dashboard/Gateway for a standard connection, or the
|
||||
* capability-preferred SSE surface for a true API-only compatibility record.
|
||||
* Live reachability and sign-in state never change the owner of an open chat.
|
||||
*/
|
||||
fun resolveStreamingEndpointPreference(
|
||||
preference: String,
|
||||
gateway: GatewayAvailability,
|
||||
capabilities: ServerCapabilities,
|
||||
gatewayOwned: Boolean = true,
|
||||
): String = when (preference) {
|
||||
"sessions", "completions", "runs", "gateway" -> preference
|
||||
else -> if (
|
||||
gateway == GatewayAvailability.Ready ||
|
||||
gateway == GatewayAvailability.Unknown
|
||||
) {
|
||||
"gateway"
|
||||
} else {
|
||||
capabilities.preferredChatEndpoint()
|
||||
}
|
||||
else -> if (gatewayOwned) "gateway" else capabilities.preferredChatEndpoint()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -262,6 +262,11 @@ internal class HermesRuntimeBinder(
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.isStreaming.collect(connection::setChatStreaming)
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.conversationBinding.collect { binding ->
|
||||
connection.setActiveConversationTransport(binding.transport)
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.activeConnectionId,
|
||||
|
||||
@@ -136,6 +136,8 @@ import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
|
||||
import com.hermesandroid.relay.data.BuildFlavor
|
||||
import com.hermesandroid.relay.data.CandidateBuild
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.FeatureFlags
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
@@ -283,6 +285,8 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
connection: Connection?,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
streamingEndpoint: String = "auto",
|
||||
conversationOwner: SessionTransport? = null,
|
||||
): ChatRuntimeStatus {
|
||||
val capabilities = connection?.capabilities
|
||||
val gateway = when {
|
||||
@@ -298,7 +302,11 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
|
||||
else -> ChatTransportReadiness.Unavailable
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api)
|
||||
val owner = when (conversationOwner ?: connection?.chatTransportForPreference(streamingEndpoint)) {
|
||||
SessionTransport.SSE -> ChatTransportPath.ApiSse
|
||||
else -> ChatTransportPath.Gateway
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api, owner = owner)
|
||||
}
|
||||
|
||||
internal fun shouldSettleStartupUnreachable(
|
||||
@@ -360,7 +368,7 @@ internal fun resolveFooterRouteCandidate(
|
||||
*
|
||||
* Endpoint roles are operator and wire metadata, so an internal role such as
|
||||
* `authenticated_dashboard` must never leak into this constrained surface.
|
||||
* Gateway labels describe how the Dashboard is reached; API fallback keeps
|
||||
* Gateway labels describe how the Dashboard is reached; Direct API keeps
|
||||
* the route's ordinary transport label.
|
||||
*/
|
||||
internal fun resolveFooterRouteLabel(
|
||||
@@ -1593,6 +1601,7 @@ fun RelayApp() {
|
||||
// evidence alone left a window where the reveal showed the CTA for
|
||||
// the few hundred ms until the client-based health verdict landed.
|
||||
val chatReady by connectionViewModel.chatReady.collectAsState()
|
||||
val conversationOwner by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
var startupGateMinElapsed by remember { mutableStateOf(false) }
|
||||
var startupGateTimedOut by remember { mutableStateOf(false) }
|
||||
var startupGateReleased by remember { mutableStateOf(false) }
|
||||
@@ -1619,6 +1628,8 @@ fun RelayApp() {
|
||||
connection = activeConnection,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
apiHealth = apiHealth,
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
conversationOwner = conversationOwner,
|
||||
)
|
||||
// A Dashboard/Gateway-only connection is a complete standard Hermes
|
||||
// connection. Startup readiness follows the same transport-neutral
|
||||
@@ -2125,7 +2136,9 @@ fun RelayApp() {
|
||||
?: stringResource(R.string.status_no_route),
|
||||
)
|
||||
val transportStatus = resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
|
||||
streamingEndpoint,
|
||||
),
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCapabilities,
|
||||
)
|
||||
@@ -2967,7 +2980,12 @@ fun RelayApp() {
|
||||
}
|
||||
composable(Screen.AdvancedSettings.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
LaunchedEffect(Unit) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
AdvancedSettingsScreen(
|
||||
supervisedPolicy = supervisedPolicy,
|
||||
@@ -2998,7 +3016,12 @@ fun RelayApp() {
|
||||
}
|
||||
composable(Screen.SupervisedControls.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
LaunchedEffect(Unit) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SupervisedControlsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
|
||||
@@ -138,12 +138,10 @@ internal fun sanitizeSupervisedChatRouteArgs(
|
||||
}
|
||||
}
|
||||
|
||||
/** A disabled policy may become active only after an enrolled credential succeeds. */
|
||||
/** A disabled policy may become active only after the app-specific parent credential succeeds. */
|
||||
internal fun mayEnableSupervisedMode(
|
||||
policy: SupervisedModePolicy,
|
||||
deviceSecure: Boolean,
|
||||
deviceCredentialConfirmed: Boolean,
|
||||
parentCredentialConfirmed: Boolean,
|
||||
): Boolean = !policy.enabled &&
|
||||
policy.isConfigured &&
|
||||
deviceSecure &&
|
||||
deviceCredentialConfirmed
|
||||
parentCredentialConfirmed
|
||||
|
||||
+1
-1
@@ -613,7 +613,7 @@ private fun CapabilityRow(
|
||||
|
||||
/**
|
||||
* Advanced compatibility and override content:
|
||||
* - optional direct API fallback URL/key
|
||||
* - optional Direct API URL/key
|
||||
* - explicit direct Relay endpoint override/test
|
||||
* - allow-insecure-connections development toggle
|
||||
*
|
||||
|
||||
+20
-46
@@ -21,9 +21,9 @@ import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
|
||||
enum class ChatTransportTier(val endpointId: String, val label: String) {
|
||||
Gateway("gateway", "⚡ Gateway"),
|
||||
Sessions("sessions", "📡 Sessions"),
|
||||
Completions("completions", "Completions"),
|
||||
Runs("runs", "Runs"),
|
||||
Sessions("sessions", "Direct API"),
|
||||
Completions("completions", "Direct API"),
|
||||
Runs("runs", "Direct API"),
|
||||
Offline("offline", "offline"),
|
||||
}
|
||||
|
||||
@@ -67,18 +67,6 @@ fun resolveChatTransportStatus(
|
||||
detail = "No reachable Hermes chat transport is available.",
|
||||
)
|
||||
|
||||
fun sseFallback(gatewayReason: String): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline(gatewayReason)
|
||||
val tier = preferredAvailableSseTier(serverCapabilities)
|
||||
?: return offline(gatewayReason)
|
||||
return ChatTransportStatus(
|
||||
tier = tier,
|
||||
tone = ChatTransportTone.Fallback,
|
||||
reason = "$gatewayReason → ${tier.plainName()}",
|
||||
detail = "${tier.detailText()} Using this as the fallback while Gateway is unavailable.",
|
||||
)
|
||||
}
|
||||
|
||||
fun manualSse(tier: ChatTransportTier, supported: Boolean): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline()
|
||||
return if (supported) {
|
||||
@@ -94,23 +82,17 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
|
||||
return when (preference) {
|
||||
"auto" -> when {
|
||||
"auto", "gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "auto → Gateway (best)",
|
||||
reason = "Gateway connected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "Gateway selected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
else -> unavailable(
|
||||
ChatTransportTier.Gateway,
|
||||
gatewayFallbackReason(gatewayAvailability),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
|
||||
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
|
||||
@@ -119,42 +101,34 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
}
|
||||
|
||||
private fun preferredAvailableSseTier(capabilities: ServerCapabilities): ChatTransportTier? =
|
||||
when {
|
||||
capabilities.sessionsChatStream -> ChatTransportTier.Sessions
|
||||
capabilities.portable -> ChatTransportTier.Completions
|
||||
capabilities.runs -> ChatTransportTier.Runs
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun gatewayFallbackReason(availability: GatewayAvailability): String =
|
||||
when (availability) {
|
||||
GatewayAvailability.SignInRequired -> "gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "checking gateway"
|
||||
GatewayAvailability.Ready -> "gateway ready"
|
||||
GatewayAvailability.SignInRequired -> "Gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "Gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "Gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "Checking Gateway"
|
||||
GatewayAvailability.Ready -> "Gateway ready"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.plainName(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway -> "Gateway"
|
||||
ChatTransportTier.Sessions -> "Sessions"
|
||||
ChatTransportTier.Completions -> "Completions"
|
||||
ChatTransportTier.Runs -> "Runs"
|
||||
ChatTransportTier.Sessions -> "Direct API"
|
||||
ChatTransportTier.Completions -> "Direct API"
|
||||
ChatTransportTier.Runs -> "Direct API"
|
||||
ChatTransportTier.Offline -> "offline"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.detailText(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway ->
|
||||
"Gateway uses the dashboard WebSocket /api/ws for live thinking and rich tool events."
|
||||
"Hermes Chat uses the signed-in Dashboard connection."
|
||||
ChatTransportTier.Sessions ->
|
||||
"Sessions uses /api/sessions/{id}/chat/stream with server-side session history."
|
||||
"Direct API compatibility chat with server-side session history."
|
||||
ChatTransportTier.Completions ->
|
||||
"Completions uses OpenAI-compatible SSE at /v1/chat/completions."
|
||||
"Direct API compatibility chat."
|
||||
ChatTransportTier.Runs ->
|
||||
"Runs uses /v1/runs plus streamed run events."
|
||||
"Direct API compatibility chat with streamed run events."
|
||||
ChatTransportTier.Offline ->
|
||||
"No chat transport is reachable."
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ import java.net.URI
|
||||
* Settings → Gateways. Hermes setup starts with the one Dashboard address
|
||||
* the phone can open, probes public `/api/status`, and lets advertised
|
||||
* capabilities select authentication. A separate public sign-in URL is never
|
||||
* universally required. API fallback, Relay pairing, and extra LAN/Tailscale
|
||||
* universally required. Direct API, Relay pairing, and extra LAN/Tailscale
|
||||
* routes remain explicit advanced paths.
|
||||
*
|
||||
* Steps:
|
||||
|
||||
@@ -847,7 +847,7 @@ internal fun routeSurfaceSecurityPresentation(
|
||||
val label = when (surface) {
|
||||
EndpointSurface.Standard,
|
||||
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
||||
EndpointSurface.Api -> "API fallback"
|
||||
EndpointSurface.Api -> "Direct API"
|
||||
EndpointSurface.Relay -> "Relay tools"
|
||||
}
|
||||
val securityVerdict = classifySurfaceSecurity(
|
||||
|
||||
@@ -25,6 +25,8 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||
@@ -41,7 +43,7 @@ fun RelayStatusStrip(
|
||||
/** Optional security marker rendered just before the route label. */
|
||||
securityGlyph: (@Composable () -> Unit)? = null,
|
||||
/**
|
||||
* When true, the strip shows an amber "Reconnecting…" cue in place of the
|
||||
* When true, the strip shows an amber "Relay reconnecting" cue in place of the
|
||||
* route label. This is where a **routine** in-progress relay reconnect
|
||||
* surfaces — the top chrome stays empty so chat content never shifts.
|
||||
*/
|
||||
@@ -108,7 +110,7 @@ fun RelayStatusStrip(
|
||||
}
|
||||
|
||||
/**
|
||||
* Amber "· Reconnecting…" cue with a softly pulsing dot. This is the *only*
|
||||
* Amber "Relay reconnecting" cue with a softly pulsing dot. This is the *only*
|
||||
* surface for a routine in-progress relay reconnect — the top of the app stays
|
||||
* empty (chat/agent status rides the chat header subtitle) so nothing shifts.
|
||||
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
|
||||
@@ -132,7 +134,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
|
||||
.background(RelayRefresh.Amber),
|
||||
)
|
||||
Text(
|
||||
text = "Reconnecting…",
|
||||
text = stringResource(R.string.settings_relay_reconnecting),
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Amber,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -401,7 +401,7 @@ internal fun SessionPathDetails(
|
||||
* Vertical "transport path" ladder, basic → best:
|
||||
* Completions → Runs → Sessions → Gateway. The active tier is filled +
|
||||
* highlighted; tiers the server doesn't expose render muted; the resolver's
|
||||
* reason ("auto → Gateway (best)" / "gateway unavailable → Sessions") is shown
|
||||
* owner/readiness reason ("Gateway connected" / "Gateway unavailable") is shown
|
||||
* beneath. Uses the same [resolveChatTransportStatus] the status badge does, so
|
||||
* the drawer and the badge can never disagree.
|
||||
*/
|
||||
|
||||
@@ -778,7 +778,7 @@ fun ChatSettingsScreen(
|
||||
serverCaps,
|
||||
) {
|
||||
resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = resolvedStreamingEndpoint,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCaps,
|
||||
)
|
||||
|
||||
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
@@ -83,6 +84,7 @@ import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
||||
import com.hermesandroid.relay.viewmodel.resolveActiveChatTransport
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -476,12 +478,16 @@ private fun ActiveOverview(
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val usingApiFallback = apiReachable && gatewayAvailability in setOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
)
|
||||
val currentRouteUrl = if (usingApiFallback) {
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
// Observe the binding as well as the saved preference so a restored
|
||||
// conversation immediately presents its actual owner.
|
||||
val activeConversationTransport by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
val usingDirectApi = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport,
|
||||
connection = connection,
|
||||
preference = streamingEndpoint,
|
||||
) == SessionTransport.SSE
|
||||
val currentRouteUrl = if (usingDirectApi) {
|
||||
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
||||
} else {
|
||||
effectiveDashboardUrl
|
||||
@@ -492,23 +498,29 @@ private fun ActiveOverview(
|
||||
effectiveDashboardUrl = currentRouteUrl,
|
||||
)
|
||||
val routeStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unknown ||
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
|
||||
(!usingDirectApi && gatewayAvailability == GatewayAvailability.Unknown) ||
|
||||
(usingDirectApi && apiHealth == ConnectionViewModel.HealthStatus.Probing) ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
|
||||
}
|
||||
val chatStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unreachable && !apiReachable ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unreachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
usingDirectApi && !apiReachable && apiHealth != ConnectionViewModel.HealthStatus.Probing ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
}
|
||||
|
||||
+22
-7
@@ -62,6 +62,7 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
import com.hermesandroid.relay.data.isDashboardOnlyRoute
|
||||
@@ -386,6 +387,12 @@ private fun ConnectionListCard(
|
||||
} else {
|
||||
connection.resolvedDashboardUrl
|
||||
}
|
||||
val selectedProfile: Profile? = if (activeConnectionViewModel != null) {
|
||||
val profile by activeConnectionViewModel.selectedProfile.collectAsState()
|
||||
profile
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val presentedConnection = activeConnection ?: connection
|
||||
val presentation = resolveGatewayCardPresentation(
|
||||
connection = presentedConnection,
|
||||
@@ -429,13 +436,7 @@ private fun ConnectionListCard(
|
||||
modifier = Modifier
|
||||
.size(10.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(
|
||||
if (presentation.status == GatewayCardStatus.Online) {
|
||||
com.hermesandroid.relay.ui.theme.RelayRefresh.Green
|
||||
} else {
|
||||
MaterialTheme.colorScheme.outline
|
||||
},
|
||||
),
|
||||
.background(gatewayStatusColor(presentation.status)),
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Dns,
|
||||
@@ -484,6 +485,20 @@ private fun ConnectionListCard(
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (isActive) {
|
||||
Text(
|
||||
text = listOfNotNull(
|
||||
stringResource(R.string.conn_info_profile),
|
||||
selectedProfile?.name?.takeIf { it.isNotBlank() }
|
||||
?: stringResource(R.string.settings_server_default),
|
||||
selectedProfile?.model?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onSwitch != null || isSwitching || justSwitched) {
|
||||
OutlinedButton(
|
||||
|
||||
+863
@@ -0,0 +1,863 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Intent
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Backspace
|
||||
import androidx.compose.material.icons.filled.Dialpad
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthResult
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStore
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthenticator
|
||||
import com.hermesandroid.relay.data.SupervisedParentCredentialType
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentVerifyDialog(
|
||||
store: SupervisedParentAuthenticator,
|
||||
onDismiss: () -> Unit,
|
||||
onVerified: () -> Unit,
|
||||
onUseRecoveryCode: () -> Unit,
|
||||
) {
|
||||
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
|
||||
var selectedLegacyType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
|
||||
?: selectedLegacyType
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun verify(candidateText: String) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
scope.launch {
|
||||
val candidate = candidateText.toCharArray()
|
||||
val result = try {
|
||||
store.verify(candidate)
|
||||
} finally {
|
||||
candidate.fill('\u0000')
|
||||
}
|
||||
busy = false
|
||||
when (result) {
|
||||
SupervisedParentAuthResult.Success -> onVerified()
|
||||
else -> error = result.toUserMessage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ParentAuthDialogSurface(
|
||||
step = null,
|
||||
onBack = if (storedType == SupervisedParentCredentialType.Legacy && inputType != null) {
|
||||
{ selectedLegacyType = null; error = null }
|
||||
} else {
|
||||
onDismiss
|
||||
},
|
||||
) {
|
||||
when (inputType) {
|
||||
SupervisedParentCredentialType.Pin -> PinEntryScreen(
|
||||
title = "Parent PIN",
|
||||
subtitle = "Enter your 6-digit PIN.",
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::verify,
|
||||
onUseRecovery = onUseRecoveryCode,
|
||||
)
|
||||
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
|
||||
busy = busy,
|
||||
error = error,
|
||||
onSubmit = ::verify,
|
||||
onUseRecovery = onUseRecoveryCode,
|
||||
)
|
||||
else -> CredentialChoiceScreen(
|
||||
title = "How do you enter your parent credential?",
|
||||
subtitle = "This existing setup predates the PIN/password choice.",
|
||||
onSelected = { selectedLegacyType = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentSetupDialog(
|
||||
store: SupervisedParentAuthenticator,
|
||||
currentSecretRequired: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onEnrolled: (SupervisedParentEnrollment) -> Unit,
|
||||
) {
|
||||
val storedType by store.credentialTypeFlow.collectAsState(initial = null)
|
||||
var stage by remember(currentSecretRequired) {
|
||||
mutableStateOf(if (currentSecretRequired) SetupStage.VerifyCurrent else SetupStage.Choose)
|
||||
}
|
||||
var legacyInputType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
var currentSecret by remember { mutableStateOf("") }
|
||||
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun enroll(newSecretText: String) {
|
||||
val type = credentialType ?: return
|
||||
busy = true
|
||||
scope.launch {
|
||||
val current = currentSecret.toCharArray()
|
||||
val replacement = newSecretText.toCharArray()
|
||||
val result = try {
|
||||
if (currentSecretRequired) store.change(current, replacement, type)
|
||||
else store.enroll(replacement, type)
|
||||
} finally {
|
||||
current.fill('\u0000')
|
||||
replacement.fill('\u0000')
|
||||
}
|
||||
busy = false
|
||||
result.fold(onSuccess = onEnrolled, onFailure = { error = it.toUserMessage() })
|
||||
}
|
||||
}
|
||||
|
||||
fun verifyCurrent(candidateText: String) {
|
||||
busy = true
|
||||
scope.launch {
|
||||
val candidate = candidateText.toCharArray()
|
||||
val result = try { store.verify(candidate) } finally { candidate.fill('\u0000') }
|
||||
busy = false
|
||||
if (result == SupervisedParentAuthResult.Success) {
|
||||
currentSecret = candidateText
|
||||
error = null
|
||||
stage = SetupStage.Choose
|
||||
} else {
|
||||
error = result.toUserMessage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val backAction: () -> Unit = when (stage) {
|
||||
SetupStage.VerifyCurrent, SetupStage.Choose -> onDismiss
|
||||
SetupStage.Pin, SetupStage.Password -> {
|
||||
{ stage = SetupStage.Choose; credentialType = null; error = null }
|
||||
}
|
||||
}
|
||||
val step = when (stage) {
|
||||
SetupStage.VerifyCurrent -> 1 to 3
|
||||
SetupStage.Choose -> if (currentSecretRequired) 2 to 3 else 1 to 2
|
||||
SetupStage.Pin, SetupStage.Password -> if (currentSecretRequired) 3 to 3 else 2 to 2
|
||||
}
|
||||
|
||||
ParentAuthDialogSurface(step = step, onBack = backAction) {
|
||||
when (stage) {
|
||||
SetupStage.VerifyCurrent -> {
|
||||
val inputType = storedType?.takeUnless { it == SupervisedParentCredentialType.Legacy }
|
||||
?: legacyInputType
|
||||
when (inputType) {
|
||||
SupervisedParentCredentialType.Pin -> PinEntryScreen(
|
||||
title = "Current parent PIN",
|
||||
subtitle = "Confirm before changing parent access.",
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::verifyCurrent,
|
||||
)
|
||||
SupervisedParentCredentialType.Password -> PasswordVerifyScreen(
|
||||
title = "Current parent password",
|
||||
busy = busy,
|
||||
error = error,
|
||||
onSubmit = ::verifyCurrent,
|
||||
)
|
||||
else -> CredentialChoiceScreen(
|
||||
title = "How do you enter the current credential?",
|
||||
subtitle = "Choose the input that matches the existing setup.",
|
||||
onSelected = { legacyInputType = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
SetupStage.Choose -> CredentialChoiceScreen(
|
||||
title = if (currentSecretRequired) "Choose new parent access" else "Choose parent access",
|
||||
subtitle = "Pick one way to unlock parent settings. You can change it later.",
|
||||
onSelected = {
|
||||
credentialType = it
|
||||
stage = if (it == SupervisedParentCredentialType.Pin) SetupStage.Pin else SetupStage.Password
|
||||
},
|
||||
)
|
||||
SetupStage.Pin -> PinSetupScreen(
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::enroll,
|
||||
)
|
||||
SetupStage.Password -> PasswordSetupScreen(
|
||||
busy = busy,
|
||||
error = error,
|
||||
onComplete = ::enroll,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentRecoveryDialog(
|
||||
store: SupervisedParentAuthenticator,
|
||||
onDismiss: () -> Unit,
|
||||
onReset: (SupervisedParentEnrollment) -> Unit,
|
||||
) {
|
||||
var stage by remember { mutableStateOf(RecoveryStage.Phrase) }
|
||||
var recoveryPhrase by remember { mutableStateOf("") }
|
||||
var credentialType by remember { mutableStateOf<SupervisedParentCredentialType?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun reset(newSecretText: String) {
|
||||
val type = credentialType ?: return
|
||||
busy = true
|
||||
scope.launch {
|
||||
val recovery = recoveryPhrase.toCharArray()
|
||||
val replacement = newSecretText.toCharArray()
|
||||
val result = try {
|
||||
store.resetWithRecoveryPhrase(recovery, replacement, type)
|
||||
} finally {
|
||||
recovery.fill('\u0000')
|
||||
replacement.fill('\u0000')
|
||||
}
|
||||
busy = false
|
||||
result.fold(onSuccess = onReset, onFailure = { error = it.toUserMessage() })
|
||||
}
|
||||
}
|
||||
|
||||
val step = when (stage) {
|
||||
RecoveryStage.Phrase -> 1 to 3
|
||||
RecoveryStage.Choose -> 2 to 3
|
||||
RecoveryStage.Pin, RecoveryStage.Password -> 3 to 3
|
||||
}
|
||||
ParentAuthDialogSurface(
|
||||
step = step,
|
||||
onBack = when (stage) {
|
||||
RecoveryStage.Phrase -> onDismiss
|
||||
RecoveryStage.Choose -> ({ stage = RecoveryStage.Phrase })
|
||||
RecoveryStage.Pin, RecoveryStage.Password -> ({ stage = RecoveryStage.Choose })
|
||||
},
|
||||
) {
|
||||
when (stage) {
|
||||
RecoveryStage.Phrase -> RecoveryPhraseInputScreen(
|
||||
value = recoveryPhrase,
|
||||
error = error,
|
||||
onValueChange = { recoveryPhrase = it; error = null },
|
||||
onContinue = { stage = RecoveryStage.Choose },
|
||||
)
|
||||
RecoveryStage.Choose -> CredentialChoiceScreen(
|
||||
title = "Choose new parent access",
|
||||
subtitle = "Your recovery phrase will be replaced after reset.",
|
||||
onSelected = {
|
||||
credentialType = it
|
||||
stage = if (it == SupervisedParentCredentialType.Pin) RecoveryStage.Pin
|
||||
else RecoveryStage.Password
|
||||
},
|
||||
)
|
||||
RecoveryStage.Pin -> PinSetupScreen(busy = busy, error = error, onComplete = ::reset)
|
||||
RecoveryStage.Password -> PasswordSetupScreen(busy = busy, error = error, onComplete = ::reset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentRecoveryCodeDialog(
|
||||
enrollment: SupervisedParentEnrollment,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val clipboard = remember(context) {
|
||||
context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
}
|
||||
ParentAuthDialogSurface(step = 3 to 3, onBack = null) {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
enrollment = enrollment,
|
||||
onShare = {
|
||||
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = "text/plain"
|
||||
putExtra(Intent.EXTRA_TEXT, enrollment.recoveryPhrase)
|
||||
}
|
||||
context.startActivity(Intent.createChooser(intent, "Share recovery phrase"))
|
||||
},
|
||||
onCopy = {
|
||||
clipboard.setPrimaryClip(
|
||||
ClipData.newPlainText("Parent recovery phrase", enrollment.recoveryPhrase),
|
||||
)
|
||||
},
|
||||
onDone = onDone,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ParentAuthDialogSurface(
|
||||
step: Pair<Int, Int>?,
|
||||
onBack: (() -> Unit)?,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Dialog(
|
||||
onDismissRequest = { onBack?.invoke() },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
ParentAuthScreenSurface(step = step, onBack = onBack, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ParentAuthScreenSurface(
|
||||
step: Pair<Int, Int>?,
|
||||
onBack: (() -> Unit)?,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.systemBarsPadding()
|
||||
.imePadding()
|
||||
.padding(horizontal = 24.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().height(64.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (onBack != null) {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
} else {
|
||||
Spacer(Modifier.size(48.dp))
|
||||
}
|
||||
step?.let { (current, total) ->
|
||||
Row(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
repeat(total) { index ->
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(width = 46.dp, height = 4.dp)
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (index < current) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"$current of $total",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} ?: Spacer(Modifier.weight(1f))
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.TopCenter,
|
||||
) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun CredentialChoiceScreen(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onSelected: (SupervisedParentCredentialType) -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 28.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(title, subtitle)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
CredentialChoiceRow(
|
||||
icon = { Icon(Icons.Filled.Dialpad, contentDescription = null) },
|
||||
title = "Use a PIN",
|
||||
subtitle = "Fast on this phone · 6 digits",
|
||||
onClick = { onSelected(SupervisedParentCredentialType.Pin) },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
CredentialChoiceRow(
|
||||
icon = { Icon(Icons.Filled.Lock, contentDescription = null) },
|
||||
title = "Use a password",
|
||||
subtitle = "Works with password managers · 8+ characters",
|
||||
onClick = { onSelected(SupervisedParentCredentialType.Password) },
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
"PIN and password are separate choices.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CredentialChoiceRow(
|
||||
icon: @Composable () -> Unit,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 18.dp, vertical = 18.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(48.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) { icon() }
|
||||
}
|
||||
Column(Modifier.weight(1f).padding(horizontal = 16.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Text("›", fontSize = 30.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PinEntryScreen(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onComplete: (String) -> Unit,
|
||||
onUseRecovery: (() -> Unit)? = null,
|
||||
) {
|
||||
var pin by remember { mutableStateOf("") }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(title, subtitle)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PinDots(pin.length)
|
||||
Spacer(Modifier.height(26.dp))
|
||||
NumericKeypad(
|
||||
enabled = !busy,
|
||||
onDigit = { digit ->
|
||||
if (pin.length < 6) {
|
||||
val next = pin + digit
|
||||
pin = next
|
||||
if (next.length == 6) onComplete(next)
|
||||
}
|
||||
},
|
||||
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
|
||||
)
|
||||
AuthError(error)
|
||||
onUseRecovery?.let {
|
||||
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PinSetupScreen(
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onComplete: (String) -> Unit,
|
||||
) {
|
||||
var firstPin by remember { mutableStateOf<String?>(null) }
|
||||
var pin by remember(firstPin) { mutableStateOf("") }
|
||||
var localError by remember { mutableStateOf<String?>(null) }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(
|
||||
if (firstPin == null) "Create a parent PIN" else "Confirm parent PIN",
|
||||
if (firstPin == null) "Choose a 6-digit PIN." else "Enter the same 6 digits again.",
|
||||
)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PinDots(pin.length)
|
||||
Spacer(Modifier.height(26.dp))
|
||||
NumericKeypad(
|
||||
enabled = !busy,
|
||||
onDigit = { digit ->
|
||||
if (pin.length < 6) {
|
||||
val next = pin + digit
|
||||
pin = next
|
||||
if (next.length == 6) {
|
||||
if (firstPin == null) {
|
||||
firstPin = next
|
||||
} else if (firstPin == next) {
|
||||
onComplete(next)
|
||||
} else {
|
||||
localError = "The PINs do not match. Try again."
|
||||
firstPin = null
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onBackspace = { if (pin.isNotEmpty()) pin = pin.dropLast(1) },
|
||||
)
|
||||
AuthError(localError ?: error)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NumericKeypad(
|
||||
enabled: Boolean,
|
||||
onDigit: (String) -> Unit,
|
||||
onBackspace: () -> Unit,
|
||||
) {
|
||||
val rows = listOf(listOf("1", "2", "3"), listOf("4", "5", "6"), listOf("7", "8", "9"))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
rows.forEach { row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
row.forEach { digit -> KeypadButton(digit, enabled) { onDigit(digit) } }
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Spacer(Modifier.size(width = 92.dp, height = 58.dp))
|
||||
KeypadButton("0", enabled) { onDigit("0") }
|
||||
Surface(
|
||||
modifier = Modifier.size(width = 92.dp, height = 58.dp).clickable(enabled = enabled, onClick = onBackspace),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.AutoMirrored.Filled.Backspace, contentDescription = "Delete digit")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KeypadButton(label: String, enabled: Boolean, onClick: () -> Unit) {
|
||||
Button(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = Modifier.size(width = 92.dp, height = 58.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
) {
|
||||
Text(label, style = MaterialTheme.typography.headlineSmall)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PinDots(count: Int) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
repeat(6) { index ->
|
||||
Box(
|
||||
Modifier
|
||||
.size(22.dp)
|
||||
.clip(CircleShape)
|
||||
.then(
|
||||
if (index < count) Modifier.background(MaterialTheme.colorScheme.primary)
|
||||
else Modifier.border(2.dp, MaterialTheme.colorScheme.outline, CircleShape),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PasswordSetupScreen(
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onComplete: (String) -> Unit,
|
||||
) {
|
||||
var password by remember { mutableStateOf("") }
|
||||
var confirmation by remember { mutableStateOf("") }
|
||||
var reveal by remember { mutableStateOf(false) }
|
||||
var localError by remember { mutableStateOf<String?>(null) }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading("Create a parent password", "Use 8 or more characters.")
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PasswordField("Password", password, { password = it; localError = null }, reveal, { reveal = !reveal })
|
||||
Spacer(Modifier.height(12.dp))
|
||||
PasswordField("Confirm password", confirmation, { confirmation = it; localError = null }, reveal, { reveal = !reveal }, ImeAction.Done)
|
||||
AuthError(localError ?: error)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
enabled = !busy && password.isNotEmpty() && confirmation.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = {
|
||||
when {
|
||||
password != confirmation -> localError = "The passwords do not match."
|
||||
!SupervisedParentAuthStore.validateNewSecret(
|
||||
password.toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).valid -> localError = "Use a password with at least 8 characters."
|
||||
else -> onComplete(password)
|
||||
}
|
||||
},
|
||||
) { Text(if (busy) "Saving…" else "Continue") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PasswordVerifyScreen(
|
||||
title: String = "Parent password",
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onSubmit: (String) -> Unit,
|
||||
onUseRecovery: (() -> Unit)? = null,
|
||||
) {
|
||||
var password by remember { mutableStateOf("") }
|
||||
var reveal by remember { mutableStateOf(false) }
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(title, "Enter your password.")
|
||||
Spacer(Modifier.height(28.dp))
|
||||
PasswordField("Password", password, { password = it }, reveal, { reveal = !reveal }, ImeAction.Done)
|
||||
AuthError(error)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
enabled = !busy && password.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = { onSubmit(password) },
|
||||
) { Text(if (busy) "Checking…" else "Unlock") }
|
||||
onUseRecovery?.let {
|
||||
TextButton(enabled = !busy, onClick = it) { Text("Use recovery phrase") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PasswordField(
|
||||
label: String,
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
reveal: Boolean,
|
||||
onReveal: () -> Unit,
|
||||
imeAction: ImeAction = ImeAction.Next,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = { if (it.length <= 64) onValueChange(it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text(label) },
|
||||
visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = onReveal) {
|
||||
Icon(
|
||||
if (reveal) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
|
||||
contentDescription = if (reveal) "Hide password" else "Show password",
|
||||
)
|
||||
}
|
||||
},
|
||||
singleLine = true,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RecoveryPhraseInputScreen(
|
||||
value: String,
|
||||
error: String?,
|
||||
onValueChange: (String) -> Unit,
|
||||
onContinue: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading("Enter recovery phrase", "Paste or type the six words.")
|
||||
Spacer(Modifier.height(28.dp))
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text("Recovery phrase") },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done),
|
||||
minLines = 2,
|
||||
)
|
||||
AuthError(error)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
enabled = value.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = onContinue,
|
||||
) { Text("Continue") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SupervisedParentRecoveryCodeContent(
|
||||
enrollment: SupervisedParentEnrollment,
|
||||
onShare: () -> Unit = {},
|
||||
onCopy: () -> Unit = {},
|
||||
onDone: () -> Unit = {},
|
||||
) {
|
||||
val words = enrollment.recoveryPhrase.split('-')
|
||||
val displayPhrase = if (words.size == 6) {
|
||||
words.take(3).joinToString("-") + "\n" + words.drop(3).joinToString("-")
|
||||
} else {
|
||||
enrollment.recoveryPhrase
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
AuthHeading(
|
||||
"Save your recovery phrase",
|
||||
"This is the only way to reset parent access if you forget it.",
|
||||
)
|
||||
Spacer(Modifier.height(28.dp))
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
SelectionContainer {
|
||||
Text(
|
||||
displayPhrase,
|
||||
modifier = Modifier.padding(20.dp),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
style = MaterialTheme.typography.titleMedium.copy(lineHeight = 28.sp),
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Text(
|
||||
"Send it somewhere parent-only, then delete the message or saved copy from this phone.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Button(
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = onShare,
|
||||
) {
|
||||
Icon(Icons.Filled.Share, contentDescription = null)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text("Share")
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedButton(
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
onClick = onCopy,
|
||||
) { Text("Copy phrase") }
|
||||
TextButton(onClick = onDone) { Text("Done") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AuthHeading(title: String, subtitle: String) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AuthError(error: String?) {
|
||||
error?.let {
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
|
||||
private fun SupervisedParentAuthResult.toUserMessage(): String = when (this) {
|
||||
SupervisedParentAuthResult.Success -> ""
|
||||
is SupervisedParentAuthResult.Invalid -> if (attemptsBeforeDelay > 0) {
|
||||
"Incorrect parent credential. $attemptsBeforeDelay attempts remain before a delay."
|
||||
} else {
|
||||
"Incorrect parent credential."
|
||||
}
|
||||
is SupervisedParentAuthResult.Throttled -> {
|
||||
val seconds = ((retryAfterMillis + 999L) / 1_000L).coerceAtLeast(1)
|
||||
"Too many attempts. Try again in $seconds seconds."
|
||||
}
|
||||
SupervisedParentAuthResult.Missing -> "Parent access has not been set up."
|
||||
SupervisedParentAuthResult.Corrupt -> "Parent access data is unavailable. Supervised Mode remains locked."
|
||||
}
|
||||
|
||||
private fun Throwable.toUserMessage(): String = when (this) {
|
||||
is IllegalArgumentException -> message ?: "The new parent credential is not valid."
|
||||
is SupervisedParentAuthStore.ParentAuthenticationException -> authResult.toUserMessage()
|
||||
else -> "Parent access could not be updated. Try again."
|
||||
}
|
||||
|
||||
private enum class SetupStage { VerifyCurrent, Choose, Pin, Password }
|
||||
private enum class RecoveryStage { Phrase, Choose, Pin, Password }
|
||||
+240
-54
@@ -1,8 +1,5 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -52,7 +49,9 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -65,6 +64,9 @@ import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStatus
|
||||
import com.hermesandroid.relay.data.SupervisedParentAuthStore
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.data.SupervisedSessionActions
|
||||
import com.hermesandroid.relay.data.SupervisedVisibilityPreset
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAvailablePets
|
||||
@@ -77,6 +79,7 @@ import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.gradientBorder
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* The settings surface available while supervised mode is locked.
|
||||
@@ -100,28 +103,29 @@ fun SupervisedSettingsScreen(
|
||||
val effectiveProfile by connectionViewModel.effectiveDisplayProfile.collectAsState()
|
||||
val profileAlias by connectionViewModel.profileDisplayAlias.collectAsState()
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
|
||||
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
|
||||
initialValue = null,
|
||||
key1 = parentAuthStore,
|
||||
) {
|
||||
parentAuthStore.statusFlow.collect { value = it }
|
||||
}
|
||||
var authError by remember { mutableStateOf<String?>(null) }
|
||||
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
|
||||
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
|
||||
var showAbout by remember { mutableStateOf(false) }
|
||||
|
||||
val credentialLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
}
|
||||
}
|
||||
|
||||
fun requestParentAccess() {
|
||||
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
|
||||
val intent = keyguard?.createConfirmDeviceCredentialIntent(
|
||||
"Parent access",
|
||||
"Unlock full Hermes settings and supervised-mode controls. Device credentials verify an enrolled device user, not a distinct parent identity.",
|
||||
)
|
||||
if (intent == null) {
|
||||
authError = "Set a device screen lock before using parent access."
|
||||
} else {
|
||||
credentialLauncher.launch(intent)
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
|
||||
SupervisedParentAuthStatus.Missing -> {
|
||||
authError = "This legacy supervised policy has no app-specific parent credential and stays locked. " +
|
||||
"Reset this app's local data, reconnect, and configure parent access before enabling Supervised Mode again."
|
||||
}
|
||||
SupervisedParentAuthStatus.Corrupt -> {
|
||||
authError = "Parent access data is unavailable. Supervised Mode remains locked."
|
||||
}
|
||||
null -> authError = "Parent access is still loading."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +190,7 @@ fun SupervisedSettingsScreen(
|
||||
SupervisedNavigationRow(
|
||||
icon = Icons.Filled.Lock,
|
||||
title = "Parent access",
|
||||
subtitle = "Unlock full settings with the device screen lock",
|
||||
subtitle = "Unlock full settings with the app parent PIN or password",
|
||||
onClick = ::requestParentAccess,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
@@ -217,6 +221,38 @@ fun SupervisedSettingsScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
when (parentAuthDialog) {
|
||||
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onVerified = {
|
||||
parentAuthDialog = null
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
},
|
||||
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
|
||||
)
|
||||
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onReset = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
else -> Unit
|
||||
}
|
||||
pendingEnrollment?.let { enrollment ->
|
||||
SupervisedParentRecoveryCodeDialog(
|
||||
enrollment = enrollment,
|
||||
onDone = {
|
||||
pendingEnrollment = null
|
||||
authError = null
|
||||
onParentAccessGranted()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Restricted appearance editor backed by the supervised policy, not global theme settings. */
|
||||
@@ -293,42 +329,41 @@ fun SupervisedControlsScreen(
|
||||
onReturnToSupervisedView: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val keyguardManager = remember(context) {
|
||||
context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
|
||||
val parentAuthStore = remember(context) { SupervisedParentAuthStore(context) }
|
||||
val parentAuthStatus by produceState<SupervisedParentAuthStatus?>(
|
||||
initialValue = null,
|
||||
key1 = parentAuthStore,
|
||||
) {
|
||||
parentAuthStore.statusFlow.collect { value = it }
|
||||
}
|
||||
val deviceSecure = keyguardManager?.isDeviceSecure == true
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
var showProfilePicker by remember { mutableStateOf(false) }
|
||||
var sessionActionsExpanded by remember { mutableStateOf(false) }
|
||||
var enableAuthError by remember { mutableStateOf<String?>(null) }
|
||||
var enableRequested by remember { mutableStateOf(false) }
|
||||
val enableCredentialLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result ->
|
||||
val shouldEnable = enableRequested && mayEnableSupervisedMode(
|
||||
policy = policy,
|
||||
deviceSecure = deviceSecure,
|
||||
deviceCredentialConfirmed = result.resultCode == Activity.RESULT_OK,
|
||||
)
|
||||
enableRequested = false
|
||||
if (shouldEnable) {
|
||||
enableAuthError = null
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
}
|
||||
var parentAuthDialog by remember { mutableStateOf<ParentAuthDialog?>(null) }
|
||||
var pendingEnrollment by remember { mutableStateOf<SupervisedParentEnrollment?>(null) }
|
||||
var enableAfterEnrollment by remember { mutableStateOf(false) }
|
||||
var showRemoveCredentialConfirm by remember { mutableStateOf(false) }
|
||||
var removeCredentialBusy by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun requestFirstEnable() {
|
||||
val intent = keyguardManager?.createConfirmDeviceCredentialIntent(
|
||||
"Enable supervised mode",
|
||||
"Confirm with an enrolled device credential. This does not verify a distinct parent identity.",
|
||||
)
|
||||
if (!deviceSecure || intent == null) {
|
||||
enableAuthError = "Set a secure device screen lock before enabling supervised mode."
|
||||
if (!policy.isConfigured) {
|
||||
enableAuthError = "Choose an agent profile before enabling Supervised Mode."
|
||||
return
|
||||
}
|
||||
enableRequested = true
|
||||
enableCredentialLauncher.launch(intent)
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Missing -> {
|
||||
enableAfterEnrollment = true
|
||||
parentAuthDialog = ParentAuthDialog.Setup
|
||||
}
|
||||
SupervisedParentAuthStatus.Configured -> parentAuthDialog = ParentAuthDialog.Verify
|
||||
SupervisedParentAuthStatus.Corrupt -> {
|
||||
enableAuthError = "Parent access data is unavailable. Reset local app data before enabling Supervised Mode."
|
||||
}
|
||||
null -> enableAuthError = "Parent access is still loading."
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
@@ -360,14 +395,18 @@ fun SupervisedControlsScreen(
|
||||
subtitle = when {
|
||||
policy.pinnedProfileName.isNullOrBlank() ->
|
||||
"Choose an agent profile before enabling"
|
||||
!deviceSecure ->
|
||||
"Set a device screen lock before enabling"
|
||||
parentAuthStatus == SupervisedParentAuthStatus.Missing ->
|
||||
"Set an app-specific parent PIN or password"
|
||||
else ->
|
||||
"Show only the approved Android chat surfaces"
|
||||
},
|
||||
checked = policy.enabled,
|
||||
enabled = policy.enabled ||
|
||||
(!policy.pinnedProfileName.isNullOrBlank() && deviceSecure),
|
||||
(!policy.pinnedProfileName.isNullOrBlank() &&
|
||||
parentAuthStatus in setOf(
|
||||
SupervisedParentAuthStatus.Missing,
|
||||
SupervisedParentAuthStatus.Configured,
|
||||
)),
|
||||
onCheckedChange = { enabled ->
|
||||
if (enabled) requestFirstEnable()
|
||||
else onPolicyChange(policy.copy(enabled = false))
|
||||
@@ -404,7 +443,7 @@ fun SupervisedControlsScreen(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
"Android device credentials authenticate an enrolled device user; they do not establish a separate parent identity. Use a parent-only device credential or managed-device policy where that distinction matters.",
|
||||
"Parent access uses an app-specific PIN or password, separate from the supervised user's Android screen lock and biometrics.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -713,14 +752,42 @@ fun SupervisedControlsScreen(
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Column(Modifier.padding(start = 12.dp)) {
|
||||
Text("Device authentication", style = MaterialTheme.typography.titleSmall)
|
||||
Text("App parent credential", style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
"Full features require the device screen lock. This verifies an enrolled device user, not a distinct parent identity.",
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Configured -> "A parent PIN or password is configured for this app."
|
||||
SupervisedParentAuthStatus.Missing -> "Set a parent PIN or password before enabling Supervised Mode."
|
||||
SupervisedParentAuthStatus.Corrupt -> "Parent access data is unavailable and fails closed."
|
||||
null -> "Loading parent access…"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
when (parentAuthStatus) {
|
||||
SupervisedParentAuthStatus.Missing -> OutlinedButton(
|
||||
onClick = {
|
||||
enableAfterEnrollment = false
|
||||
parentAuthDialog = ParentAuthDialog.Setup
|
||||
},
|
||||
) { Text("Set parent PIN or password") }
|
||||
SupervisedParentAuthStatus.Configured -> {
|
||||
OutlinedButton(onClick = { parentAuthDialog = ParentAuthDialog.Change }) {
|
||||
Text("Change parent PIN or password")
|
||||
}
|
||||
TextButton(onClick = { parentAuthDialog = ParentAuthDialog.Recovery }) {
|
||||
Text("Reset with recovery phrase")
|
||||
}
|
||||
TextButton(onClick = { showRemoveCredentialConfirm = true }) {
|
||||
Text(
|
||||
"Remove parent credential",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
HorizontalDivider()
|
||||
SupervisedSwitchRow(
|
||||
title = "Relock when the app leaves the screen",
|
||||
@@ -794,6 +861,118 @@ fun SupervisedControlsScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showRemoveCredentialConfirm) {
|
||||
RemoveParentCredentialDialog(
|
||||
busy = removeCredentialBusy,
|
||||
onDismiss = { showRemoveCredentialConfirm = false },
|
||||
onConfirm = {
|
||||
removeCredentialBusy = true
|
||||
scope.launch {
|
||||
val result = parentAuthStore.clearCredentialAndDisablePolicies()
|
||||
removeCredentialBusy = false
|
||||
result.fold(
|
||||
onSuccess = {
|
||||
showRemoveCredentialConfirm = false
|
||||
enableAuthError = null
|
||||
onBack()
|
||||
},
|
||||
onFailure = {
|
||||
enableAuthError = "Parent access could not be removed. Try again."
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
when (parentAuthDialog) {
|
||||
ParentAuthDialog.Verify -> SupervisedParentVerifyDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onVerified = {
|
||||
parentAuthDialog = null
|
||||
enableAuthError = null
|
||||
if (mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
},
|
||||
onUseRecoveryCode = { parentAuthDialog = ParentAuthDialog.Recovery },
|
||||
)
|
||||
ParentAuthDialog.Setup -> SupervisedParentSetupDialog(
|
||||
store = parentAuthStore,
|
||||
currentSecretRequired = false,
|
||||
onDismiss = {
|
||||
parentAuthDialog = null
|
||||
enableAfterEnrollment = false
|
||||
},
|
||||
onEnrolled = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
ParentAuthDialog.Change -> SupervisedParentSetupDialog(
|
||||
store = parentAuthStore,
|
||||
currentSecretRequired = true,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onEnrolled = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
ParentAuthDialog.Recovery -> SupervisedParentRecoveryDialog(
|
||||
store = parentAuthStore,
|
||||
onDismiss = { parentAuthDialog = null },
|
||||
onReset = { enrollment ->
|
||||
parentAuthDialog = null
|
||||
pendingEnrollment = enrollment
|
||||
},
|
||||
)
|
||||
null -> Unit
|
||||
}
|
||||
pendingEnrollment?.let { enrollment ->
|
||||
SupervisedParentRecoveryCodeDialog(
|
||||
enrollment = enrollment,
|
||||
onDone = {
|
||||
pendingEnrollment = null
|
||||
enableAuthError = null
|
||||
if (enableAfterEnrollment && mayEnableSupervisedMode(policy, parentCredentialConfirmed = true)) {
|
||||
onPolicyChange(policy.copy(enabled = true))
|
||||
}
|
||||
enableAfterEnrollment = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun RemoveParentCredentialDialog(
|
||||
busy: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!busy) onDismiss() },
|
||||
title = { Text("Remove parent credential?") },
|
||||
text = {
|
||||
Text(
|
||||
"This disables Supervised Mode on every connection and removes the app-wide " +
|
||||
"PIN or password and recovery phrase. Your supervised settings and toggles are kept. " +
|
||||
"Hermes sessions and server history are not deleted.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = !busy, onClick = onConfirm) {
|
||||
Text(
|
||||
if (busy) "Removing…" else "Remove",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(enabled = !busy, onClick = onDismiss) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -984,6 +1163,13 @@ private fun sessionActionsSummary(actions: SupervisedSessionActions): String = w
|
||||
else -> "${actions.enabledCount} of ${SupervisedSessionActions.TOTAL} allowed"
|
||||
}
|
||||
|
||||
private enum class ParentAuthDialog {
|
||||
Verify,
|
||||
Setup,
|
||||
Change,
|
||||
Recovery,
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SessionActionSwitch(
|
||||
title: String,
|
||||
|
||||
@@ -28,25 +28,26 @@ sealed interface ChatRuntimeStatus {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve chat health in product priority order:
|
||||
* Gateway primary, API/SSE fallback, pending connection, then unavailable.
|
||||
* Resolve chat health for the active conversation owner only. A reachable
|
||||
* sibling endpoint cannot make a signed-out or unreachable conversation look
|
||||
* connected.
|
||||
*/
|
||||
fun resolveChatRuntimeStatus(
|
||||
gateway: ChatTransportReadiness,
|
||||
apiSse: ChatTransportReadiness,
|
||||
): ChatRuntimeStatus = when {
|
||||
gateway == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.Gateway,
|
||||
fallback = false,
|
||||
)
|
||||
|
||||
apiSse == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.ApiSse,
|
||||
fallback = true,
|
||||
)
|
||||
|
||||
gateway == ChatTransportReadiness.Connecting ||
|
||||
apiSse == ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
|
||||
else -> ChatRuntimeStatus.Unavailable
|
||||
owner: ChatTransportPath = ChatTransportPath.Gateway,
|
||||
): ChatRuntimeStatus {
|
||||
val readiness = when (owner) {
|
||||
ChatTransportPath.Gateway -> gateway
|
||||
ChatTransportPath.ApiSse -> apiSse
|
||||
}
|
||||
return when (readiness) {
|
||||
ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = owner,
|
||||
fallback = false,
|
||||
)
|
||||
ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
ChatTransportReadiness.NotConfigured,
|
||||
ChatTransportReadiness.Unavailable -> ChatRuntimeStatus.Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +291,7 @@ internal data class ResolvedGatewayActiveSessions(
|
||||
val ambiguousForCurrent: Boolean,
|
||||
)
|
||||
|
||||
/** Resolve process-wide runtime rows without ever inventing a profile owner. */
|
||||
/** Resolve process-wide runtime rows without ever inventing an ambiguous profile owner. */
|
||||
internal fun resolveGatewayActiveSessions(
|
||||
sessions: List<GatewayActiveSession>,
|
||||
directory: Set<SessionActivityOwner>,
|
||||
@@ -316,6 +316,8 @@ internal fun resolveGatewayActiveSessions(
|
||||
currentRuntimeId == row.runtimeSessionId &&
|
||||
currentOwner.storedSessionId == row.storedSessionId -> currentOwner
|
||||
explicitProfile != null && candidates.size == 1 -> candidates.single()
|
||||
explicitProfile == null && currentOwner != null && candidates.singleOrNull() == currentOwner ->
|
||||
currentOwner
|
||||
else -> null
|
||||
}
|
||||
if (owner == null) {
|
||||
@@ -2121,9 +2123,12 @@ class ChatViewModel : ViewModel() {
|
||||
* RelayApp pushes the resolved value) prefers an EventSource-compatible
|
||||
* OpenAI chat path instead of assuming `/v1/runs` is an SSE stream.
|
||||
*/
|
||||
private var resolvedStreamingEndpoint: String = "completions"
|
||||
|
||||
var streamingEndpoint: String = "completions"
|
||||
set(value) {
|
||||
field = value
|
||||
resolvedStreamingEndpoint = value
|
||||
field = endpointForConversationOwner(value)
|
||||
// Only the gateway transport auto-names sessions server-side
|
||||
// (tui_gateway runs the turn in a HermesCLI child that calls
|
||||
// agent.title_generator.maybe_auto_title). The api_server SSE/runs/
|
||||
@@ -2138,12 +2143,19 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE endpoint used when a "gateway" turn can't run (gateway unreachable,
|
||||
* sign-in expired, attachments present). Wired from RelayApp alongside
|
||||
* [streamingEndpoint] as the capability-resolved SSE preference; never
|
||||
* "auto" or "gateway".
|
||||
* Capability-resolved endpoint for an explicitly API-owned compatibility
|
||||
* conversation. It never acts as a fallback for a Gateway-owned chat.
|
||||
*/
|
||||
var sseFallbackEndpoint: String = "completions"
|
||||
set(value) {
|
||||
field = value
|
||||
if (
|
||||
conversationBinding.value.transport == SessionTransport.SSE &&
|
||||
resolvedStreamingEndpoint == "gateway"
|
||||
) {
|
||||
streamingEndpoint = resolvedStreamingEndpoint
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gateway chat transport (dashboard `/api/ws` — live thinking). Owned and
|
||||
@@ -3184,6 +3196,7 @@ class ChatViewModel : ViewModel() {
|
||||
) {
|
||||
val handler = chatHandler ?: return
|
||||
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) return
|
||||
val contextKey = activeProfileContextKey
|
||||
gatewayHistoryReconcileJob?.cancel()
|
||||
gatewayHistoryReconcileJob = viewModelScope.launch {
|
||||
val expected = expectedAssistantText?.trim()?.takeIf { it.isNotEmpty() }
|
||||
@@ -3216,7 +3229,28 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
val transcriptSnapshot = handler.messages.value
|
||||
val serverMessages = loadGatewaySessionHistory(storedSessionId)
|
||||
val serverMessages = try {
|
||||
loadGatewaySessionHistory(
|
||||
sessionId = storedSessionId,
|
||||
requireProfileScope = true,
|
||||
)
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// A live completion is already visible and settled locally.
|
||||
// History auth loss must retain that transcript and promote
|
||||
// the existing sign-in recovery instead of escaping this
|
||||
// Main-scope coroutine and crashing the app.
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == contextKey &&
|
||||
handler.currentSessionId.value == storedSessionId
|
||||
) {
|
||||
publishHistoryLoadFailure(storedSessionId, e)
|
||||
}
|
||||
gatewayHistoryReconcileJob = null
|
||||
return@launch
|
||||
}
|
||||
if (chatHandler !== handler || handler.currentSessionId.value != storedSessionId) {
|
||||
return@launch
|
||||
}
|
||||
@@ -3728,6 +3762,17 @@ class ChatViewModel : ViewModel() {
|
||||
private val bindingDisplayProfile: Profile?
|
||||
get() = conversationBinding.value.displayProfile
|
||||
|
||||
private fun endpointForConversationOwner(candidate: String): String =
|
||||
when (conversationBinding.value.transport) {
|
||||
SessionTransport.GATEWAY -> "gateway"
|
||||
SessionTransport.SSE -> if (candidate == "gateway") sseFallbackEndpoint else candidate
|
||||
null -> candidate
|
||||
}
|
||||
|
||||
private fun reapplyConversationTransportAffinity() {
|
||||
streamingEndpoint = resolvedStreamingEndpoint
|
||||
}
|
||||
|
||||
/**
|
||||
* Profile namespace owned by the conversation currently on screen. Opening a
|
||||
* row from the global All Profiles browser binds this state first; the UI
|
||||
@@ -3740,6 +3785,7 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
private fun clearOpenedSessionOwner() {
|
||||
conversationBindingController.releaseExplicitOwner()
|
||||
reapplyConversationTransportAffinity()
|
||||
}
|
||||
|
||||
/** Process ownership is profile+session scoped; stored IDs alone are not globally unique. */
|
||||
@@ -4656,6 +4702,7 @@ class ChatViewModel : ViewModel() {
|
||||
lastSessionRefreshSuccessNanos = 0L
|
||||
_sessionListUnavailable.value = false
|
||||
conversationBindingController.reset()
|
||||
reapplyConversationTransportAffinity()
|
||||
exitProvisionalThread()
|
||||
relayCapabilityGeneration.incrementAndGet()
|
||||
relayReasoningCapabilities.value = emptyMap()
|
||||
@@ -4818,6 +4865,8 @@ class ChatViewModel : ViewModel() {
|
||||
} else {
|
||||
sessionProfileNameProvider()
|
||||
}
|
||||
val targetTransport = sessionId?.let(SessionTransport::forSessionId)
|
||||
?: SessionTransport.forEndpoint(resolvedStreamingEndpoint)
|
||||
if (explicitBinding) {
|
||||
val accepted = conversationBindingController.openExplicit(
|
||||
contextKey = contextKey,
|
||||
@@ -4825,6 +4874,7 @@ class ChatViewModel : ViewModel() {
|
||||
sessionId = sessionId,
|
||||
displayProfile = explicitDisplayProfile,
|
||||
lockedProfileToken = lockedProfileNameProvider(),
|
||||
transport = targetTransport,
|
||||
)
|
||||
if (!accepted) return
|
||||
} else if (reconciliation) {
|
||||
@@ -4832,6 +4882,7 @@ class ChatViewModel : ViewModel() {
|
||||
contextKey = contextKey,
|
||||
profileName = targetProfileName,
|
||||
sessionId = sessionId,
|
||||
transport = targetTransport,
|
||||
)
|
||||
if (!accepted) {
|
||||
_initialChatSettled.value = true
|
||||
@@ -4842,8 +4893,10 @@ class ChatViewModel : ViewModel() {
|
||||
contextKey = contextKey,
|
||||
profileName = targetProfileName,
|
||||
sessionId = sessionId,
|
||||
transport = targetTransport,
|
||||
)
|
||||
}
|
||||
reapplyConversationTransportAffinity()
|
||||
activateSessionActivityScope()
|
||||
handler.activeAgentName = currentAgentDisplayName()
|
||||
if (
|
||||
@@ -5401,6 +5454,7 @@ class ChatViewModel : ViewModel() {
|
||||
// recovery state. Preserve cached history and
|
||||
// mark the directory unavailable without also
|
||||
// emitting a generic turn/error toast.
|
||||
dashboardSignInRequiredHandler?.invoke()
|
||||
} else if (scoped != null) {
|
||||
// The shared API list belongs to the launch/default
|
||||
// database. Preserve the current profile's rows and
|
||||
@@ -5423,7 +5477,9 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
retryUnavailable = true
|
||||
retryReadiness = retryReadiness || !e.isSessionReadTimeout()
|
||||
if (!e.isDashboardSignInRequiredFailure()) {
|
||||
if (e.isDashboardSignInRequiredFailure()) {
|
||||
dashboardSignInRequiredHandler?.invoke()
|
||||
} else {
|
||||
emitError(
|
||||
e,
|
||||
context = if (profileSessionLister != null) {
|
||||
@@ -5600,7 +5656,10 @@ class ChatViewModel : ViewModel() {
|
||||
// profile/context so an All Profiles conversation becomes a fresh
|
||||
// draft for that same owner instead of falling back to the globally
|
||||
// restored default profile.
|
||||
conversationBindingController.startFreshDraft()
|
||||
conversationBindingController.startFreshDraft(
|
||||
SessionTransport.forEndpoint(resolvedStreamingEndpoint),
|
||||
)
|
||||
reapplyConversationTransportAffinity()
|
||||
exitProvisionalThread()
|
||||
|
||||
// Gateway turns continue as detached siblings; SSE remains exclusive.
|
||||
@@ -5859,6 +5918,7 @@ class ChatViewModel : ViewModel() {
|
||||
val contextKey = activeProfileContextKey
|
||||
val profileName = currentSessionProfileName()
|
||||
conversationBindingController.switchSession(sessionId)
|
||||
reapplyConversationTransportAffinity()
|
||||
|
||||
handler.setSessionId(sessionId)
|
||||
publishQueuedMessages()
|
||||
@@ -5975,6 +6035,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
if (handler.currentSessionId.value == null) {
|
||||
conversationBindingController.switchSession(null)
|
||||
reapplyConversationTransportAffinity()
|
||||
onSessionChanged?.invoke(null)
|
||||
}
|
||||
|
||||
@@ -6201,10 +6262,10 @@ class ChatViewModel : ViewModel() {
|
||||
val client = apiClient
|
||||
if (
|
||||
(streamingEndpoint != "gateway" && client == null) ||
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null && client == null)
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null)
|
||||
) {
|
||||
val message = if (streamingEndpoint == "gateway") {
|
||||
"Gateway is unavailable and no API fallback is configured for this connection."
|
||||
"This chat belongs to the Hermes Dashboard. Sign in or reconnect, then retry."
|
||||
} else {
|
||||
"API fallback is not configured for this connection."
|
||||
}
|
||||
@@ -6312,9 +6373,15 @@ class ChatViewModel : ViewModel() {
|
||||
?: return VoiceMessageSubmissionResult.Rejected("Hermes chat is not ready.")
|
||||
val client = apiClient
|
||||
if ((streamingEndpoint != "gateway" && client == null) ||
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null && client == null)
|
||||
(streamingEndpoint == "gateway" && gatewayClient == null)
|
||||
) {
|
||||
return VoiceMessageSubmissionResult.Rejected("Hermes is not connected.")
|
||||
return VoiceMessageSubmissionResult.Rejected(
|
||||
if (streamingEndpoint == "gateway") {
|
||||
"This chat needs the Hermes Dashboard. Sign in or reconnect, then retry."
|
||||
} else {
|
||||
"The direct API connection is unavailable."
|
||||
},
|
||||
)
|
||||
}
|
||||
if (activeStream != null || streamRecovery != null || handler.isStreaming.value) {
|
||||
return VoiceMessageSubmissionResult.Rejected(
|
||||
@@ -7854,11 +7921,22 @@ class ChatViewModel : ViewModel() {
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (handler.currentSessionId.value == expectedSessionId) {
|
||||
// Recovery completion has already settled the
|
||||
// local turn. Keep it visible and route an
|
||||
// expired Dashboard session to sign-in.
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == checkpoint.contextKey &&
|
||||
handler.currentSessionId.value == expectedSessionId
|
||||
) {
|
||||
publishHistoryLoadFailure(expectedSessionId, e)
|
||||
}
|
||||
} finally {
|
||||
if (handler.currentSessionId.value == expectedSessionId) {
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == checkpoint.contextKey &&
|
||||
handler.currentSessionId.value == expectedSessionId
|
||||
) {
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(expectedSessionId)
|
||||
}
|
||||
@@ -9727,6 +9805,7 @@ class ChatViewModel : ViewModel() {
|
||||
// tool.complete. The structured reload recovers those calls without ever
|
||||
// parsing assistant prose and retains the profile-aware history boundary.
|
||||
val sid = handler.currentSessionId.value
|
||||
val historyContextKey = activeProfileContextKey
|
||||
// A turn that ended in an error (gateway ❌ lifecycle → "Error" badge)
|
||||
// has NO assistant message persisted server-side, so reconciling the
|
||||
// server transcript would WIPE the just-shown error bubble (the user
|
||||
@@ -9769,7 +9848,11 @@ class ChatViewModel : ViewModel() {
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (handler.currentSessionId.value == sid) {
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == historyContextKey &&
|
||||
handler.currentSessionId.value == sid
|
||||
) {
|
||||
publishHistoryLoadFailure(sid, e)
|
||||
}
|
||||
} finally {
|
||||
@@ -9779,8 +9862,14 @@ class ChatViewModel : ViewModel() {
|
||||
// is persisted, so a brand-new chat would otherwise stay missing
|
||||
// from the drawer (carried only by the optimistic row) until a
|
||||
// manual reload. By message.complete the dashboard list includes it.
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(sid)
|
||||
if (
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == historyContextKey &&
|
||||
handler.currentSessionId.value == sid
|
||||
) {
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(sid)
|
||||
}
|
||||
drainQueue()
|
||||
}
|
||||
}
|
||||
@@ -10059,12 +10148,11 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
}
|
||||
|
||||
// SSE dispatch shared by the three HTTP endpoints AND the gateway
|
||||
// branch's per-turn fallback (gateway unreachable / not the resolved
|
||||
// transport). Warns once per dispatch about any attachment it can't carry.
|
||||
// SSE dispatch shared by the three explicit API compatibility endpoints.
|
||||
// Warns once per dispatch about any attachment it can't carry.
|
||||
fun dispatchSse(endpoint: String): ActiveTurnHandle? {
|
||||
val sseClient = client ?: run {
|
||||
onErrorCb("Gateway unavailable and no API fallback is configured.")
|
||||
onErrorCb("The direct API connection is unavailable.")
|
||||
return null
|
||||
}
|
||||
val prepared = prepareTextTransportAttachments(message, attachments.orEmpty())
|
||||
@@ -10209,13 +10297,13 @@ class ChatViewModel : ViewModel() {
|
||||
activeStream = when {
|
||||
effectiveEndpoint != "gateway" -> dispatchSse(effectiveEndpoint)
|
||||
|
||||
// Gateway turns upload ALL attachments via their typed upstream
|
||||
// RPC (image.attach_bytes / pdf.attach / file.attach), matching the
|
||||
// desktop client. Only a missing gateway client forces the per-turn
|
||||
// SSE fallback (where non-image attachments are not upstream-
|
||||
// recognized and would be dropped — graceful degradation).
|
||||
gateway == null ->
|
||||
dispatchSse(resolveSseFallback(handler))
|
||||
// The conversation owner is immutable. Losing Gateway preserves
|
||||
// the local transcript/draft and exposes Retry; it never dispatches
|
||||
// the turn into the API server's different session database.
|
||||
gateway == null -> {
|
||||
onErrorCb("This chat belongs to the Hermes Dashboard. Sign in or reconnect, then retry.")
|
||||
null
|
||||
}
|
||||
|
||||
else -> {
|
||||
startImageActivityBridge()
|
||||
@@ -10387,11 +10475,14 @@ class ChatViewModel : ViewModel() {
|
||||
activeStream = null
|
||||
settleSessionActivity(handler.currentSessionId.value)
|
||||
} else {
|
||||
// Nothing started server-side — rerun this turn on
|
||||
// the SSE fallback. Callbacks land on the main
|
||||
// thread, so swapping activeStream here is safe.
|
||||
// The fallback turn is not steerable.
|
||||
activeStream = dispatchSse(resolveSseFallback(handler))
|
||||
// Nothing started server-side. Keep this turn bound
|
||||
// to Gateway and settle it as retryable local state;
|
||||
// API sessions are a different owner/database.
|
||||
onPreflightErrorCb(
|
||||
IllegalStateException(
|
||||
"Hermes Dashboard chat is unavailable. Sign in or reconnect, then retry.",
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -10415,8 +10506,8 @@ class ChatViewModel : ViewModel() {
|
||||
// configured transport: a gateway-configured turn forced onto SSE
|
||||
// (voice interface context, trace drain) did carry the synthetic
|
||||
// messages, and skipping the mark there re-sent them every turn.
|
||||
// The async gateway preflight-failure fallback stays conservative:
|
||||
// its traces are marked on the NEXT turn (at-least-once delivery).
|
||||
// A failed Gateway preflight leaves these traces unsynced; retrying the
|
||||
// same owner retains at-least-once delivery without crossing stores.
|
||||
if (voiceIntentMessages != null && effectiveEndpoint != "gateway") {
|
||||
if (hasVoiceIntents) handler.markVoiceIntentsSynced()
|
||||
if (hasCardDispatches) handler.markCardDispatchesSynced()
|
||||
@@ -10428,18 +10519,6 @@ class ChatViewModel : ViewModel() {
|
||||
private fun EventSource.asTurnHandle(): ActiveTurnHandle =
|
||||
ActiveTurnHandle { this.cancel() }
|
||||
|
||||
/**
|
||||
* SSE endpoint for a turn that was meant for the gateway. The sessions
|
||||
* endpoint needs an existing server session — without one, use the
|
||||
* stateless completions path instead of failing the turn.
|
||||
*/
|
||||
private fun resolveSseFallback(handler: ChatHandler): String =
|
||||
if (sseFallbackEndpoint == "sessions" && handler.currentSessionId.value == null) {
|
||||
"completions"
|
||||
} else {
|
||||
sseFallbackEndpoint
|
||||
}
|
||||
|
||||
private fun currentAgentDisplayName(
|
||||
effectiveProfileOverride: Profile? = null,
|
||||
): String? {
|
||||
|
||||
@@ -55,6 +55,8 @@ import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.automaticChatTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.ConnectionSecurity
|
||||
import com.hermesandroid.relay.data.ConnectionStore
|
||||
import com.hermesandroid.relay.data.LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE
|
||||
@@ -348,16 +350,16 @@ internal fun resolveChatConnectState(
|
||||
ready: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
chatOwner: SessionTransport = connection?.automaticChatTransport ?: SessionTransport.GATEWAY,
|
||||
): ChatConnectState {
|
||||
if (ready) return ChatConnectState.Ready
|
||||
if (!hydrated) return ChatConnectState.Connecting
|
||||
val active = connection ?: return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = active.capabilities.dashboardGatewayConfigured &&
|
||||
if (connection == null) return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability in setOf(
|
||||
GatewayAvailability.Unknown,
|
||||
GatewayAvailability.SignInRequired,
|
||||
)
|
||||
val apiStillSettling = active.capabilities.apiServerConfigured &&
|
||||
val apiStillSettling = chatOwner == SessionTransport.SSE &&
|
||||
apiHealth in setOf(
|
||||
ConnectionViewModel.HealthStatus.Unknown,
|
||||
ConnectionViewModel.HealthStatus.Probing,
|
||||
@@ -374,9 +376,20 @@ internal fun isChatTransportReady(
|
||||
apiClientPresent: Boolean,
|
||||
apiReachable: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
chatOwner: SessionTransport = SessionTransport.GATEWAY,
|
||||
): Boolean =
|
||||
gatewayAvailability == GatewayAvailability.Ready ||
|
||||
(apiClientPresent && apiReachable)
|
||||
when (chatOwner) {
|
||||
SessionTransport.GATEWAY -> gatewayAvailability == GatewayAvailability.Ready
|
||||
SessionTransport.SSE -> apiClientPresent && apiReachable
|
||||
}
|
||||
|
||||
internal fun resolveActiveChatTransport(
|
||||
boundOwner: SessionTransport?,
|
||||
connection: Connection?,
|
||||
preference: String,
|
||||
): SessionTransport = boundOwner
|
||||
?: connection?.chatTransportForPreference(preference)
|
||||
?: SessionTransport.GATEWAY
|
||||
|
||||
/** Startup transport timeouts are retryable evidence, not an offline verdict. */
|
||||
internal fun isTransientDashboardTransportFailure(error: Throwable?): Boolean =
|
||||
@@ -1325,7 +1338,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
upstreamTransport.dashboardSessionClientFor(cid, url)
|
||||
},
|
||||
streamingEndpointProvider = { streamingEndpoint.value },
|
||||
gatewayAvailabilityProvider = { upstreamTransport.gatewayAvailability.value },
|
||||
automaticTransportProvider = {
|
||||
activeConnection.value?.automaticChatTransport ?: SessionTransport.GATEWAY
|
||||
},
|
||||
setLastSessionId = { _lastSessionId.value = it },
|
||||
legacyDefaultSessionId = {
|
||||
getApplication<Application>().relayDataStore.data.first()[KEY_LAST_SESSION_ID]
|
||||
@@ -1667,10 +1682,17 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private val _chatApiClient = MutableStateFlow<HermesApiClient?>(null)
|
||||
val chatApiClient: StateFlow<HermesApiClient?> = _chatApiClient.asStateFlow()
|
||||
private val _activeConversationTransport = MutableStateFlow<SessionTransport?>(null)
|
||||
val activeConversationTransport: StateFlow<SessionTransport?> =
|
||||
_activeConversationTransport.asStateFlow()
|
||||
private var profileChatApiClient: HermesApiClient? = null
|
||||
private var profileChatApiClientUrl: String? = null
|
||||
private var profileChatApiClientKey: String? = null
|
||||
|
||||
fun setActiveConversationTransport(transport: SessionTransport?) {
|
||||
_activeConversationTransport.value = transport
|
||||
}
|
||||
|
||||
// Chat mode + per-endpoint capability snapshot — owned by
|
||||
// [upstreamTransport]; getters delegate. `rebuildApiClient()` pushes the
|
||||
// freshly-probed snapshot via `setCapabilitiesAndMode`.
|
||||
@@ -1863,16 +1885,24 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
return upstreamTransport.dashboardClientFor(connectionId, dashboardUrl).getConfig()
|
||||
}
|
||||
|
||||
// Gateway/Dashboard is the standard path; API remains an optional fallback.
|
||||
private val streamingEndpointPreference: StateFlow<String> =
|
||||
application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
|
||||
// Readiness follows the active conversation owner, not any reachable sibling route.
|
||||
val chatReady: StateFlow<Boolean> = combine(
|
||||
_chatApiClient,
|
||||
_apiServerReachable,
|
||||
combine(_chatApiClient, _apiServerReachable) { client, reachable -> client to reachable },
|
||||
upstreamTransport.gatewayAvailability,
|
||||
) { client, apiReachable, gateway ->
|
||||
activeConnection,
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (client, apiReachable), gateway, connection, preference, boundOwner ->
|
||||
isChatTransportReady(
|
||||
apiClientPresent = client != null,
|
||||
apiReachable = apiReachable,
|
||||
gatewayAvailability = gateway,
|
||||
chatOwner = resolveActiveChatTransport(boundOwner, connection, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
|
||||
@@ -1892,13 +1922,22 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* before any flow emits — is the neutral state, not the CTA.
|
||||
*/
|
||||
val chatConnectState: StateFlow<ChatConnectState> = combine(
|
||||
connectionStore.isHydrated,
|
||||
activeConnection,
|
||||
chatReady,
|
||||
combine(connectionStore.isHydrated, activeConnection, chatReady) { hydrated, active, ready ->
|
||||
Triple(hydrated, active, ready)
|
||||
},
|
||||
upstreamTransport.gatewayAvailability,
|
||||
_apiServerHealth,
|
||||
) { hydrated, active, ready, gateway, apiHealth ->
|
||||
resolveChatConnectState(hydrated, active, ready, gateway, apiHealth)
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (hydrated, active, ready), gateway, apiHealth, preference, boundOwner ->
|
||||
resolveChatConnectState(
|
||||
hydrated,
|
||||
active,
|
||||
ready,
|
||||
gateway,
|
||||
apiHealth,
|
||||
resolveActiveChatTransport(boundOwner, active, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, ChatConnectState.Connecting)
|
||||
// NOTE: [relayReady] / [voiceReady] are declared below the [_relayUrl]
|
||||
// MutableStateFlow,
|
||||
@@ -2749,9 +2788,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
//
|
||||
// Existing users keep whatever they previously chose. Only fresh installs
|
||||
// (no value persisted yet) get the new "auto" default.
|
||||
val streamingEndpoint: StateFlow<String> = application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
val streamingEndpoint: StateFlow<String> = streamingEndpointPreference
|
||||
|
||||
fun setStreamingEndpoint(endpoint: String) {
|
||||
viewModelScope.launch {
|
||||
@@ -2833,14 +2870,28 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
upstreamTransport.resolveStreamingEndpoint(preference)
|
||||
upstreamTransport.resolveStreamingEndpoint(
|
||||
preference = preference,
|
||||
gatewayOwned = activeConnection.value
|
||||
?.chatTransportForPreference(preference) == SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [ChatViewModel.sseFallbackEndpoint] for per-turn gateway fallbacks.
|
||||
* [ChatViewModel.sseFallbackEndpoint] only for an API-owned compatibility
|
||||
* binding.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String = upstreamTransport.resolveSseStreamingEndpoint()
|
||||
|
||||
fun resolveActiveStreamingEndpoint(preference: String): String =
|
||||
when (activeConversationTransport.value) {
|
||||
SessionTransport.GATEWAY -> "gateway"
|
||||
SessionTransport.SSE -> resolveStreamingEndpoint(preference)
|
||||
.takeUnless { it == "gateway" }
|
||||
?: resolveSseStreamingEndpoint()
|
||||
null -> resolveStreamingEndpoint(preference)
|
||||
}
|
||||
|
||||
// Parse tool annotations from text markers toggle
|
||||
val parseToolAnnotations: StateFlow<Boolean> = application.relayDataStore.data
|
||||
.map { it[KEY_PARSE_TOOL_ANNOTATIONS] ?: false }
|
||||
@@ -3674,11 +3725,18 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
val dashboardConfigured = activeConnection?.capabilities?.dashboardGatewayConfigured == true
|
||||
val apiConfigured = activeConnection?.capabilities?.apiServerConfigured == true
|
||||
// This helper runs from an eager StateFlow during construction. Read
|
||||
// the earlier-declared backing preference, not its later public alias.
|
||||
val chatOwner = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport.value,
|
||||
connection = activeConnection,
|
||||
preference = streamingEndpointPreference.value,
|
||||
)
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_sign_in_required),
|
||||
@@ -3695,8 +3753,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_not_reachable),
|
||||
@@ -3712,7 +3770,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
return when {
|
||||
apiConfigured &&
|
||||
chatOwner == SessionTransport.SSE &&
|
||||
apiConfigured &&
|
||||
apiHealth == HealthStatus.Unreachable &&
|
||||
gatewayAvailability != GatewayAvailability.Ready -> {
|
||||
// Diagnose, don't just report: for a single-route connection
|
||||
|
||||
+13
-2
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -23,6 +24,7 @@ internal data class ConversationBinding(
|
||||
val contextKey: String? = null,
|
||||
val profileName: String? = null,
|
||||
val sessionId: String? = null,
|
||||
val transport: SessionTransport? = null,
|
||||
val displayProfile: Profile? = null,
|
||||
val origin: ConversationBindingOrigin = ConversationBindingOrigin.GlobalSelection,
|
||||
val revision: Long = 0L,
|
||||
@@ -46,6 +48,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
lockedProfileToken: String?,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
if (!profileAllowed(profileName, lockedProfileToken)) return false
|
||||
reduce(
|
||||
@@ -54,6 +57,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
transport = transport,
|
||||
)
|
||||
return true
|
||||
}
|
||||
@@ -63,6 +67,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
) {
|
||||
reduce(
|
||||
contextKey = contextKey,
|
||||
@@ -70,6 +75,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.GlobalSelection,
|
||||
transport = transport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -79,6 +85,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
val current = _state.value
|
||||
if (
|
||||
@@ -89,7 +96,7 @@ internal class ConversationBindingController {
|
||||
current.sessionId != sessionId
|
||||
)
|
||||
) return false
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile)
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile, transport)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -98,17 +105,19 @@ internal class ConversationBindingController {
|
||||
if (current.sessionId == sessionId) return
|
||||
_state.value = current.copy(
|
||||
sessionId = sessionId,
|
||||
transport = sessionId?.let(SessionTransport::forSessionId) ?: current.transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
}
|
||||
|
||||
/** A user-requested draft keeps its owner and fences persisted-session reconciliation. */
|
||||
fun startFreshDraft() {
|
||||
fun startFreshDraft(transport: SessionTransport? = _state.value.transport) {
|
||||
val current = _state.value
|
||||
if (!current.isBound) return
|
||||
if (current.sessionId == null && current.hasExplicitOwner) return
|
||||
_state.value = current.copy(
|
||||
sessionId = null,
|
||||
transport = transport,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
@@ -130,6 +139,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
origin: ConversationBindingOrigin,
|
||||
transport: SessionTransport?,
|
||||
) {
|
||||
val current = _state.value
|
||||
val next = ConversationBinding(
|
||||
@@ -138,6 +148,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = origin,
|
||||
transport = transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
if (current.copy(revision = next.revision) != next) {
|
||||
|
||||
+6
-11
@@ -130,8 +130,8 @@ class ProfileController(
|
||||
private val dashboardClientFactory: (connectionId: String, dashboardUrl: String) -> DashboardApiClient,
|
||||
/** Current `streamingEndpoint` preference (for [activeSessionTransport]). */
|
||||
private val streamingEndpointProvider: () -> String,
|
||||
/** Current gateway availability tier (for [activeSessionTransport]). */
|
||||
private val gatewayAvailabilityProvider: () -> GatewayAvailability,
|
||||
/** Stable Auto owner for the active saved connection. */
|
||||
private val automaticTransportProvider: () -> SessionTransport,
|
||||
/** Writes `ConnectionViewModel._lastSessionId`. */
|
||||
private val setLastSessionId: (String?) -> Unit,
|
||||
/** Legacy default (untransported) session id for the server-default profile. */
|
||||
@@ -1517,19 +1517,14 @@ class ProfileController(
|
||||
|
||||
/**
|
||||
* Which transport's session slot to restore right now — or `null` when the
|
||||
* decision is still pending (the gateway probe hasn't landed). A manual
|
||||
* streaming-endpoint override resolves immediately; under `"auto"`, Unknown
|
||||
* remains Gateway-owned because the transport resolver also chooses Gateway
|
||||
* until a definitive fallback verdict exists.
|
||||
* decision is still pending. A manual streaming-endpoint override resolves
|
||||
* immediately; under `"auto"`, the saved connection contract owns the
|
||||
* choice, never a transient reachability or authentication verdict.
|
||||
*/
|
||||
fun activeSessionTransport(): SessionTransport? {
|
||||
val preference = streamingEndpointProvider()
|
||||
if (preference != "auto") return SessionTransport.forEndpoint(preference)
|
||||
return when (gatewayAvailabilityProvider()) {
|
||||
GatewayAvailability.Ready -> SessionTransport.GATEWAY
|
||||
GatewayAvailability.Unknown -> SessionTransport.GATEWAY
|
||||
else -> SessionTransport.SSE
|
||||
}
|
||||
return automaticTransportProvider()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-2
@@ -667,17 +667,21 @@ class UpstreamTransportController(
|
||||
* - "sessions" / "completions" / "runs" pass through unchanged (manual override wins).
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
fun resolveStreamingEndpoint(
|
||||
preference: String,
|
||||
gatewayOwned: Boolean,
|
||||
): String =
|
||||
resolveStreamingEndpointPreference(
|
||||
preference = preference,
|
||||
gateway = _gatewayAvailability.value,
|
||||
capabilities = _serverCapabilities.value,
|
||||
gatewayOwned = gatewayOwned,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [com.hermesandroid.relay.viewmodel.ChatViewModel.sseFallbackEndpoint] for
|
||||
* per-turn gateway fallbacks.
|
||||
* explicit API-owned compatibility conversations.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String =
|
||||
_serverCapabilities.value.preferredChatEndpoint()
|
||||
|
||||
@@ -288,7 +288,7 @@
|
||||
<string name="cw_cloud_subtitle">Conecte ao seu agente hospedado</string>
|
||||
<string name="cw_server_vps_title">Gateway remoto</string>
|
||||
<string name="cw_server_vps_subtitle">Informe o endereço do Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e fallback da API são opcionais.</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e API direta são opcionais.</string>
|
||||
<string name="cw_cloud_entry_title">Conectar ao Hermes hospedado pela Nous</string>
|
||||
<string name="cw_cloud_entry_description">Insira o endereço do agente mostrado no Nous Portal. Você entrará com segurança depois que o Hermes for encontrado.</string>
|
||||
<string name="cw_cloud_agent_name">Endereço do agente</string>
|
||||
@@ -373,7 +373,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 ou http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API do Hermes usada pelo Chat e pelas sessões — a porta 8642 da API e http:// são presumidos para hosts sem esquema (a porta 9119 do painel é determinada separadamente)</string>
|
||||
<string name="cw_scan_message">Procurando o painel/a API do Hermes nesta LAN…</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas no fallback opcional pela API direta.</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas em conexões explícitas pela API direta.</string>
|
||||
<string name="cw_pair_relay_section">Parear o Relay (opcional)</string>
|
||||
<string name="cw_pair_relay_section_desc">O plugin do Relay já está em execução? Faça o pareamento aqui para ativar Terminal, Bridge e permissões de canais.</string>
|
||||
<string name="cw_pair_relay_url_label">URL do Relay</string>
|
||||
@@ -665,7 +665,7 @@
|
||||
<string name="settings_hermes_management">Gerenciamento do Hermes</string>
|
||||
<string name="settings_hermes_management_desc">Recursos do painel: habilidades, cron, MCP, perfis e modelos</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, fallback da API, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, API direta, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_voice_mode">Modo de voz</string>
|
||||
<string name="settings_voice_mode_desc">Voz do painel, opções de relay em tempo real e provedores</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -775,11 +775,11 @@
|
||||
<string name="chat_settings_debug">Depuração</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostre os marcadores ocultos \"[System: …]\" do servidor (alterações de modelo/personalidade). Desativado corresponde ao desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Endpoint de streaming</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: escolhe o melhor caminho com base no que seu servidor oferece. Em uso no momento: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: conexões padrão usam o Gateway; conexões somente API usam a API direta. Em uso no momento: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamento ao vivo pelo WebSocket do painel)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat por /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat transmitido explicitamente por /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, usa SSE como alternativa em cada turno.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, este chat permanece no Gateway e oferece login ou nova tentativa.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessões: fluxo nativo do Hermes em /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatível com OpenAI por /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use somente quando seu servidor transmitir /v1/runs diretamente.</string>
|
||||
@@ -3339,7 +3339,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Inacessível</string>
|
||||
<string name="active_section_no_fallback_routes">Ainda não há rotas alternativas</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Adicione uma rota de API opcional para chat direto alternativo e troca de rede.</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota alternativa</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota de API direta</string>
|
||||
<string name="active_section_security_authentication">Autenticação</string>
|
||||
<string name="active_section_dashboard_session">Sessão do Dashboard</string>
|
||||
<string name="active_section_credential_storage">Armazenamento de credenciais</string>
|
||||
@@ -3364,7 +3364,7 @@
|
||||
<string name="cw_timeline_authenticated">Autenticação verificada</string>
|
||||
<string name="cw_timeline_ready">Conexão pronta</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage e Voice podem usar este Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">Fallback opcional pela API direta</string>
|
||||
<string name="active_section_optional_api_fallback">API direta opcional</string>
|
||||
<string name="active_section_api_not_required">Não é necessário quando esta conexão usa o Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Onde obtenho essa chave?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY é criada no seu servidor Hermes; este aplicativo não fornece a chave. Configure-a somente ao ativar o servidor de API opcional, que exige uma chave utilizável, e insira aqui o mesmo valor.</string>
|
||||
@@ -4378,7 +4378,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API direta</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Defina o endereço do Dashboard e do Gateway que este telefone deve usar. Rotas privadas de LAN e Tailscale podem usar HTTP ou HTTPS; rotas públicas exigem HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Endereço do gateway</string>
|
||||
@@ -4395,7 +4395,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. O fallback da API e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. A API direta e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes 报告了此错误。应用不会自动切换路由或模型。</string>
|
||||
<string name="chat_failure_copy_details">复制详情</string>
|
||||
<string name="chat_failure_route_gateway">网关</string>
|
||||
<string name="chat_failure_route_api">API 回退</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">打开设置</string>
|
||||
<string name="chat_connect_hermes">连接 Hermes</string>
|
||||
<string name="chat_try_demo">体验演示</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 或 http://你的服务器:8642</string>
|
||||
<string name="cw_api_url_supporting">聊天和会话使用的 Hermes API——裸主机名默认使用 API 端口 8642 和 http://(仪表盘的 9119 端口单独推导)</string>
|
||||
<string name="cw_scan_message">正在扫描本局域网寻找 Hermes 仪表盘/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于可选的直接 API 回退。</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于明确配置的 Direct API 连接。</string>
|
||||
<string name="cw_pair_relay_section">配对 Relay(可选)</string>
|
||||
<string name="cw_pair_relay_for">为 %1$s 配对 Relay</string>
|
||||
<string name="cw_pair_relay_scoped_desc">为这个已保存的 Hermes 连接添加可选的 Relay 扩展。这不会添加或替换服务器。</string>
|
||||
@@ -703,7 +703,7 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">仪表盘功能:技能、定时任务、MCP、配置文件、模型</string>
|
||||
<string name="settings_chat">聊天</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、API 回退、工具显示、消息长度</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、Direct API、工具显示、消息长度</string>
|
||||
<string name="settings_voice_mode">语音模式</string>
|
||||
<string name="settings_voice_mode_desc">仪表盘语音、实时 Relay 选项、提供商</string>
|
||||
<string name="settings_threads">话题</string>
|
||||
@@ -814,11 +814,11 @@
|
||||
<string name="chat_settings_debug">调试</string>
|
||||
<string name="chat_settings_show_system_messages_desc">显示服务器隐藏的 \"[System: …]\" 标记(模型/人格更改)。关闭则与桌面/TUI 一致。</string>
|
||||
<string name="chat_settings_streaming_endpoint">流式端点</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:根据服务器暴露的内容选择最佳路径。当前使用:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:标准连接使用网关;仅 API 连接使用直接 API。当前使用:</string>
|
||||
<string name="chat_settings_gateway_suffix">(通过仪表盘 WebSocket 实时思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(通过 /v1/chat/completions 聊天)</string>
|
||||
<string name="chat_settings_runs_suffix">(通过显式流式 /v1/runs 聊天)</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)实时思考+丰富工具事件——桌面应用使用的方式。需要管理登录;不可用时每轮回退到 SSE。</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)提供实时思考和丰富工具事件——桌面应用也使用此路径。需要“管理”登录;不可用时,此聊天仍保留在网关,并提示登录或重试。</string>
|
||||
<string name="chat_settings_sessions_desc">会话:Hermes 原生 /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">聊天:通过 /v1/chat/completions 的 OpenAI 兼容 SSE。</string>
|
||||
<string name="chat_settings_runs_desc">Runs:仅在服务器直接流式传输 /v1/runs 时使用。</string>
|
||||
@@ -3450,7 +3450,7 @@
|
||||
<string name="active_section_dashboard_unreachable">无法访问</string>
|
||||
<string name="active_section_no_fallback_routes">尚无备用路由</string>
|
||||
<string name="active_section_no_fallback_routes_desc">可添加 API 路由,用于直接聊天回退和网络切换。</string>
|
||||
<string name="active_section_add_api_fallback">添加备用路由</string>
|
||||
<string name="active_section_add_api_fallback">添加 Direct API 路由</string>
|
||||
<string name="active_section_security_authentication">身份验证</string>
|
||||
<string name="active_section_dashboard_session">Dashboard 会话</string>
|
||||
<string name="active_section_credential_storage">凭据存储</string>
|
||||
@@ -3516,7 +3516,7 @@
|
||||
<string name="cw_timeline_authenticated">身份验证已确认</string>
|
||||
<string name="cw_timeline_ready">连接已就绪</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage 和 Voice 可以使用此 Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">可选的直接 API 回退</string>
|
||||
<string name="active_section_optional_api_fallback">可选 Direct API</string>
|
||||
<string name="active_section_api_not_required">此连接使用 Hermes Dashboard 时不需要配置。</string>
|
||||
<string name="active_section_where_api_key">从哪里获取此密钥?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY 需要在 Hermes 服务器上创建,并非由此应用提供。仅在启用可选 API 服务器时配置;该服务器需要可用密钥,并在此输入相同的值。</string>
|
||||
@@ -4459,7 +4459,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">直接 API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">设置此手机使用的 Dashboard 和 Gateway 地址。私有 LAN 与 Tailscale 路由可使用 HTTP 或 HTTPS;公共路由必须使用 HTTPS。</string>
|
||||
<string name="dashboard_address_editor_title">网关地址</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes hat diesen Fehler gemeldet. Die App wechselt Routen oder Modelle nicht automatisch.</string>
|
||||
<string name="chat_failure_copy_details">Details kopieren</string>
|
||||
<string name="chat_failure_route_gateway">Gateway</string>
|
||||
<string name="chat_failure_route_api">API-Fallback</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">Einstellungen öffnen</string>
|
||||
<string name="chat_connect_hermes">Hermes verbinden</string>
|
||||
<string name="chat_try_demo">Demo ausprobieren</string>
|
||||
@@ -309,7 +309,7 @@
|
||||
<string name="cw_cloud_subtitle">Mit deinem gehosteten Agenten verbinden</string>
|
||||
<string name="cw_server_vps_title">Remote-Gateway</string>
|
||||
<string name="cw_server_vps_subtitle">Dashboard-Adresse eingeben</string>
|
||||
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und API-Fallback sind optional.</string>
|
||||
<string name="cw_relay_optional_note">Private LAN- und Tailscale-Adressen dürfen HTTP oder HTTPS verwenden. Öffentliche Adressen erfordern HTTPS. Relay und Direct API sind optional.</string>
|
||||
<string name="cw_cloud_entry_title">Mit von Nous gehostetem Hermes verbinden</string>
|
||||
<string name="cw_cloud_entry_description">Gib die im Nous Portal angezeigte Agentenadresse ein. Nach dem Auffinden von Hermes meldest du dich sicher an.</string>
|
||||
<string name="cw_cloud_agent_name">Agentenadresse</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 oder http://dein-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Von Chat und Sitzungen verwendete Hermes-API — bei reinen Hosts werden API-Port 8642 und http:// angenommen (Dashboard-Port 9119 wird separat abgeleitet)</string>
|
||||
<string name="cw_scan_message">Dieses LAN wird nach Hermes-Dashboard/API durchsucht…</string>
|
||||
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für den optionalen direkten API-Fallback.</string>
|
||||
<string name="cw_dashboard_signin_hint">Melde dich über das Dashboard an, um Verwaltung und Sprache freizuschalten — der API-Schlüssel gilt nur für eine explizite Direct-API-Verbindung.</string>
|
||||
<string name="cw_pair_relay_section">Relay koppeln (optional)</string>
|
||||
<string name="cw_pair_relay_for">Relay mit %1$s koppeln</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Füge dieser gespeicherten Hermes-Verbindung die optionale Relay-Erweiterung hinzu. Dadurch wird kein Server hinzugefügt oder ersetzt.</string>
|
||||
@@ -706,7 +706,7 @@
|
||||
<string name="settings_hermes_management">Hermes-Verwaltung</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard-Funktionen: Skills, Cron, MCP, Profile, Modelle</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Chatverhalten, Gateway, API-Fallback, Werkzeuganzeige, Nachrichtenlänge</string>
|
||||
<string name="settings_chat_desc">Chatverhalten, Gateway, Direct API, Werkzeuganzeige, Nachrichtenlänge</string>
|
||||
<string name="settings_voice_mode">Sprachmodus</string>
|
||||
<string name="settings_voice_mode_desc">Dashboard-Sprache, Echtzeit-Relay-Optionen, Anbieter</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -817,11 +817,11 @@
|
||||
<string name="chat_settings_debug">Debug</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Verborgene \"[System: …]\"-Markierungen des Servers anzeigen (Modell-/Personawechsel). Aus entspricht Desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Streaming-Endpunkt</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: wählt anhand der Serverfunktionen den besten Pfad. Derzeit verwendet: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automatisch: Standardverbindungen verwenden Gateway; reine API-Verbindungen verwenden Direct API. Derzeit verwendet: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (Live-Denken über den Dashboard-WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (Chat über /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (Chat über ausdrücklich gestreamte /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; weicht bei Nichtverfügbarkeit pro Durchlauf auf SSE aus.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: Live-Denken + umfangreiche Werkzeugereignisse über den Dashboard-WebSocket (/api/ws), wie in der Desktop-App. Erfordert Anmeldung unter Verwalten; bei Nichtverfügbarkeit bleibt dieser Chat auf Gateway und bietet Anmeldung oder Wiederholen an.</string>
|
||||
<string name="chat_settings_sessions_desc">Sitzungen: Hermes-eigener Endpunkt /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: OpenAI-kompatibles SSE über /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Durchläufe: nur verwenden, wenn dein Server /v1/runs direkt streamt.</string>
|
||||
@@ -3520,7 +3520,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Nicht erreichbar</string>
|
||||
<string name="active_section_no_fallback_routes">Noch keine Ausweichrouten</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Füge optional eine API-Route für direkten Chat-Ausweichbetrieb und Netzwerkwechsel hinzu.</string>
|
||||
<string name="active_section_add_api_fallback">Ausweichroute hinzufügen</string>
|
||||
<string name="active_section_add_api_fallback">Direct-API-Route hinzufügen</string>
|
||||
<string name="active_section_security_authentication">Authentifizierung</string>
|
||||
<string name="active_section_dashboard_session">Dashboard-Sitzung</string>
|
||||
<string name="active_section_credential_storage">Anmeldedatenspeicher</string>
|
||||
@@ -3584,7 +3584,7 @@
|
||||
<string name="cw_timeline_authenticated">Authentifizierung bestätigt</string>
|
||||
<string name="cw_timeline_ready">Verbindung bereit</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage und Voice können dieses Dashboard verwenden</string>
|
||||
<string name="active_section_optional_api_fallback">Optionaler direkter API-Fallback</string>
|
||||
<string name="active_section_optional_api_fallback">Optionale Direct API</string>
|
||||
<string name="active_section_api_not_required">Nicht erforderlich, wenn diese Verbindung das Hermes Dashboard verwendet.</string>
|
||||
<string name="active_section_where_api_key">Wo erhalte ich diesen Schlüssel?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY wird auf deinem Hermes-Server erstellt und nicht von dieser App bereitgestellt. Konfiguriere ihn nur für den optionalen API-Server, der einen verwendbaren Schlüssel verlangt, und gib hier denselben Wert ein.</string>
|
||||
@@ -4535,7 +4535,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Lege die Dashboard- und Gateway-Adresse für dieses Telefon fest. Private LAN- und Tailscale-Routen dürfen HTTP oder HTTPS verwenden; öffentliche Routen erfordern HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Gateway-Adresse</string>
|
||||
@@ -4552,7 +4552,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. API-Fallback und Relay-Erweiterungen sind optional.</string>
|
||||
<string name="network_routes_summary">LAN-, Tailscale- und öffentliche Routen sind Wege zu diesem Gateway. Direct API und Relay-Erweiterungen sind optional.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -742,11 +742,11 @@
|
||||
<string name="chat_settings_debug">Depurar</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostrar los marcadores \" ocultos del servidor [Sistema: …]\" (cambios de modelo / personalidad). Off coincide con el escritorio/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Punto final de transmisión</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: elige la mejor ruta según lo que expone su servidor. Actualmente usando: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: las conexiones estándar usan Gateway; las conexiones solo API usan API directa. En uso: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamiento en vivo a través del tablero WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chatear vía /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chatear a través de /v1/runs transmitido explícitamente)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos en el panel WebSocket (/api/ws): lo que utiliza la aplicación de escritorio. Requiere el inicio de sesión en Administrar; vuelve a SSE por turno cuando no está disponible.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamiento en vivo + eventos de herramientas enriquecidos por el WebSocket del panel (/api/ws), como en la aplicación de escritorio. Requiere iniciar sesión en Administrar; si no está disponible, este chat permanece en Gateway y ofrece iniciar sesión o reintentar.</string>
|
||||
<string name="chat_settings_sessions_desc">Sesiones: Hermes-nativo /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatible con OpenAI a través de /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Ejecuciones: utilícelo solo cuando su servidor transmita /v1/runs directamente.</string>
|
||||
@@ -4226,7 +4226,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API directa</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Define la dirección del Dashboard y Gateway que usará este teléfono. Las rutas privadas LAN y Tailscale pueden usar HTTP o HTTPS; las rutas públicas requieren HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Dirección del gateway</string>
|
||||
|
||||
@@ -141,7 +141,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes からこのエラーが報告されました。アプリがルートやモデルを自動的に切り替えることはありません。</string>
|
||||
<string name="chat_failure_copy_details">詳細をコピー</string>
|
||||
<string name="chat_failure_route_gateway">ゲートウェイ</string>
|
||||
<string name="chat_failure_route_api">API フォールバック</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">設定を開く</string>
|
||||
<string name="chat_connect_hermes">Hermesを接続してください</string>
|
||||
<string name="chat_try_demo">デモを試してみる</string>
|
||||
@@ -309,7 +309,7 @@
|
||||
<string name="cw_cloud_subtitle">ホスト済みエージェントに接続します</string>
|
||||
<string name="cw_server_vps_title">リモートゲートウェイ</string>
|
||||
<string name="cw_server_vps_subtitle">Dashboard アドレスを入力</string>
|
||||
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と API フォールバックは任意です。</string>
|
||||
<string name="cw_relay_optional_note">プライベート LAN と Tailscale のアドレスは HTTP または HTTPS を使用できます。公開アドレスには HTTPS が必要です。Relay と Direct API は任意です。</string>
|
||||
<string name="cw_cloud_entry_title">Nous ホスト版 Hermes に接続</string>
|
||||
<string name="cw_cloud_entry_description">Nous Portal に表示されるエージェントのアドレスを入力してください。Hermes が見つかった後、安全にサインインします。</string>
|
||||
<string name="cw_cloud_agent_name">エージェントのアドレス</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 または http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API チャットとセッションで使用されます — API ポート 8642 および http:// はベア ホストとして想定されます (ダッシュボードの 9119 は個別に派生します)</string>
|
||||
<string name="cw_scan_message">この LAN をスキャンして Hermes ダッシュボード/API を探しています…</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは任意の直接 API フォールバックでのみ使います。</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは明示的な Direct API 接続でのみ使います。</string>
|
||||
<string name="cw_pair_relay_section">Relay のペア (オプション)</string>
|
||||
<string name="cw_pair_relay_section_desc">すでに Relay プラグインを実行していますか?ここでペアリングすると、ターミナル、Bridge、およびチャネル許可が有効になります。</string>
|
||||
<string name="cw_pair_relay_url_label">Relay URL</string>
|
||||
@@ -703,7 +703,7 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">ダッシュボードの機能: スキル、cron、MCP、プロファイル、モデル</string>
|
||||
<string name="settings_chat">チャット</string>
|
||||
<string name="settings_chat_desc">チャット動作、Gateway、API フォールバック、ツール表示、メッセージ長</string>
|
||||
<string name="settings_chat_desc">チャット動作、Gateway、Direct API、ツール表示、メッセージ長</string>
|
||||
<string name="settings_voice_mode">ボイスモード</string>
|
||||
<string name="settings_voice_mode_desc">ダッシュボード音声、リアルタイムRelayオプション、プロバイダー</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -814,11 +814,11 @@
|
||||
<string name="chat_settings_debug">デバッグ</string>
|
||||
<string name="chat_settings_show_system_messages_desc">サーバーの非表示の「[システム: …]」マーカーを表示します (モデル/パーソナリティの変更)。 Off はデスクトップ/TUI に一致します。</string>
|
||||
<string name="chat_settings_streaming_endpoint">ストリーミングエンドポイント</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: サーバーが公開しているものに基づいて最適なパスを選択します。現在使用しているもの:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自動: 標準接続は Gateway、API 専用接続は Direct API を使用します。現在使用中: </string>
|
||||
<string name="chat_settings_gateway_suffix">(ダッシュボード WebSocket を介したライブ思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(/v1/chat/completions 経由でチャット)</string>
|
||||
<string name="chat_settings_runs_suffix">(明示的にストリーミングされた /v1/runs を介してチャットします)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード上のライブ思考 + 豊富なツール イベント WebSocket (/api/ws) — デスクトップ アプリが使用するもの。管理サインインが必要です。利用できない場合はターンごとに SSE に戻ります。</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: ダッシュボード WebSocket(/api/ws)経由のライブ思考と豊富なツールイベント — デスクトップアプリと同じ経路です。管理へのサインインが必要です。利用できない場合もこのチャットは Gateway のまま、サインインまたは再試行を案内します。</string>
|
||||
<string name="chat_settings_sessions_desc">セッション: Hermes-native /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">チャット: /v1/chat/completions 経由の OpenAI 互換の SSE。</string>
|
||||
<string name="chat_settings_runs_desc">実行: サーバーが /v1/runs を直接ストリーミングする場合にのみ使用します。</string>
|
||||
@@ -3514,7 +3514,7 @@
|
||||
<string name="active_section_dashboard_unreachable">接続できません</string>
|
||||
<string name="active_section_no_fallback_routes">フォールバックルートはまだありません</string>
|
||||
<string name="active_section_no_fallback_routes_desc">直接チャットのフォールバックやネットワーク切り替え用に、任意の API ルートを追加できます。</string>
|
||||
<string name="active_section_add_api_fallback">フォールバックルートを追加</string>
|
||||
<string name="active_section_add_api_fallback">Direct API ルートを追加</string>
|
||||
<string name="active_section_security_authentication">認証</string>
|
||||
<string name="active_section_dashboard_session">Dashboard セッション</string>
|
||||
<string name="active_section_credential_storage">認証情報ストレージ</string>
|
||||
@@ -3580,7 +3580,7 @@
|
||||
<string name="cw_timeline_authenticated">認証を確認済み</string>
|
||||
<string name="cw_timeline_ready">接続準備完了</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage、Voice でこの Dashboard を使用できます</string>
|
||||
<string name="active_section_optional_api_fallback">任意の直接 API フォールバック</string>
|
||||
<string name="active_section_optional_api_fallback">任意の Direct API</string>
|
||||
<string name="active_section_api_not_required">この接続が Hermes Dashboard を使用する場合は必要ありません。</string>
|
||||
<string name="active_section_where_api_key">このキーはどこで入手しますか?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY は Hermes サーバー上で作成します。このアプリからは発行されません。任意の API サーバーを有効にする場合のみ設定します。このサーバーには使用可能なキーが必要です。同じ値をここに入力してください。</string>
|
||||
@@ -4530,7 +4530,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">この端末で使う Dashboard と Gateway のアドレスを設定します。プライベート LAN と Tailscale ルートは HTTP または HTTPS を使用でき、公開ルートには HTTPS が必要です。</string>
|
||||
<string name="dashboard_address_editor_title">ゲートウェイのアドレス</string>
|
||||
@@ -4547,7 +4547,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。API フォールバックと Relay 拡張は任意です。</string>
|
||||
<string name="network_routes_summary">LAN、Tailscale、公開ルートはこの Gateway への接続経路です。Direct API と Relay 拡張は任意です。</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
|
||||
@@ -292,7 +292,7 @@
|
||||
<string name="cw_cloud_subtitle">Подключитесь к своему размещённому агенту</string>
|
||||
<string name="cw_server_vps_title">Удалённый шлюз</string>
|
||||
<string name="cw_server_vps_subtitle">Введите адрес Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и резервный API необязательны.</string>
|
||||
<string name="cw_relay_optional_note">Частные адреса LAN и Tailscale могут использовать HTTP или HTTPS. Публичным адресам требуется HTTPS. Relay и Direct API необязательны.</string>
|
||||
<string name="cw_cloud_entry_title">Подключиться к Hermes на хостинге Nous</string>
|
||||
<string name="cw_cloud_entry_description">Введите адрес агента, указанный в Nous Portal. После обнаружения Hermes вы безопасно войдёте в систему.</string>
|
||||
<string name="cw_cloud_agent_name">Адрес агента</string>
|
||||
@@ -392,7 +392,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 или http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API Гермеса, используемый Чатом и сеансами — порт API 8642 и http:// предполагаются для голых хостов (порт 9119 панели управления выводится отдельно)</string>
|
||||
<string name="cw_scan_message">Сканирование этой локальной сети на предмет панели управления/API Гермеса…</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для необязательного резервного копирования прямого API.</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для явно настроенного Direct API.</string>
|
||||
<string name="cw_pair_relay_section">Сопряжение Relay (необязательно)</string>
|
||||
<string name="cw_pair_relay_for">Сопряжение Relay с %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Добавьте необязательное расширение Relay к этому сохранённому подключению Гермеса. Это не добавляет и не заменяет сервер.</string>
|
||||
@@ -682,7 +682,7 @@
|
||||
<string name="settings_hermes_management">Управление Гермесом</string>
|
||||
<string name="settings_hermes_management_desc">Функции панели управления: навыки, cron, MCP, профили, модели</string>
|
||||
<string name="settings_chat">Чат</string>
|
||||
<string name="settings_chat_desc">Поведение чата, Gateway, резервный API, отображение инструментов, длина сообщения</string>
|
||||
<string name="settings_chat_desc">Поведение чата, Gateway, Direct API, отображение инструментов, длина сообщения</string>
|
||||
<string name="settings_voice_mode">Режим голоса</string>
|
||||
<string name="settings_voice_mode_desc">Голос панели управления, опции Relay в реальном времени, поставщики</string>
|
||||
<string name="settings_threads">Потоки</string>
|
||||
@@ -791,11 +791,11 @@
|
||||
<string name="chat_settings_debug">Отладка</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Показывать скрытые сервером маркеры \"[Система: …]\" (изменения модели / личности). Выключено соответствует рабочему столу/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Потоковая конечная точка</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: выбирает лучший путь на основе того, что ваш сервер предоставляет. В настоящее время используется:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Авто: стандартные подключения используют Gateway; подключения только к API используют Direct API. Сейчас используется: </string>
|
||||
<string name="chat_settings_gateway_suffix">(живое мышление через WebSocket панели управления)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(чат через /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix">(чат через явно потоковые /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Шлюз: живое мышление + богатые события инструментов через WebSocket панели управления (/api/ws) — что использует настольное приложение. Требует входа в систему Manage; возвращается к SSE на каждый ход, когда недоступен.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: живое мышление и расширенные события инструментов через WebSocket панели управления (/api/ws), как в настольном приложении. Требует входа в Manage; если Gateway недоступен, чат остается на нем и предлагает войти или повторить попытку.</string>
|
||||
<string name="chat_settings_sessions_desc">Сессии: Hermes-native /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Чат: совместимый с OpenAI SSE через /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Запуски: используйте только когда ваш сервер напрямую потоковые /v1/runs.</string>
|
||||
@@ -927,7 +927,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Недоступно</string>
|
||||
<string name="active_section_no_fallback_routes">Нет резервных маршрутов</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Добавьте локальный адрес, Tailscale или публичный адрес, чтобы сохранить это соединение доступным при изменении сетей.</string>
|
||||
<string name="active_section_add_api_fallback">Добавить резервный маршрут</string>
|
||||
<string name="active_section_add_api_fallback">Добавить маршрут Direct API</string>
|
||||
<string name="active_section_security_authentication">Аутентификация</string>
|
||||
<string name="active_section_dashboard_session">Сессия панели управления</string>
|
||||
<string name="active_section_credential_storage">Хранение учетных данных</string>
|
||||
@@ -942,7 +942,7 @@
|
||||
<string name="active_section_route_selection">Выбор маршрута</string>
|
||||
<string name="active_section_automatic">Автоматически</string>
|
||||
<string name="active_section_api_access">Доступ к API</string>
|
||||
<string name="active_section_optional_api_fallback">Дополнительный прямой резерв API</string>
|
||||
<string name="active_section_optional_api_fallback">Необязательный Direct API</string>
|
||||
<string name="active_section_api_not_required">Не требуется, если это соединение использует панель управления Гермесом.</string>
|
||||
<string name="active_section_where_api_key">Где взять это?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY создается на вашем сервере Гермеса; он не предоставляется этим приложением. Настройте его только при включении дополнительного сервера API, который требует рабочего ключа, затем введите то же значение здесь.</string>
|
||||
@@ -4274,7 +4274,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Укажите адрес Dashboard и Gateway для этого телефона. Частные маршруты LAN и Tailscale могут использовать HTTP или HTTPS; публичным маршрутам требуется HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Адрес шлюза</string>
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
<string name="chat_failure_details_guidance">Hermes reported this error. The app won’t switch routes or models automatically.</string>
|
||||
<string name="chat_failure_copy_details">Copy details</string>
|
||||
<string name="chat_failure_route_gateway">Gateway</string>
|
||||
<string name="chat_failure_route_api">API fallback</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">Open Settings</string>
|
||||
<string name="chat_connect_hermes">Connect Hermes</string>
|
||||
<string name="chat_try_demo">Try the demo</string>
|
||||
@@ -315,7 +315,7 @@
|
||||
<string name="cw_cloud_subtitle">Connect to your hosted agent</string>
|
||||
<string name="cw_server_vps_title">Remote gateway</string>
|
||||
<string name="cw_server_vps_subtitle">Enter its Dashboard address</string>
|
||||
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and API fallback are optional.</string>
|
||||
<string name="cw_relay_optional_note">Private LAN and Tailscale addresses may use HTTP or HTTPS. Public addresses require HTTPS. Relay and Direct API are optional.</string>
|
||||
<string name="cw_cloud_entry_title">Connect to Nous-hosted Hermes</string>
|
||||
<string name="cw_cloud_entry_description">Enter the agent address shown in Nous Portal. You’ll sign in securely after Hermes is found.</string>
|
||||
<string name="cw_cloud_agent_name">Agent address</string>
|
||||
@@ -387,7 +387,7 @@
|
||||
<string name="cw_back">Back</string>
|
||||
<string name="cw_connect_button">Connect</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the preferred upstream auth path; the API key remains the Android Chat fallback.</string>
|
||||
<string name="cw_hermes_label_desc">Use this for Chat and Manage. Pair Relay later only when you enable Terminal, Bridge, Relay sessions, or grants. Dashboard sign-in is the standard upstream auth path; an API key is only for explicit Direct API connections.</string>
|
||||
<string name="cw_api_url_label">API server URL or host</string>
|
||||
<string name="cw_api_key_label">API key</string>
|
||||
<string name="cw_api_key_placeholder">Value from API_SERVER_KEY</string>
|
||||
@@ -419,7 +419,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 or http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API used by Chat and sessions — API port 8642 and http:// assumed for bare hosts (the dashboard\'s 9119 is derived separately)</string>
|
||||
<string name="cw_scan_message">Scanning this LAN for Hermes dashboard/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for the optional direct API fallback.</string>
|
||||
<string name="cw_dashboard_signin_hint">Sign in via the dashboard to unlock Manage and voice — the API key is only for optional Direct API compatibility.</string>
|
||||
<string name="cw_pair_relay_section">Pair Relay (optional)</string>
|
||||
<string name="cw_pair_relay_for">Pair Relay with %1$s</string>
|
||||
<string name="cw_pair_relay_scoped_desc">Add the optional Relay extension to this saved Hermes connection. This does not add or replace a server.</string>
|
||||
@@ -751,7 +751,7 @@
|
||||
<string name="settings_hermes_management">Hermes management</string>
|
||||
<string name="settings_hermes_management_desc">Dashboard features: skills, cron, MCP, profiles, models</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Chat behavior, Gateway, API fallback, tool display, message length</string>
|
||||
<string name="settings_chat_desc">Chat behavior, Gateway, Direct API, tool display, message length</string>
|
||||
<string name="settings_voice_mode">Voice mode</string>
|
||||
<string name="settings_voice_mode_desc">Dashboard voice, realtime relay options, providers</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
@@ -872,11 +872,11 @@
|
||||
<string name="chat_settings_debug">Debug</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Show the server\'s hidden \"[System: …]\" markers (model / personality changes). Off matches the desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Streaming endpoint</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: picks the best path based on what your server exposes. Currently using: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Auto: standard connections use Gateway; API-only connections use Direct API. Currently using: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (live thinking via the dashboard WebSocket)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat via /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat via explicitly streamed /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; falls back to SSE per turn when unavailable.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: live thinking + rich tool events over the dashboard WebSocket (/api/ws) — what the desktop app uses. Requires Manage sign-in; when unavailable, this chat stays on Gateway and offers sign-in or retry.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessions: Hermes-native /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: OpenAI-compatible SSE via /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use only when your server streams /v1/runs directly.</string>
|
||||
@@ -1027,14 +1027,14 @@
|
||||
<string name="active_section_primary_dashboard">Primary Dashboard</string>
|
||||
<string name="dashboard_gateway_title">Dashboard & Gateway</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">Direct API</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
<string name="dashboard_gateway_secure_origin">Authenticated Dashboard address</string>
|
||||
<string name="dashboard_gateway_oidc_explainer">The configured route may be LAN, Tailscale, or public. Hermes owns the OIDC callback; Android does not require a second sign-in address.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. API fallback and Relay extensions are optional.</string>
|
||||
<string name="network_routes_summary">LAN, Tailscale, and public routes are ways to reach this Gateway. Direct API and Relay extensions are optional.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="active_section_using_now">Using now</string>
|
||||
@@ -1054,7 +1054,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Not reachable</string>
|
||||
<string name="active_section_no_fallback_routes">No fallback routes yet</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Add a LAN, Tailscale, or public address to keep this connection available when networks change.</string>
|
||||
<string name="active_section_add_api_fallback">Add fallback route</string>
|
||||
<string name="active_section_add_api_fallback">Add Direct API route</string>
|
||||
<string name="active_section_security_authentication">Authentication</string>
|
||||
<string name="active_section_dashboard_session">Dashboard session</string>
|
||||
<string name="active_section_credential_storage">Credential storage</string>
|
||||
@@ -1069,7 +1069,7 @@
|
||||
<string name="active_section_route_selection">Route selection</string>
|
||||
<string name="active_section_automatic">Automatic</string>
|
||||
<string name="active_section_api_access">API access</string>
|
||||
<string name="active_section_optional_api_fallback">Optional direct API fallback</string>
|
||||
<string name="active_section_optional_api_fallback">Optional Direct API</string>
|
||||
<string name="active_section_api_not_required">Not required when this connection uses the Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Where do I get this?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY is created on your Hermes server; it is not supplied by this app. Configure it only when you enable the optional API server, which requires a usable key, then enter the same value here.</string>
|
||||
@@ -4255,7 +4255,7 @@
|
||||
<string name="voice_overlay_notification_body">Microphone access remains available while Hermes is over another app.</string>
|
||||
<string name="voice_overlay_notification_stop">Stop voice</string>
|
||||
<string name="conn_info_profile_api_key_title">Profile API key</string>
|
||||
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex API fallback. Stored encrypted; the connection key is never reused.</string>
|
||||
<string name="conn_info_profile_api_key_hint">Used only for this profile’s shared multiplex Direct API route. Stored encrypted; the connection key is never reused.</string>
|
||||
<string name="conn_info_profile_api_key_stored">A key is stored</string>
|
||||
<string name="conn_info_profile_api_key_not_stored">No key stored</string>
|
||||
<string name="conn_info_profile_api_key_save">Save key</string>
|
||||
|
||||
@@ -38,6 +38,7 @@ class ConnectionCapabilitiesTest {
|
||||
assertTrue(connection.capabilities.dashboardGatewayConfigured)
|
||||
assertTrue(connection.capabilities.apiServerConfigured)
|
||||
assertTrue(connection.capabilities.relayConfigured)
|
||||
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,6 +54,20 @@ class ConnectionCapabilitiesTest {
|
||||
assertTrue(connection.capabilities.dashboardGatewayConfigured)
|
||||
assertTrue(connection.capabilities.apiChatFallbackAvailable)
|
||||
assertFalse(connection.capabilities.relayFeaturesAvailable)
|
||||
assertEquals(SessionTransport.SSE, connection.automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistedDashboardOwnsAutoChatEvenWhenApiIsAlsoConfigured() {
|
||||
val connection = connection(
|
||||
dashboardUrl = "https://hermes.example.com",
|
||||
apiServerUrl = "https://api.example.com",
|
||||
relayUrl = "",
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, connection.automaticChatTransport)
|
||||
assertEquals(SessionTransport.GATEWAY, connection.chatTransportForPreference("auto"))
|
||||
assertEquals(SessionTransport.SSE, connection.chatTransportForPreference("sessions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -184,7 +184,7 @@ class ConnectionSecurityTest {
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Tls, result.level)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
|
||||
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "API fallback" }.useState)
|
||||
assertEquals(SurfaceUseState.Available, result.surfaces.single { it.label == "Direct API" }.useState)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -203,7 +203,7 @@ class ConnectionSecurityTest {
|
||||
|
||||
assertEquals(ConnectionSecurityLevel.Plain, result.level)
|
||||
assertEquals(SurfaceUseState.Unavailable, result.surfaces.single { it.label == "Dashboard & Gateway" }.useState)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "API fallback" }.useState)
|
||||
assertEquals(SurfaceUseState.InUse, result.surfaces.single { it.label == "Direct API" }.useState)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedParentAuthStoreTest {
|
||||
@Test
|
||||
fun `new credential policy accepts strong pins and passwords`() {
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("12345".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertTrue(SupervisedParentAuthStore.validateNewSecret("123456".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("1234567".toCharArray(), SupervisedParentCredentialType.Pin).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("short".toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertTrue(SupervisedParentAuthStore.validateNewSecret("long passphrase".toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret(" ".repeat(8).toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
assertFalse(SupervisedParentAuthStore.validateNewSecret("x".repeat(65).toCharArray(), SupervisedParentCredentialType.Password).valid)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enrollment stores only salted PBKDF2 verifiers and returns six word recovery phrase`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
|
||||
val enrollment = store.enroll(
|
||||
"correct horse".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).getOrThrow()
|
||||
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
|
||||
assertEquals(6, enrollment.recoveryPhrase.split('-').size)
|
||||
assertEquals(6, enrollment.recoveryPhrase.split('-').distinct().size)
|
||||
assertTrue(raw.contains("PBKDF2WithHmacSHA256"))
|
||||
assertTrue(raw.contains("\"iterations\":1"))
|
||||
assertFalse(raw.contains("correct horse"))
|
||||
assertFalse(raw.contains(enrollment.recoveryPhrase))
|
||||
assertTrue(raw.contains("\"credentialType\":\"Password\""))
|
||||
assertTrue(raw.contains("\"recoveryFormat\":\"WordPhrase\""))
|
||||
val salts = Regex("\"(?:parentSalt|recoverySalt)\":\"([^\"]+)\"")
|
||||
.findAll(raw).map { it.groupValues[1] }.toList()
|
||||
assertEquals(2, salts.size)
|
||||
assertNotEquals(salts[0], salts[1])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `production enrollment records 310000 rounds`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = SupervisedParentAuthStore.forTesting(
|
||||
dataStore = dataStore,
|
||||
iterations = 310_000,
|
||||
)
|
||||
|
||||
store.enroll("production-strength".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(
|
||||
dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting]
|
||||
.orEmpty().contains("\"iterations\":310000"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `verification is fail closed when missing or corrupt`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
assertEquals(SupervisedParentAuthStatus.Missing, store.statusFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Missing, store.verify("anything".toCharArray()))
|
||||
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "not-json" }
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Corrupt, store.verify("anything".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unsupported or weakened records fail closed`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val raw = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
|
||||
dataStore.edit {
|
||||
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"version\":1", "\"version\":2")
|
||||
}
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
|
||||
dataStore.edit {
|
||||
it[SupervisedParentAuthStore.recordKeyForTesting] = raw.replace("\"iterations\":1", "\"iterations\":0")
|
||||
}
|
||||
assertEquals(SupervisedParentAuthStatus.Corrupt, store.statusFlow.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `records created before credential type selection remain verifiable`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val current = dataStore.data.first()[SupervisedParentAuthStore.recordKeyForTesting].orEmpty()
|
||||
val legacy = current
|
||||
.replace(Regex(",\"credentialType\":\"Password\""), "")
|
||||
.replace(Regex(",\"recoveryFormat\":\"WordPhrase\""), "")
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = legacy }
|
||||
|
||||
assertEquals(SupervisedParentCredentialType.Legacy, store.credentialTypeFlow.first())
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enroll cannot replace an existing or corrupt credential`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val store = fastStore(dataStore)
|
||||
store.enroll("first password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("first password".toCharArray()))
|
||||
|
||||
dataStore.edit { it[SupervisedParentAuthStore.recordKeyForTesting] = "corrupt" }
|
||||
assertTrue(store.enroll("second password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `authenticated clear removes credential and disables policies without losing settings`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val authStore = fastStore(dataStore)
|
||||
val policyStore = SupervisedModeStore.forTesting(dataStore)
|
||||
authStore.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
policyStore.setPolicy(
|
||||
"connection-a",
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(attachments = false, voice = true),
|
||||
),
|
||||
)
|
||||
policyStore.setPolicy(
|
||||
"connection-b",
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "coder",
|
||||
visibility = SupervisedVisibility(showTimestamps = true),
|
||||
),
|
||||
)
|
||||
val beforeA = policyStore.policyFlow("connection-a").first()
|
||||
val beforeB = policyStore.policyFlow("connection-b").first()
|
||||
|
||||
authStore.clearCredentialAndDisablePolicies().getOrThrow()
|
||||
|
||||
assertEquals(SupervisedParentAuthStatus.Missing, authStore.statusFlow.first())
|
||||
assertEquals(beforeA.copy(enabled = false), policyStore.policyFlow("connection-a").first())
|
||||
assertEquals(beforeB.copy(enabled = false), policyStore.policyFlow("connection-b").first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed attempts persist across store recreation and backoff expires by clock`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val clock = AtomicLong(1_000L)
|
||||
var store = fastStore(dataStore, clock)
|
||||
store.enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
repeat(4) {
|
||||
assertTrue(store.verify("wrong password".toCharArray()) is SupervisedParentAuthResult.Invalid)
|
||||
}
|
||||
val fifth = store.verify("wrong password".toCharArray())
|
||||
assertEquals(SupervisedParentAuthResult.Throttled(30_000L), fifth)
|
||||
|
||||
store = fastStore(dataStore, clock)
|
||||
assertEquals(
|
||||
SupervisedParentAuthResult.Throttled(30_000L),
|
||||
store.verify("parent password".toCharArray()),
|
||||
)
|
||||
clock.addAndGet(30_001L)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("parent password".toCharArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `concurrent store instances preserve the capped failure sequence`() = runTest {
|
||||
val dataStore = InMemoryParentAuthDataStore()
|
||||
val stores = List(5) { fastStore(dataStore) }
|
||||
stores.first().enroll("parent password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
val results = stores.map { store -> async { store.verify("wrong password".toCharArray()) } }.awaitAll()
|
||||
|
||||
assertEquals(4, results.count { it is SupervisedParentAuthResult.Invalid })
|
||||
assertEquals(1, results.count { it == SupervisedParentAuthResult.Throttled(30_000L) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `change requires the current credential and rotates recovery`() = runTest {
|
||||
val store = fastStore(InMemoryParentAuthDataStore())
|
||||
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
|
||||
assertTrue(store.change("wrong".toCharArray(), "new password".toCharArray(), SupervisedParentCredentialType.Password).isFailure)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("old password".toCharArray()))
|
||||
|
||||
val replacement = store.change(
|
||||
"old password".toCharArray(),
|
||||
"654321".toCharArray(),
|
||||
SupervisedParentCredentialType.Pin,
|
||||
).getOrThrow()
|
||||
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
|
||||
assertTrue(store.verify("old password".toCharArray()) is SupervisedParentAuthResult.Invalid)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("654321".toCharArray()))
|
||||
assertEquals(SupervisedParentCredentialType.Pin, store.credentialTypeFlow.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovery is normalized one time and rotates both secrets`() = runTest {
|
||||
val store = fastStore(InMemoryParentAuthDataStore())
|
||||
val original = store.enroll("old password".toCharArray(), SupervisedParentCredentialType.Password).getOrThrow()
|
||||
val lowerSpaced = original.recoveryPhrase.uppercase().replace("-", " ").toCharArray()
|
||||
|
||||
val replacement = store.resetWithRecoveryPhrase(
|
||||
lowerSpaced,
|
||||
"new password".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
).getOrThrow()
|
||||
|
||||
assertNotEquals(original.recoveryPhrase, replacement.recoveryPhrase)
|
||||
assertEquals(SupervisedParentAuthResult.Success, store.verify("new password".toCharArray()))
|
||||
assertTrue(
|
||||
store.resetWithRecoveryPhrase(
|
||||
original.recoveryPhrase.toCharArray(),
|
||||
"another password".toCharArray(),
|
||||
SupervisedParentCredentialType.Password,
|
||||
)
|
||||
.isFailure,
|
||||
)
|
||||
}
|
||||
|
||||
private fun fastStore(
|
||||
dataStore: DataStore<Preferences>,
|
||||
clock: AtomicLong = AtomicLong(1_000L),
|
||||
): SupervisedParentAuthStore = SupervisedParentAuthStore.forTesting(
|
||||
dataStore = dataStore,
|
||||
iterations = 1,
|
||||
minimumAcceptedIterations = 1,
|
||||
nowMillis = clock::get,
|
||||
)
|
||||
}
|
||||
|
||||
private class InMemoryParentAuthDataStore : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow(emptyPreferences())
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences {
|
||||
val updated = transform(state.value)
|
||||
state.value = updated
|
||||
return updated
|
||||
}
|
||||
}
|
||||
+274
-1
@@ -772,6 +772,7 @@ class GatewayChatClientTest {
|
||||
val moaReferences = ConcurrentLinkedQueue<GatewayMoaReference>()
|
||||
val usages = ConcurrentLinkedQueue<UsageInfo>()
|
||||
val reconcileRequests = AtomicInteger(0)
|
||||
val completions = AtomicInteger(0)
|
||||
val completeLatch = CountDownLatch(1)
|
||||
val preflightFailures = ConcurrentLinkedQueue<String>()
|
||||
|
||||
@@ -785,7 +786,7 @@ class GatewayChatClientTest {
|
||||
onToolCallFailed = { _, _ -> },
|
||||
onTurnComplete = { },
|
||||
onReconcileRequired = { reconcileRequests.incrementAndGet() },
|
||||
onComplete = { completeLatch.countDown() },
|
||||
onComplete = { completions.incrementAndGet(); completeLatch.countDown() },
|
||||
onUsage = { it?.let(usages::add) },
|
||||
onError = { errors += it; completeLatch.countDown() },
|
||||
onToolGenerating = { toolGenerating += it ?: "" },
|
||||
@@ -803,6 +804,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
callbackDispatcher: (block: () -> Unit) -> Unit = { it() },
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) = GatewayChatClient(
|
||||
@@ -824,6 +826,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
)
|
||||
|
||||
private fun awaitCondition(
|
||||
@@ -837,6 +840,21 @@ class GatewayChatClientTest {
|
||||
assertTrue("condition did not settle within ${timeoutMs}ms", condition())
|
||||
}
|
||||
|
||||
private fun exactActiveSessionPayload(
|
||||
status: String,
|
||||
liveSessionId: String = "live-1",
|
||||
storedSessionId: String = "20260612_120000_abc123",
|
||||
): JsonObject = buildJsonObject {
|
||||
put("sessions", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("id", liveSessionId)
|
||||
put("session_key", storedSessionId)
|
||||
put("status", status)
|
||||
put("last_active", 1_777_000_000.0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap in a client with shortened timeout seams. Mints a FRESH scope:
|
||||
* shutdown() cancels the scope's Job, and the replacement client must
|
||||
@@ -846,6 +864,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs: Long = 15_000L,
|
||||
promptSubmitTimeoutMs: Long = 1_800_000L,
|
||||
turnIdleTimeoutMs: Long = 180_000L,
|
||||
compactingTimeoutMs: Long = 600_000L,
|
||||
ticketTimeoutMs: Long = 8_000L,
|
||||
) {
|
||||
client.shutdown()
|
||||
@@ -854,6 +873,7 @@ class GatewayChatClientTest {
|
||||
rpcTimeoutMs = rpcTimeoutMs,
|
||||
promptSubmitTimeoutMs = promptSubmitTimeoutMs,
|
||||
turnIdleTimeoutMs = turnIdleTimeoutMs,
|
||||
compactingTimeoutMs = compactingTimeoutMs,
|
||||
ticketTimeoutMs = ticketTimeoutMs,
|
||||
)
|
||||
}
|
||||
@@ -4710,6 +4730,180 @@ class GatewayChatClientTest {
|
||||
assertTrue(harness.ticketMints.get() >= 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session idle settles exact Android turn without interrupt`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn(null, "finish without terminal", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "durable partial") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload("idle")
|
||||
|
||||
assertTrue(client.listActiveSessions() is GatewayActiveSessionsResult.Success)
|
||||
assertTrue("idle snapshot did not settle turn", recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertEquals(1, recorder.completions.get())
|
||||
assertEquals(1, recorder.reconcileRequests.get())
|
||||
assertTrue(recorder.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session idle never settles passively observed turn`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
client.setUnsolicitedTurnProvider {
|
||||
GatewayInboundTurnRegistration(recorder.callbacks) { true }
|
||||
}
|
||||
assertTrue(client.prewarmAwait("stored-session"))
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "desktop-owned") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload(
|
||||
status = "idle",
|
||||
liveSessionId = "live-resumed",
|
||||
storedSessionId = "stored-session",
|
||||
)
|
||||
|
||||
client.listActiveSessions()
|
||||
assertFalse(recorder.completeLatch.await(250, TimeUnit.MILLISECONDS))
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "desktop-owned") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale active session snapshot cannot settle newer turn generation`() = runBlocking {
|
||||
val first = Recorder()
|
||||
client.sendTurn(null, "first", null, first.callbacks) { first.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "first") }, "live-1"),
|
||||
)
|
||||
awaitCondition { first.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.suppressAckMethods += "session.active_list"
|
||||
val staleSnapshot = scope.async { client.listActiveSessions() }
|
||||
val staleAck = harness.awaitPendingAck()
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "first") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
assertTrue(first.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
|
||||
val second = Recorder()
|
||||
client.sendTurn(
|
||||
"20260612_120000_abc123",
|
||||
"second",
|
||||
null,
|
||||
second.callbacks,
|
||||
) { second.preflightFailures += it }
|
||||
harness.awaitRpcCount("prompt.submit", 2)
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "second") }, "live-1"),
|
||||
)
|
||||
awaitCondition { second.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.releaseAck(staleAck, exactActiveSessionPayload("idle"))
|
||||
assertTrue(staleSnapshot.await() is GatewayActiveSessionsResult.Success)
|
||||
assertFalse(second.completeLatch.await(250, TimeUnit.MILLISECONDS))
|
||||
assertEquals(0, second.reconcileRequests.get())
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "second") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
assertTrue(second.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cancellation wins over delayed active session idle snapshot`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
val handle = client.sendTurn(null, "cancel me", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "partial") }, "live-1"),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
|
||||
harness.suppressAckMethods += "session.active_list"
|
||||
val delayedSnapshot = scope.async { client.listActiveSessions() }
|
||||
val delayedAck = harness.awaitPendingAck()
|
||||
handle.cancel()
|
||||
harness.awaitRpc("session.interrupt")
|
||||
harness.releaseAck(delayedAck, exactActiveSessionPayload("idle"))
|
||||
|
||||
assertTrue(delayedSnapshot.await() is GatewayActiveSessionsResult.Success)
|
||||
assertEquals(0, recorder.completions.get())
|
||||
assertEquals(0, recorder.reconcileRequests.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `late terminal after active session settle is consumed once`() = runBlocking {
|
||||
val recorder = Recorder()
|
||||
val unmatched = ConcurrentLinkedQueue<GatewayBackgroundTurnCompletion>()
|
||||
client.setUnmatchedTurnCompleteListener(unmatched::add)
|
||||
client.sendTurn(null, "late terminal", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(harness.eventFrame("message.start", null, "live-1"))
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.delta", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
awaitCondition { recorder.textDeltas.isNotEmpty() }
|
||||
harness.activeSessionListPayload = exactActiveSessionPayload("idle")
|
||||
client.listActiveSessions()
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", "done") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(150)
|
||||
assertEquals(1, recorder.completions.get())
|
||||
assertTrue(unmatched.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `idle watchdog does not fire while events keep arriving slowly`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 1_000L)
|
||||
@@ -4738,6 +4932,85 @@ class GatewayChatClientTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compacting status extends watchdog until a later completion`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 1_000L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "compact once", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "compacting") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(500)
|
||||
|
||||
assertTrue("normal idle watchdog fired during compaction: ${r.errors}", r.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(r.errors.isEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compacting heartbeats rearm watchdog beyond one compaction lease`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 200L, compactingTimeoutMs = 500L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "compact with heartbeats", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
repeat(3) {
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "compacting") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
Thread.sleep(300)
|
||||
}
|
||||
|
||||
assertTrue("compaction lease was not rearmed: ${r.errors}", r.errors.isEmpty())
|
||||
assertTrue(harness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
serverWs.send(
|
||||
harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"),
|
||||
)
|
||||
assertTrue("turn never completed", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(r.errors.isEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non compacting status keeps the ordinary watchdog`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 250L, compactingTimeoutMs = 2_000L)
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "ordinary status", null, r.callbacks) { r.preflightFailures += it }
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"status.update",
|
||||
buildJsonObject { put("kind", "process") },
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue("ordinary watchdog never fired", r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue("expected a stream error from the watchdog", r.errors.isNotEmpty())
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
harness.awaitRpc("session.interrupt")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `idle watchdog fires when events stop flowing`() {
|
||||
rebuildClient(turnIdleTimeoutMs = 500L)
|
||||
|
||||
+41
-7
@@ -5,9 +5,8 @@ import org.junit.Test
|
||||
|
||||
/**
|
||||
* Resolution matrix for [resolveStreamingEndpointPreference] — the gateway
|
||||
* tier sits above the capability-preferred SSE endpoint for "auto". An
|
||||
* unresolved cold-start probe remains on Gateway until it produces a
|
||||
* definitive fallback verdict.
|
||||
* tier is a stable owner for standard "auto" conversations. API capability
|
||||
* ordering applies only to true API-only compatibility connections.
|
||||
*/
|
||||
class GatewayEndpointResolutionTest {
|
||||
|
||||
@@ -44,28 +43,63 @@ class GatewayEndpointResolutionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `auto falls back after a definitive non-ready verdict`() {
|
||||
fun `standard auto remains gateway owned after auth expiry or outage`() {
|
||||
listOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
).forEach { availability ->
|
||||
assertEquals(
|
||||
"expected SSE fallback for $availability",
|
||||
"sessions",
|
||||
"expected Gateway affinity for $availability",
|
||||
"gateway",
|
||||
resolveStreamingEndpointPreference("auto", availability, fullCaps),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `auto fallback respects capability ordering`() {
|
||||
fun `API-only auto respects capability ordering`() {
|
||||
assertEquals(
|
||||
"sessions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.SignInRequired,
|
||||
fullCaps,
|
||||
gatewayOwned = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"completions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.SignInRequired,
|
||||
portableOnlyCaps,
|
||||
gatewayOwned = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `standard auto does not consult API health when gateway is unavailable`() {
|
||||
assertEquals(
|
||||
"gateway",
|
||||
resolveStreamingEndpointPreference(
|
||||
"auto",
|
||||
GatewayAvailability.Unreachable,
|
||||
ServerCapabilities.DISCONNECTED,
|
||||
gatewayOwned = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `manual API selection remains explicit compatibility mode`() {
|
||||
assertEquals(
|
||||
"sessions",
|
||||
resolveStreamingEndpointPreference(
|
||||
"sessions",
|
||||
GatewayAvailability.SignInRequired,
|
||||
fullCaps,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.ui.screens.CredentialChoiceScreen
|
||||
import com.hermesandroid.relay.ui.screens.ParentAuthScreenSurface
|
||||
import com.hermesandroid.relay.ui.screens.PasswordSetupScreen
|
||||
import com.hermesandroid.relay.ui.screens.PinSetupScreen
|
||||
import com.hermesandroid.relay.ui.screens.SupervisedParentRecoveryCodeContent
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w400dp-h900dp-432dpi")
|
||||
class SupervisedParentAuthFlowScreenshotTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun credentialChoice() {
|
||||
render("build/visual-qa/supervised-parent-choice.png", 1 to 2) {
|
||||
CredentialChoiceScreen(
|
||||
title = "Choose parent access",
|
||||
subtitle = "Pick one way to unlock parent settings. You can change it later.",
|
||||
onSelected = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pinSetup() {
|
||||
render("build/visual-qa/supervised-parent-pin.png", 2 to 2) {
|
||||
PinSetupScreen(busy = false, error = null, onComplete = {})
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passwordSetup() {
|
||||
render("build/visual-qa/supervised-parent-password.png", 2 to 2) {
|
||||
PasswordSetupScreen(busy = false, error = null, onComplete = {})
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveryPhrase() {
|
||||
render("build/visual-qa/supervised-parent-recovery.png", 3 to 3) {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
enrollment = SupervisedParentEnrollment(
|
||||
"maple-river-lantern-copper-sparrow-moon",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun render(
|
||||
path: String,
|
||||
step: Pair<Int, Int>,
|
||||
content: @androidx.compose.runtime.Composable () -> Unit,
|
||||
) {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
ParentAuthScreenSurface(step = step, onBack = {}, content = content)
|
||||
}
|
||||
}
|
||||
compose.onRoot().captureRoboImage(path)
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,39 @@ class RelayAppStatusTest {
|
||||
assertEquals(ChatRuntimeStatus.Connecting, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard sign-out is not masked by a reachable sibling API`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
connection = connection(
|
||||
dashboardUrl = "https://host.ts.net:9119",
|
||||
apiServerUrl = "https://host.ts.net:8642",
|
||||
),
|
||||
gatewayAvailability = GatewayAvailability.SignInRequired,
|
||||
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
|
||||
streamingEndpoint = "sessions",
|
||||
conversationOwner = com.hermesandroid.relay.data.SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
assertEquals(ChatRuntimeStatus.Unavailable, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy API-only connection remains connected compatibility chat`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
connection = connection(
|
||||
dashboardUrl = null,
|
||||
apiServerUrl = "https://host.ts.net:8642",
|
||||
),
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
apiHealth = ConnectionViewModel.HealthStatus.Reachable,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `committed pair target stays ready while public inventory catches up`() {
|
||||
assertTrue(
|
||||
@@ -392,7 +425,7 @@ class RelayAppStatusTest {
|
||||
}
|
||||
|
||||
private fun connected(path: ChatTransportPath) =
|
||||
ChatRuntimeStatus.Connected(transport = path, fallback = path == ChatTransportPath.ApiSse)
|
||||
ChatRuntimeStatus.Connected(transport = path, fallback = false)
|
||||
|
||||
private fun connection(
|
||||
dashboardUrl: String? = null,
|
||||
|
||||
@@ -172,25 +172,23 @@ class SupervisedNavigationPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `first enable requires configured policy secure screen and successful device credential`() {
|
||||
@Test fun `first enable requires configured policy and successful app parent credential`() {
|
||||
val configured = SupervisedModePolicy(pinnedProfileName = "willow")
|
||||
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = false,
|
||||
deviceCredentialConfirmed = true,
|
||||
parentCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = true,
|
||||
deviceCredentialConfirmed = false,
|
||||
parentCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true, true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true, true))
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true))
|
||||
}
|
||||
}
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.SupervisedParentCredentialType
|
||||
import com.hermesandroid.relay.data.SupervisedParentEnrollment
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@Config(qualifiers = "w400dp-h900dp-432dpi")
|
||||
class SupervisedParentAuthDialogsTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun `choice presents mutually exclusive pin and password routes`() {
|
||||
var selected: SupervisedParentCredentialType? = null
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
CredentialChoiceScreen("Choose parent access", "Pick one.") { selected = it }
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Use a PIN").assertIsDisplayed().performClick()
|
||||
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Pin, selected) }
|
||||
compose.onNodeWithText("Use a password").assertIsDisplayed().performClick()
|
||||
compose.runOnIdle { assertEquals(SupervisedParentCredentialType.Password, selected) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pin auth uses six positions and a dedicated numeric keypad`() {
|
||||
var submitted: String? = null
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
PinEntryScreen("Parent PIN", "Enter your 6-digit PIN.", false, null, { submitted = it })
|
||||
}
|
||||
}
|
||||
|
||||
(0..9).forEach { compose.onNodeWithText(it.toString()).assertIsDisplayed() }
|
||||
compose.onNodeWithContentDescription("Delete digit").assertIsDisplayed()
|
||||
(1..6).forEach { compose.onNodeWithText(it.toString()).performClick() }
|
||||
compose.runOnIdle { assertEquals("123456", submitted) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password setup uses distinct password fields and visibility controls`() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme { PasswordSetupScreen(false, null, {}) }
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Create a parent password").assertIsDisplayed()
|
||||
compose.onNodeWithText("Password").assertIsDisplayed()
|
||||
compose.onNodeWithText("Confirm password").assertIsDisplayed()
|
||||
compose.onAllNodesWithContentDescription("Show password").assertCountEquals(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovery phrase handoff exposes sharing copy and cleanup guidance`() {
|
||||
var shares = 0
|
||||
var copies = 0
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
SupervisedParentRecoveryCodeContent(
|
||||
SupervisedParentEnrollment("maple-river-lantern-copper-sparrow-moon"),
|
||||
onShare = { shares += 1 },
|
||||
onCopy = { copies += 1 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("maple-river-lantern", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("copper-sparrow-moon", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("Share").assertIsDisplayed()
|
||||
compose.onNodeWithText("Copy phrase").assertIsDisplayed()
|
||||
compose.onNodeWithText("delete the message or saved copy", substring = true).assertIsDisplayed()
|
||||
compose.onNodeWithText("Share").performClick()
|
||||
compose.onNodeWithText("Copy phrase").performClick()
|
||||
compose.runOnIdle {
|
||||
assertEquals(1, shares)
|
||||
assertEquals(1, copies)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -38,12 +40,54 @@ class ChatReadinessTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready with reachable API when Gateway is unavailable`() {
|
||||
fun `ready with reachable API for API-only owner`() {
|
||||
assertTrue(
|
||||
isChatTransportReady(
|
||||
apiClientPresent = true,
|
||||
apiReachable = true,
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
chatOwner = SessionTransport.SSE,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reachable API cannot make a Gateway-owned chat ready`() {
|
||||
assertFalse(
|
||||
isChatTransportReady(
|
||||
apiClientPresent = true,
|
||||
apiReachable = true,
|
||||
gatewayAvailability = GatewayAvailability.SignInRequired,
|
||||
chatOwner = SessionTransport.GATEWAY,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `eager status owner resolves from backing preference before public alias`() {
|
||||
val connection = Connection(
|
||||
id = "dashboard-owner",
|
||||
label = "Dashboard",
|
||||
apiServerUrl = "https://hermes.example.com:8642",
|
||||
relayUrl = "",
|
||||
tokenStoreKey = "test-key",
|
||||
dashboardUrl = "https://hermes.example.com:9119",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
SessionTransport.GATEWAY,
|
||||
resolveActiveChatTransport(
|
||||
boundOwner = null,
|
||||
connection = connection,
|
||||
preference = "auto",
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SessionTransport.SSE,
|
||||
resolveActiveChatTransport(
|
||||
boundOwner = SessionTransport.SSE,
|
||||
connection = connection,
|
||||
preference = "auto",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,23 +28,25 @@ class ChatRuntimeStatusTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `API SSE ready is healthy fallback when gateway is unavailable`() {
|
||||
fun `API SSE ready is healthy only for an API-owned conversation`() {
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = false),
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Ready,
|
||||
owner = ChatTransportPath.ApiSse,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready API fallback wins while gateway is still connecting`() {
|
||||
fun `ready sibling API cannot mask gateway auth expiry`() {
|
||||
assertEquals(
|
||||
ChatRuntimeStatus.Connected(ChatTransportPath.ApiSse, fallback = true),
|
||||
ChatRuntimeStatus.Unavailable,
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Connecting,
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Ready,
|
||||
owner = ChatTransportPath.Gateway,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -63,6 +65,7 @@ class ChatRuntimeStatusTest {
|
||||
resolveChatRuntimeStatus(
|
||||
gateway = ChatTransportReadiness.Unavailable,
|
||||
apiSse = ChatTransportReadiness.Connecting,
|
||||
owner = ChatTransportPath.ApiSse,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+89
-1
@@ -195,7 +195,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals(STORED_SESSION_ID, failure?.sessionId)
|
||||
assertEquals(ChatFailureRoute.GATEWAY, failure?.route)
|
||||
assertTrue(failure?.recoverable == true)
|
||||
assertTrue(failure?.rawError.orEmpty().contains("no API fallback"))
|
||||
assertTrue(failure?.rawError.orEmpty().contains("belongs to the Hermes Dashboard"))
|
||||
assertEquals("Retry this after reconnect", handler.lastSentMessage.value)
|
||||
assertTrue(handler.messages.value.isEmpty())
|
||||
val diagnostic = DiagnosticsLog.recent(setOf(DiagnosticCategory.Session), 1).single()
|
||||
@@ -1650,6 +1650,39 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(gatewayClient.hasActiveTurn())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayOwnedConversationDoesNotDispatchToReachableApiWhenGatewayIsMissing() {
|
||||
viewModel.streamingEndpoint = "gateway"
|
||||
viewModel.updateGatewayClient(null)
|
||||
val apiRequestsBefore = apiCompletionsRequestCount.get()
|
||||
|
||||
viewModel.sendMessage("Keep this turn on Victor")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
assertEquals(apiRequestsBefore, apiCompletionsRequestCount.get())
|
||||
assertTrue(handler.messages.value.none { it.role == MessageRole.ASSISTANT })
|
||||
assertEquals(
|
||||
ChatFailureRoute.GATEWAY,
|
||||
viewModel.chatFailure.value?.route,
|
||||
)
|
||||
assertEquals(STORED_SESSION_ID, handler.currentSessionId.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun boundGatewaySessionRejectsAResolverTransportFlipUntilExplicitNewChat() {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
|
||||
viewModel.streamingEndpoint = "sessions"
|
||||
|
||||
assertEquals("gateway", viewModel.streamingEndpoint)
|
||||
assertEquals(SessionTransport.GATEWAY, viewModel.conversationBinding.value.transport)
|
||||
|
||||
viewModel.createNewChat()
|
||||
|
||||
assertEquals("sessions", viewModel.streamingEndpoint)
|
||||
assertEquals(SessionTransport.SSE, viewModel.conversationBinding.value.transport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayRichCardActionStaysOnGatewayInsteadOfDrainingThroughSessionsApi() {
|
||||
viewModel.sseFallbackEndpoint = "sessions"
|
||||
@@ -2981,6 +3014,51 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(viewModel.queuedMessages.value.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedCorrectionDrainsOnceAfterOwnedTurnSettlesFromActiveSessionIdle() = runBlocking {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
gatewayHarness.redirectStatus = "rejected"
|
||||
viewModel.sendMessage("Original Android turn")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", "Answer without terminal") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { handler.isStreaming.value }
|
||||
|
||||
viewModel.sendMessage("Queued correction")
|
||||
gatewayHarness.awaitRpc("session.redirect")
|
||||
awaitCondition { viewModel.queuedMessages.value == listOf("Queued correction") }
|
||||
persistedHistory = persistedAnswerHistory("Answer without terminal", "settled-answer")
|
||||
gatewayHarness.activeSessionListPayload = buildJsonObject {
|
||||
put("sessions", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("id", "live-resumed")
|
||||
put("session_key", STORED_SESSION_ID)
|
||||
put("status", "idle")
|
||||
put("last_active", 1_777_000_000.0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
gatewayClient.listActiveSessions()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
awaitCondition {
|
||||
gatewayHarness.rpcLog.count { (method, params) ->
|
||||
method == "prompt.submit" &&
|
||||
params["text"] == JsonPrimitive("Queued correction") &&
|
||||
params["queued"] == JsonPrimitive(true)
|
||||
} == 1
|
||||
}
|
||||
assertTrue(viewModel.queuedMessages.value.isEmpty())
|
||||
assertTrue(viewModel.steerableTurn.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multipleQueuedMessagesDrainAsAnOwnedRunChain() {
|
||||
viewModel.switchProfileContext(
|
||||
@@ -3739,6 +3817,16 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition {
|
||||
gatewayHarness.rpcLog.count { it.first == "session.active_list" } > baselineActiveList
|
||||
}
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.Working
|
||||
}
|
||||
gatewayHarness.activeSessionListPayload = activeSessionPayload("waiting")
|
||||
viewModel.requestSessionActivityRefresh()
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.NeedsInput
|
||||
}
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = "desktop-answer",
|
||||
|
||||
+37
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -112,4 +113,40 @@ class ConversationBindingControllerTest {
|
||||
assertEquals("alpha", controller.state.value.profileName)
|
||||
assertEquals("a1", controller.state.value.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayOwnerSurvivesSessionClearAndLifecycleReconciliation() {
|
||||
controller.forceGlobal(
|
||||
contextKey = "c::victor",
|
||||
profileName = "victor",
|
||||
sessionId = "20260831_120000_deadbeef",
|
||||
transport = SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
controller.startFreshDraft()
|
||||
controller.reconcileGlobal(
|
||||
contextKey = "c::victor",
|
||||
profileName = "victor",
|
||||
sessionId = null,
|
||||
transport = SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, controller.state.value.transport)
|
||||
assertNull(controller.state.value.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitApiSessionKeepsItsCompatibilityOwner() {
|
||||
controller.openExplicit(
|
||||
contextKey = "c::default",
|
||||
profileName = null,
|
||||
sessionId = "api_1788192000_deadbeef",
|
||||
displayProfile = null,
|
||||
lockedProfileToken = null,
|
||||
)
|
||||
|
||||
assertEquals(SessionTransport.SSE, controller.state.value.transport)
|
||||
controller.switchSession(null)
|
||||
assertEquals(SessionTransport.SSE, controller.state.value.transport)
|
||||
}
|
||||
}
|
||||
|
||||
+24
-2
@@ -5,6 +5,7 @@ import com.hermesandroid.relay.data.SessionLiveStatus
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSession
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSessionStatus
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -40,14 +41,35 @@ class SessionActivityResolutionTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unscoped stored id stays unresolved even when bounded directory looks unique`() {
|
||||
fun `unique selected passive owner resolves without a runtime binding`() {
|
||||
val unique = SessionActivityOwner.of("connection", "beta", "unique")
|
||||
val result = resolveGatewayActiveSessions(
|
||||
sessions = listOf(
|
||||
GatewayActiveSession(
|
||||
runtimeSessionId = "runtime",
|
||||
storedSessionId = "unique",
|
||||
status = GatewayActiveSessionStatus.Starting,
|
||||
status = GatewayActiveSessionStatus.Waiting,
|
||||
lastActiveEpochSeconds = 1.0,
|
||||
),
|
||||
),
|
||||
directory = setOf(alpha, unique),
|
||||
currentOwner = unique,
|
||||
)
|
||||
|
||||
assertEquals(unique, result.runtimes.single().owner)
|
||||
assertEquals(SessionLiveStatus.Waiting, result.runtimes.single().status)
|
||||
assertFalse(result.ambiguous)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unique passive owner for a nonselected session stays unresolved`() {
|
||||
val unique = SessionActivityOwner.of("connection", "beta", "unique")
|
||||
val result = resolveGatewayActiveSessions(
|
||||
sessions = listOf(
|
||||
GatewayActiveSession(
|
||||
runtimeSessionId = "runtime",
|
||||
storedSessionId = "unique",
|
||||
status = GatewayActiveSessionStatus.Working,
|
||||
lastActiveEpochSeconds = 1.0,
|
||||
),
|
||||
),
|
||||
|
||||
+5
-2
@@ -118,7 +118,7 @@ class ProfileControllerLockTest {
|
||||
// (no gateway probe gating) — keeps refreshLastSessionForProfile from
|
||||
// bailing early on Unknown.
|
||||
streamingEndpointProvider = { streamingEndpoint },
|
||||
gatewayAvailabilityProvider = { gatewayAvailability },
|
||||
automaticTransportProvider = { SessionTransport.GATEWAY },
|
||||
setLastSessionId = { lastSessionIds += it },
|
||||
legacyDefaultSessionId = { null },
|
||||
rebuildChatApiClient = { },
|
||||
@@ -208,13 +208,16 @@ class ProfileControllerLockTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoUnknownRestoresGatewayBucketUntilDefinitiveFallback() {
|
||||
fun autoGatewayOwnerDoesNotChangeRestoreBucketAfterOutage() {
|
||||
streamingEndpoint = "auto"
|
||||
gatewayAvailability = GatewayAvailability.Unknown
|
||||
|
||||
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
|
||||
|
||||
gatewayAvailability = GatewayAvailability.Unreachable
|
||||
assertEquals(SessionTransport.GATEWAY, controller.activeSessionTransport())
|
||||
|
||||
streamingEndpoint = "sessions"
|
||||
assertEquals(SessionTransport.SSE, controller.activeSessionTransport())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# Android emulator testing
|
||||
|
||||
Hermes-Relay Android uses individually selected Gradle Managed Devices for
|
||||
repeatable, on-demand instrumentation. The routine virtual baseline is API 36.
|
||||
There is deliberately no aggregate matrix task and no scheduled emulator job:
|
||||
choose the smallest lane that can prove the behavior under review.
|
||||
|
||||
## Lanes
|
||||
|
||||
| Evidence lane | Gradle device | Hardware profile | Use it for |
|
||||
|---|---|---|---|
|
||||
| Real Device | None | Explicitly selected physical hardware | Firmware, radio, audio, camera, biometrics, background limits, accessibility, and release-candidate claims |
|
||||
| Compact Phone | `compactPhoneApi36` | Pixel 2 | Narrow phone layouts, compact height, keyboard pressure |
|
||||
| Standard Phone | `standardPhoneApi36` | Pixel 6 | Default functional and regression instrumentation |
|
||||
| Large Phone | `largePhoneApi36` | Pixel 7 Pro | Large handset layout and reachability |
|
||||
| Foldable | `foldableApi36` | Pixel Fold | Fold/unfold, posture, continuity, and width-class changes |
|
||||
| Tablet | `tabletApi36` | Pixel Tablet | Expanded layout, panes, and large-window behavior |
|
||||
| Future platform / native canary | `futureApi37Ps16k` | Pixel 7 Pro, API 37, forced 16 KB pages | On-demand platform and native-library compatibility only |
|
||||
|
||||
Routine API 36 lanes use the AOSP x86_64 image so deterministic app tests do not
|
||||
spend host capacity on unrelated Google-service startup. The API 37/16 KB device
|
||||
is not a screen-size lane and is not part of routine testing. Gradle Managed
|
||||
Devices may download a missing image on first use; that setup can be large and
|
||||
slow.
|
||||
|
||||
## Commands
|
||||
|
||||
List the registered tasks:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle :app:tasks --all |
|
||||
Select-String 'Api36|Ps16k'
|
||||
```
|
||||
|
||||
Compile the app and instrumentation APK without starting an emulator:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:assembleSideloadDebug `
|
||||
:app:assembleSideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
Run one complete lane, normally Standard Phone first:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:standardPhoneApi36SideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
Run one test class on one lane:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:standardPhoneApi36SideloadDebugAndroidTest `
|
||||
'-Pandroid.testInstrumentationRunnerArguments.class=com.hermesandroid.relay.viewmodel.GatewayForegroundRecoveryInstrumentedTest'
|
||||
```
|
||||
|
||||
Run the other virtual lanes only when their form factor is relevant:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle :app:compactPhoneApi36SideloadDebugAndroidTest
|
||||
.\scripts\android-lane.ps1 gradle :app:largePhoneApi36SideloadDebugAndroidTest
|
||||
.\scripts\android-lane.ps1 gradle :app:foldableApi36SideloadDebugAndroidTest
|
||||
.\scripts\android-lane.ps1 gradle :app:tabletApi36SideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
Run the future-platform/native canary explicitly:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle `
|
||||
:app:futureApi37Ps16kSideloadDebugAndroidTest
|
||||
```
|
||||
|
||||
All Windows commands use the repository's machine-wide build lane; see
|
||||
[`docs/android-build-lane.md`](android-build-lane.md). Check the lane without
|
||||
starting work with:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 status
|
||||
```
|
||||
|
||||
Do not invoke every device task as one command. Run lanes serially, record each
|
||||
result, and stop when the relevant evidence is complete or the host reaches a
|
||||
capacity limit.
|
||||
|
||||
## Configuration coverage
|
||||
|
||||
Form factor is only one axis. Select additional states according to the change:
|
||||
|
||||
- Test dark mode first; also cover light mode when colors, contrast, system bars,
|
||||
or theme persistence changed.
|
||||
- Cover portrait and landscape when layout, keyboard, media, drawers, or panes
|
||||
changed. Foldable work must include a posture or width-class transition.
|
||||
- Check default font scale and at least one enlarged scale for text-heavy or
|
||||
accessibility-sensitive UI.
|
||||
- Use the default locale for functional regressions; add a long-string locale
|
||||
and an RTL locale when copy, formatting, or layout direction changed.
|
||||
- Record gesture versus three-button navigation when bottom insets, edge-to-edge,
|
||||
back handling, sheets, or overlays changed.
|
||||
|
||||
These dimensions are selected test conditions, not permanent duplicated device
|
||||
definitions. Record any non-default setting in the evidence.
|
||||
|
||||
## Deterministic fixtures and live servers
|
||||
|
||||
Embedded MockWebServer tests own deterministic transport regressions. They use
|
||||
production clients and view models against loopback HTTP/WebSocket boundaries,
|
||||
require no credentials, mutate no real sessions, and are the correct lane for
|
||||
authentication loss, reconnect gaps, malformed frames, profile isolation, and
|
||||
repeatable lifecycle assertions.
|
||||
|
||||
Live-server testing is separate and on demand. Use a disposable test or staging
|
||||
Hermes server with disposable profiles and sessions. Normally run only the
|
||||
Standard Phone emulator plus one explicitly selected real device when physical
|
||||
evidence is required. Never multiply live mutation testing across the full size
|
||||
matrix, use a production server, or use personal conversation data. Sanitize
|
||||
logs and exports before attaching them to a pull request.
|
||||
|
||||
## Evidence
|
||||
|
||||
For each executed lane, record:
|
||||
|
||||
```text
|
||||
Commit: <exact SHA>
|
||||
Artifact/variant: sideloadDebug app + androidTest
|
||||
Lane: Standard Phone (standardPhoneApi36), API 36
|
||||
Test selection: <class or package>
|
||||
Configuration: dark/light, orientation/posture, font scale, locale, navigation
|
||||
Result: pass/fail/blocked, test count, report path
|
||||
Notes: retries, emulator/image limitation, relevant sanitized observation
|
||||
```
|
||||
|
||||
Keep claims lane-specific. Emulator proof is not physical-device proof. A
|
||||
passing API 37/16 KB canary proves only that selected platform/native lane; it
|
||||
does not replace API 36 form-factor coverage or physical firmware evidence.
|
||||
+135
-31
@@ -59,8 +59,9 @@
|
||||
### 3. Chat via Direct API, Not Relay Proxy
|
||||
|
||||
**Status:** Superseded as the standard route by ADR 38 (2026-07-18). Direct API
|
||||
chat remains the automatic fallback and an advanced headless compatibility
|
||||
mode; the upstream Dashboard/Gateway is now the primary connection surface.
|
||||
chat remains an explicit API-only/headless compatibility mode; the upstream
|
||||
Dashboard/Gateway is now the primary connection surface. ADR 71 removes
|
||||
availability-driven fallback between their non-interchangeable session stores.
|
||||
|
||||
**Decision:** ~~Chat channel proxies through the relay to the WebAPI.~~ **Updated:** Chat now connects directly from the Android app to the Hermes API Server via HTTP/SSE. The relay server is only used for bridge and terminal channels.
|
||||
|
||||
@@ -2210,7 +2211,7 @@ starting connectivity does not itself require or imply a tool grant.
|
||||
|
||||
## ADR 38 — Dashboard/Gateway is the primary Android connection surface
|
||||
|
||||
**Status:** Accepted (2026-07-18).
|
||||
**Status:** Superseded by ADR 71 for chat fallback semantics (2026-08-31).
|
||||
|
||||
**Context.** Android originally treated the API server URL and bearer key as the
|
||||
identity and prerequisite for every saved connection. The app later gained the
|
||||
@@ -2226,7 +2227,7 @@ stable identity independent of endpoint URLs.
|
||||
- **Dashboard/Gateway is standard.** It owns primary chat, dashboard auth,
|
||||
sessions, Manage, and Vanilla Hermes voice against unmodified upstream Hermes.
|
||||
- **API server is optional.** When discovered or explicitly configured, it is an
|
||||
automatic chat fallback and an advanced headless compatibility surface. Its
|
||||
API-only chat and advanced headless compatibility surface. Its
|
||||
bearer is requested and validated only when that endpoint is configured.
|
||||
- **Relay is optional.** It adds pairing, terminal, bridge/device control,
|
||||
media, notification companion, enhanced voice, and desktop tooling. It never
|
||||
@@ -2238,15 +2239,14 @@ stable identity independent of endpoint URLs.
|
||||
profile's authoritative Hermes session database without proxying chat.
|
||||
Native Gateway lifecycle events take precedence, and absence of the optional
|
||||
route silently restores the vanilla behavior.
|
||||
- **Readiness is capability-based.** Chat, Manage, Voice, API fallback, and
|
||||
- **Readiness is capability-based.** Chat, Manage, Voice, Direct API, and
|
||||
Relay extensions report their own state. A missing optional endpoint does not
|
||||
mark the whole connection unhealthy.
|
||||
- **Routing is automatic.** Chat prefers Dashboard/Gateway and falls back to the
|
||||
API server only when configured and usable. Users choose a transport only in
|
||||
advanced diagnostics or compatibility settings, not during normal setup.
|
||||
Endpoint discovery may advertise a conventional API route, but does not enable
|
||||
that optional fallback unless the connection has persisted API configuration;
|
||||
cold-start state remains unconfigured until that persisted value is hydrated.
|
||||
- **Routing is owner-bound.** Standard Chat uses Dashboard/Gateway. Legacy
|
||||
API-only records and explicit advanced compatibility selections use the API
|
||||
server. Live authentication or reachability never changes an open chat's
|
||||
owner. Endpoint discovery may advertise a conventional API route, but does
|
||||
not enable it for a Dashboard-owned conversation.
|
||||
|
||||
**Product flow.** Normal onboarding asks for one Hermes address, discovers the
|
||||
Dashboard/Gateway, authenticates through its supported provider, and finishes
|
||||
@@ -2260,8 +2260,8 @@ An API endpoint or Relay can be added later without recreating the connection.
|
||||
|
||||
- Dashboard-only Hermes connections can chat, manage, use sessions, and use
|
||||
Vanilla Hermes voice without fake API credentials.
|
||||
- API outages do not degrade a healthy Gateway session; they remove only the
|
||||
fallback capability.
|
||||
- API outages do not degrade a healthy Gateway session; they affect only an
|
||||
explicit Direct API compatibility conversation.
|
||||
- Connection storage, diagnostics, backup/restore, route discovery, pairing,
|
||||
and profile/session scoping must tolerate independently absent endpoints.
|
||||
- Legacy API-only users keep working, but public documentation no longer teaches
|
||||
@@ -3710,15 +3710,20 @@ live even when upstream had already persisted the final answer. The earlier
|
||||
visible-chat Idle reattach fix covered a socket that closed after foreground
|
||||
prewarm; it did not cover this already-active turn state.
|
||||
|
||||
**Decision.** A Gateway turn may settle from `session.activate` or exact-session
|
||||
`session.info` only when the turn has already received turn-scoped activity and
|
||||
upstream reports `running=false`. Pre-start idle snapshots are ignored because
|
||||
they can race prompt admission. This backstop is a successful server-owned
|
||||
settle, not cancellation or transport failure: Android completes the local
|
||||
stream, keeps the durable session identity, performs bounded identity-fenced
|
||||
history reconciliation, and never resubmits through API fallback. Cold open
|
||||
continues to use `session.resume`; an authoritative resume rejection remains
|
||||
visible and cannot create or switch to a replacement context.
|
||||
**Decision.** A Gateway turn may settle from `session.activate`, exact-session
|
||||
`session.info`, or an exact live/durable `session.active_list` row only when the
|
||||
turn is Android-owned, has already received turn-scoped activity, and upstream
|
||||
reports `running=false` or Idle. The active-list request captures the exact turn
|
||||
and its progress generation; a session/profile switch, cancellation, newer turn,
|
||||
or intervening live event rejects the delayed snapshot. Pre-start idle snapshots
|
||||
and passively observed Desktop/TUI turns are never eligible. This backstop is a
|
||||
successful server-owned settle, not cancellation or transport failure: Android
|
||||
completes the local stream, keeps the durable session identity, performs bounded
|
||||
identity-fenced history reconciliation, consumes one late terminal without
|
||||
double-completion, and never resubmits through API fallback. A locally queued
|
||||
correction drains once through its existing owner chain after settlement. Cold
|
||||
open continues to use `session.resume`; an authoritative resume rejection
|
||||
remains visible and cannot create or switch to a replacement context.
|
||||
|
||||
The recovery writes one bounded content-free diagnostic containing only route,
|
||||
missing-terminal phase, and reconciliation action. It records no prompt or
|
||||
@@ -3772,7 +3777,7 @@ be considered later without being silently introduced now.
|
||||
|
||||
## ADR 66 — Android Supervised Mode is a parent-controlled client policy
|
||||
|
||||
**Status:** Implemented in code; physical managed-device certification pending (2026-08-24).
|
||||
**Status:** Implemented in code; app-specific parent credential and physical managed-device certification pending (2026-08-31).
|
||||
|
||||
**Context.** Some operators prepare a deliberately restricted Hermes profile
|
||||
for use through a parent-supervised Android client. The profile remains the
|
||||
@@ -3784,9 +3789,10 @@ child security or as a server-enforced account type.
|
||||
**Decision.** Android will treat Supervised Mode as an opt-in, locally enforced
|
||||
policy pinned to one existing Connection and one existing Hermes profile. The
|
||||
parent is responsible for preparing and reviewing that profile before enabling
|
||||
the mode. Entering, changing, or leaving the parent policy requires Android
|
||||
device authentication. That prompt authenticates an enrolled device user, not
|
||||
a distinct server-side parent identity. While the policy is active, the app restores directly
|
||||
the mode. Entering, changing, or leaving the parent policy requires the
|
||||
app-global parent PIN or password. Android's screen lock, device credential,
|
||||
and enrolled biometrics are not parent authority because the supervised user
|
||||
may legitimately control them. While the policy is active, the app restores directly
|
||||
into a restricted root and never renders the ordinary app behind an
|
||||
authentication prompt. A missing Connection, missing profile, malformed policy,
|
||||
failed authentication, process restart, or restored route that cannot prove its
|
||||
@@ -3800,6 +3806,37 @@ recreation, and leaving parent settings relock parent access according to the
|
||||
policy. Deep links, notification actions, restored navigation, shortcuts, and
|
||||
programmatic routes pass the same gate.
|
||||
|
||||
The parent credential store persists only salted verifiers in app-private
|
||||
DataStore. Parent and recovery verifiers use independent 128-bit salts and
|
||||
PBKDF2-HMAC-SHA256 with 310,000 iterations; candidate comparison is
|
||||
constant-time. Five failures start a persisted 30-second delay, repeated
|
||||
failures increase it to a capped 15 minutes, and successful verification clears
|
||||
the counter. Enrollment first requires an explicit choice: an exactly six-digit
|
||||
PIN entered through the app keypad, or a password of at least eight and at most
|
||||
64 characters entered through the normal password keyboard. It returns a randomly
|
||||
generated six-word recovery phrase exactly once. Six distinct words from a
|
||||
128-word vocabulary provide about 42 bits of entropy: deliberately less than the
|
||||
previous opaque code, but materially easier to read, type, and send for this
|
||||
family-facing client restriction. Authenticated change and recovery
|
||||
reset replace both verifiers and issue a new recovery phrase; unauthenticated
|
||||
enrollment cannot overwrite an existing or corrupt record.
|
||||
|
||||
An authenticated parent may remove the app-global credential without presenting
|
||||
the recovery phrase. Removal atomically deletes the credential record and sets
|
||||
every supervised policy to `enabled = false`, so no policy can remain active
|
||||
without an unlock path. All other policy configuration is retained for later
|
||||
re-enrollment. It does not delete server-owned Hermes sessions or history. If both the parent
|
||||
credential and recovery phrase are lost, the deliberate last-resort escape hatch
|
||||
is Android's **Clear data** action for the app. Uninstall/reinstall is not the
|
||||
documented recovery path because Android backup restore may restore local state.
|
||||
|
||||
Missing, malformed, unsupported-version, weakened-KDF, and unreadable records
|
||||
fail closed. A legacy enabled policy has no trustworthy app parent identity to
|
||||
migrate, so it stays at the restricted root. Recovery requires resetting local
|
||||
app data, reconnecting, and configuring Supervised Mode again; Android must not
|
||||
disable the policy or promote the current device user automatically. Server
|
||||
sessions and history are not deleted by that local reset.
|
||||
|
||||
The parent policy controls capabilities rather than imposing a special
|
||||
attachment count. Initial capabilities are text chat, new chat, cancel, steer,
|
||||
attachments, standard voice, generated-media viewing, save/share media, copy,
|
||||
@@ -3872,8 +3909,28 @@ or applicable legal obligations. Public language uses **Supervised Mode** or
|
||||
**parent-controlled client**, not "child account," "safe for children," or
|
||||
"server enforced."
|
||||
|
||||
The verifier design raises the cost of an offline guess but cannot make a
|
||||
six-digit PIN high entropy. A privileged attacker who can copy or roll back the
|
||||
app-private store can attempt guesses offline or weaken the persisted backoff;
|
||||
device integrity, backup policy, and a strong parent password remain relevant.
|
||||
The recovery phrase may be copied or shared with a brief instruction to remove
|
||||
the message or saved copy from the phone after it reaches a parent-only place.
|
||||
It must otherwise be stored outside the supervised user's reach. Stock
|
||||
Android also cannot give one app a parent-only biometric enrollment or tell the
|
||||
app which enrolled fingerprint or face authenticated. Biometric convenience may
|
||||
be considered only as an explicit second layer over this app credential, never
|
||||
as proof of a distinct parent.
|
||||
|
||||
**Localization decision.** Until physical certification and fluent security-copy
|
||||
review, the Supervised Mode and parent-authentication surface remains canonical
|
||||
English in every app locale. It intentionally falls back to English and must not
|
||||
be described as localized. Security-critical setup, recovery, migration, and
|
||||
lockout wording will move into the translated catalogs together after review;
|
||||
machine-translating only part of this boundary is not accepted.
|
||||
|
||||
**Verification gate.** Implementation requires policy, authentication,
|
||||
navigation, process-death, deep-link, notification, capability, attachment,
|
||||
navigation, KDF-record validation, persisted throttling, change/recovery
|
||||
rotation, corruption/migration, process-death, deep-link, notification, capability, attachment,
|
||||
voice, session-ownership, Relay-tag, and revocation tests. Physical testing must
|
||||
cover the exact Android build on a managed/restricted device, including relock,
|
||||
restart, offline recovery, and attempts to escape the restricted root. Until
|
||||
@@ -4034,9 +4091,10 @@ The precedence is:
|
||||
revalidated. A failed or unsupported live refresh is **Unavailable**.
|
||||
|
||||
Android resolves each active-list row through exact foreground or detached
|
||||
ownership already held by that client, or explicit profile metadata if a
|
||||
future upstream sends it. A bounded REST directory never proves that a durable
|
||||
`session_key` is globally unique. Ambiguous or unresolved rows apply no status.
|
||||
ownership already held by that client, explicit profile metadata if a future
|
||||
upstream sends it, or the currently selected passive session when its durable
|
||||
`session_key` has exactly one owner in the current connection directory.
|
||||
Duplicate same-id owners across profiles remain ambiguous and apply no status.
|
||||
Resolved rows from a partial snapshot may update their exact owners, but they
|
||||
cannot infer absence. A missing row clears stale live state for a scope only
|
||||
when the successful process-wide snapshot was complete and every relevant row
|
||||
@@ -4076,7 +4134,10 @@ paths, which concern exact Android-owned checkpoints.
|
||||
and saved-session selection establish only the shared Gateway socket. They use
|
||||
profile-scoped REST history plus process-wide `session.active_list`; while an
|
||||
unowned row with the selected durable id is live, Android performs bounded
|
||||
history refreshes and one final read after settlement. These observer paths send
|
||||
history refreshes and one final read after settlement. When that durable id has
|
||||
exactly one owner in the current connection directory, the same read-only row
|
||||
also projects Working or Waiting for the selected session; duplicate cross-profile
|
||||
owners remain neutral. These observer paths send
|
||||
no `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`.
|
||||
Exact Android-owned checkpoints retain `session.activate` with durable-resume
|
||||
fallback, and explicit send or session-config actions may resume because the user
|
||||
@@ -4192,3 +4253,46 @@ large profile database remains a separate certification gate.
|
||||
`apps/desktop/src/app/session/hooks/use-session-list-actions.ts`. Android wiring
|
||||
lives in `DashboardApiClient`, `HermesRuntimeBinder`, `ChatScreen`, and
|
||||
`ChatViewModel`.
|
||||
|
||||
---
|
||||
|
||||
## ADR 71 — Android conversations are transport-affine
|
||||
|
||||
**Status:** Accepted (2026-08-31).
|
||||
|
||||
**Context.** Standard Android Chat now follows the upstream Dashboard/Gateway
|
||||
model, but Auto resolution still changed a live conversation to API-server
|
||||
sessions, completions, or runs when Dashboard sign-in expired or Gateway became
|
||||
unavailable. The optional API server could therefore make Chat appear connected
|
||||
and even complete a local turn while Dashboard session/history reads returned
|
||||
401. Gateway and API-server session ids belong to different databases and are
|
||||
not interchangeable, especially for named profile homes. Reachability of one
|
||||
surface is not authority to mutate a conversation owned by the other.
|
||||
|
||||
**Decision.** Every Android conversation binding includes its transport owner
|
||||
alongside connection, profile, and session identity.
|
||||
|
||||
- A standard saved connection's Auto owner is Gateway and does not change with
|
||||
Gateway availability. `SignInRequired` requests Dashboard sign-in; a temporary
|
||||
failure preserves transcript, draft, attachments, queued destination, and
|
||||
retry state.
|
||||
- Missing Gateway clients and failed Gateway preflight never dispatch the turn
|
||||
through API-server SSE. Attachments, voice sends, slash commands, queued
|
||||
turns, session restore, and profile switches all use the same bound owner.
|
||||
- A legacy connection with API configuration but no persisted Dashboard route
|
||||
remains API-only. Existing `api_…` records retain their API session slot.
|
||||
Advanced manual Direct API selection is explicit and takes effect for a new
|
||||
chat; it does not migrate an existing Gateway transcript or session.
|
||||
- Cold-start restoration selects the persisted session slot from the saved
|
||||
connection/manual preference, not a transient auth or health verdict.
|
||||
Dashboard history remains authoritative for Gateway bindings; API session
|
||||
history remains authoritative only for API-owned bindings.
|
||||
- User-facing Connected and ordinary route labels describe the active binding
|
||||
owner. A reachable sibling endpoint cannot mask sign-out or failure. Exact
|
||||
endpoint names remain available in advanced diagnostics/compatibility UI.
|
||||
|
||||
**Consequences.** Sessions, runs, and completions remain useful for legitimate
|
||||
API-only/headless clients, compatibility testing, and existing API records, but
|
||||
they are no longer automatic recovery for standard Chat. Users retry or sign in
|
||||
without losing local work, named profiles cannot cross databases silently, and
|
||||
readiness reflects the conversation that will actually receive the next turn.
|
||||
|
||||
@@ -68,10 +68,12 @@ the upstream contract identifiers it depends on.
|
||||
|---|---|
|
||||
| `initial_history_bind` | Durable, profile-scoped history is already available when the client resumes and first binds its rendered transcript |
|
||||
| `ordinary_turn` | Normal message start, deltas, completion, and persisted history |
|
||||
| `compaction_status` | Compaction status is client-visible before terminal completion and may repeat as a heartbeat |
|
||||
| `rapid_tools_interims` | Rapid chunks, reasoning, tool activity, and interim assistant boundaries |
|
||||
| `queued_follow_up` | Two explicitly owned turns and ordered queue drainage |
|
||||
| `scope_rejection_inputs` | Exact, foreign, and unscoped event inputs |
|
||||
| `terminal_gap_activate` | Socket closes after live output; replacement `session.activate` reports `running=false`; history is authoritative |
|
||||
| `terminal_gap_active_list` | An exact Android-owned turn receives deltas but no terminal; `session.active_list` reports the same live/durable owner idle; history is authoritative |
|
||||
| `terminal_gap_session_info` | Scoped `session.info {running:false}` settles a turn without `message.complete` |
|
||||
| `active_status_lifecycle` | `session.active_list` reports starting, working, waiting, and idle, then a complete empty process-wide snapshot permits removal of unambiguously owned prior rows |
|
||||
| `active_status_profile_scope` | A row has no profile metadata and a caller profile hint has no effect; the client must use exact client-held ownership and reject invented attribution |
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -26,9 +26,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -48,7 +48,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -61,9 +61,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -85,9 +85,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -96,7 +96,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -109,9 +109,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
@@ -120,7 +120,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -135,7 +135,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "2d4e3945dfec3963b26055bccfdfccc2002dc2f296f114a3a5d1d050878c5d76",
|
||||
"main": "b4c1f6ecb44c77d5da585523788caf733180cebefed826446ec9acd2ad4a52ba",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -148,9 +148,9 @@
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "8e46128280d9db518ea0dcf13109929ff93cfe9b0b491db808ff72ad3be862a4",
|
||||
"guide/getting-started.md": "dc5d299e599402e8be4a3d0cf378176cc078e55e36c5b86319e2541079c9f9dd",
|
||||
"guide/getting-started.md": "de9312d211a694fec9b2a7707b406bd0010a25e21c7c345060073ba3da12e843",
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "83e64a645bc3686fcc9d9fc861b9b8344aebb4756743dcd235b76af78c33ab8a"
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
}
|
||||
|
||||
+24
-39
@@ -637,22 +637,22 @@
|
||||
<span class="branch-label yes">Yes — manual</span>
|
||||
<div class="fnode term">
|
||||
<div class="t">Use it verbatim</div>
|
||||
<div class="s">Manual pick wins. Per-turn fallback still applies if it can't serve.</div>
|
||||
<div class="s">Manual selection owns a new chat; existing bindings do not migrate.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">No — "auto"</span>
|
||||
<div class="fnode dec" style="width:100%">
|
||||
<div class="t">gateway == Ready?</div>
|
||||
<div class="t">Saved connection owner?</div>
|
||||
</div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">Yes</span>
|
||||
<span class="branch-label yes">Standard</span>
|
||||
<div class="fnode gateway"><div class="t">→ "gateway"</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">No</span>
|
||||
<span class="branch-label no">API-only</span>
|
||||
<div class="fnode sse">
|
||||
<div class="t">capabilities<br>.preferredChatEndpoint()</div>
|
||||
<div class="s">sessions › completions › runs</div>
|
||||
@@ -672,40 +672,26 @@
|
||||
</div>
|
||||
<div class="conn arrow"></div>
|
||||
<div class="fnode dec">
|
||||
<div class="t">Voice interface-context present AND endpoint == gateway?</div>
|
||||
<div class="t">Bound owner == "gateway"?</div>
|
||||
</div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">Yes</span>
|
||||
<div class="fnode sse">
|
||||
<div class="t">Force SSE fallback</div>
|
||||
<div class="s">gateway can't carry system_message</div>
|
||||
</div>
|
||||
<span class="branch-label no">Direct API owner</span>
|
||||
<div class="fnode sse"><div class="t">dispatchSse(endpoint)</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">No</span>
|
||||
<div class="fnode dec" style="width:100%"><div class="t">effectiveEndpoint == "gateway"?</div></div>
|
||||
<span class="branch-label yes">Gateway owner</span>
|
||||
<div class="fnode dec" style="width:100%"><div class="t">gateway client live?</div></div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">SSE pick</span>
|
||||
<div class="fnode sse"><div class="t">dispatchSse(endpoint)</div></div>
|
||||
<span class="branch-label no">null</span>
|
||||
<div class="fnode term"><div class="t">Preserve + Retry</div><div class="s">sign in or reconnect; no owner change</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">gateway</span>
|
||||
<div class="fnode dec" style="width:100%"><div class="t">gateway client live?</div></div>
|
||||
<div class="conn"></div>
|
||||
<div class="branch">
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">null</span>
|
||||
<div class="fnode sse"><div class="t">dispatchSse(fallback)</div></div>
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label yes">yes</span>
|
||||
<div class="fnode gateway"><div class="t">gateway.sendTurn()</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<span class="branch-label yes">yes</span>
|
||||
<div class="fnode gateway"><div class="t">gateway.sendTurn()</div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -725,26 +711,25 @@
|
||||
</div>
|
||||
<div class="branch-col">
|
||||
<span class="branch-label no">onPreflightFailure</span>
|
||||
<div class="fnode sse term">
|
||||
<div class="t">dispatchSse(fallback)</div>
|
||||
<div class="s">nothing started server-side → safe to retry on SSE</div>
|
||||
<div class="fnode term">
|
||||
<div class="t">Preserve + Retry</div>
|
||||
<div class="s">nothing started server-side; conversation stays Gateway-owned</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="callout std">
|
||||
<strong>SSE fallback resolution.</strong> When the chosen SSE endpoint is
|
||||
<code>sessions</code> but there's no session yet, it downgrades to stateless
|
||||
<code>completions</code> for that first turn — there's nothing to stream against
|
||||
otherwise. <span class="ref">resolveSseFallback()</span>
|
||||
<strong>Transport affinity.</strong> Gateway and Direct API sessions live in
|
||||
different stores. Sign-in expiry or route loss never authorizes Android to
|
||||
resubmit the turn through another owner.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ───────────────────────── 5 ───────────────────────── -->
|
||||
<section id="inputs">
|
||||
<div class="section-head"><span class="num">05</span><h2>Decision inputs: availability + capabilities</h2></div>
|
||||
<p>The two flowcharts above read two pieces of probed state. Both are computed at connect time and refreshed on resume.</p>
|
||||
<div class="section-head"><span class="num">05</span><h2>Owner, readiness, and capabilities</h2></div>
|
||||
<p>Saved connection state chooses the owner. Availability reports whether that owner is ready; Direct API capabilities choose an endpoint only inside an API-owned conversation.</p>
|
||||
|
||||
<div class="paths" style="margin-top:16px">
|
||||
<div class="panel">
|
||||
@@ -752,7 +737,7 @@
|
||||
<p class="ref">GatewayModels.kt:22 · set by the dashboard <code>/api/status</code> + <code>/api/auth/me</code> probe</p>
|
||||
<ul style="padding-left:18px;margin-top:10px">
|
||||
<li><span class="dot neutral"></span><strong>Unknown</strong> — no probe yet (startup / connection switch)</li>
|
||||
<li><span class="dot ok"></span><strong>Ready</strong> — reachable + authenticated (or no auth) → gateway preferred</li>
|
||||
<li><span class="dot ok"></span><strong>Ready</strong> — reachable + authenticated (or no auth) → Gateway can send</li>
|
||||
<li><span class="dot warn"></span><strong>SignInRequired</strong> — reachable but gated; Manage sign-in unlocks it</li>
|
||||
<li><span class="dot bad"></span><strong>Unreachable</strong> — <code>/api/status</code> didn't answer</li>
|
||||
<li><span class="dot bad"></span><strong>Unsupported</strong> — <em>sticky</em>: WS upgrade/ticket got 404/403 (build predates embedded chat)</li>
|
||||
@@ -788,8 +773,8 @@
|
||||
<tr><th>Feature</th><th>Path</th><th>Surface</th><th>Degrades to</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><strong>Chat (live thinking)</strong></td><td class="std-c">Vanilla Hermes</td><td>Gateway WS</td><td>Sessions → Completions → Runs SSE</td></tr>
|
||||
<tr><td><strong>Chat (fallback)</strong></td><td class="std-c">Vanilla Hermes</td><td>API-server SSE</td><td>Inline-annotation parser</td></tr>
|
||||
<tr><td><strong>Chat (live thinking)</strong></td><td class="std-c">Vanilla Hermes</td><td>Gateway WS</td><td>Sign in or retry on the same owner</td></tr>
|
||||
<tr><td><strong>Direct API chat</strong></td><td class="std-c">Vanilla Hermes</td><td>API-server SSE</td><td>Inline-annotation parser</td></tr>
|
||||
<tr><td><strong>Session history / CRUD</strong></td><td class="std-c">Vanilla Hermes</td><td><code>/api/sessions</code></td><td>Stateless completions (no persistence)</td></tr>
|
||||
<tr><td><strong>Manage</strong> (config/profiles/model/env/MCP)</td><td class="std-c">Vanilla Hermes</td><td>Dashboard <code>/api/*</code></td><td>— (hidden if dashboard down)</td></tr>
|
||||
<tr><td><strong>Vanilla Hermes voice</strong> (STT/TTS)</td><td class="std-c">Vanilla Hermes</td><td>Dashboard <code>/api/audio/*</code></td><td>Relay voice if paired (Auto route)</td></tr>
|
||||
|
||||
@@ -24,7 +24,7 @@ A plain Hermes install is enough. Chat, management, and voice all work with no p
|
||||
|
||||
HOW IT WORKS
|
||||
|
||||
Chat, sessions, Manage, and voice use the Hermes Dashboard/Gateway with one sign-in. A headless API server remains an automatic compatibility fallback. Run the optional relay service and the app can pair by QR code to add power tools: remote terminal, notification companion, media handoff, relay-session management, and more voice engines.
|
||||
Chat, sessions, Manage, and voice use the Hermes Dashboard/Gateway with one sign-in. Existing API-only and headless connections remain supported as an explicit compatibility mode. Run the optional relay service and the app can pair by QR code to add power tools: remote terminal, notification companion, media handoff, relay-session management, and more voice engines.
|
||||
|
||||
GOOGLE PLAY BUILD
|
||||
|
||||
|
||||
+46
-20
@@ -7,7 +7,7 @@ Android's declarative plugin surface is specified in
|
||||
|
||||
**Status:** v1.0.0 stable. The default path supports chat, Manage, and voice on vanilla upstream Hermes without installing the Relay plugin. Relay is additive: terminal, bridge/device control, notification companion, remote access, extra/provider-native voice, desktop tooling, and dashboard Relay management. Historical phase notes remain in this file for context; the current route ownership source of truth is [`docs/upstream-surface-matrix.md`](upstream-surface-matrix.md).
|
||||
**Repo:** [Codename-11/hermes-relay](https://github.com/Codename-11/hermes-relay)
|
||||
**Updated:** 2026-08-29
|
||||
**Updated:** 2026-08-31
|
||||
|
||||
---
|
||||
|
||||
@@ -19,7 +19,7 @@ Current capabilities are split between vanilla upstream Hermes and optional Rela
|
||||
|
||||
| Surface | Requires Relay | What |
|
||||
|---------|----------------|------|
|
||||
| **Chat** | No | Talk to any Hermes agent profile with dashboard `/api/ws` live thinking when signed in, or API-server SSE fallback |
|
||||
| **Chat** | No | Talk to any Hermes agent profile with dashboard `/api/ws` live thinking when signed in, or an explicit API-only compatibility connection |
|
||||
| **Manage** | No | Dashboard-backed config, profiles, model/provider keys, skills, MCP, and diagnostics |
|
||||
| **Vanilla Hermes voice** | No | Dashboard `/api/audio/transcribe`, streaming `/api/audio/speak-stream`, and compatible `/api/audio/speak` fallback with the Manage session |
|
||||
| **Terminal** | Yes | Secure remote shell access to the Hermes server via tmux |
|
||||
@@ -27,8 +27,9 @@ Current capabilities are split between vanilla upstream Hermes and optional Rela
|
||||
| **Relay power features** | Yes | Remote access, notification companion, provider-native voice, desktop tooling, media relay |
|
||||
|
||||
The standard Vanilla Hermes connection needs only the Dashboard/Gateway surface.
|
||||
An API-server endpoint can be discovered or added as an automatic fallback for
|
||||
chat and advanced headless compatibility. Pairing adds the Relay URL, session
|
||||
An API-server endpoint can be retained or added for explicit API-only chat and
|
||||
advanced headless compatibility. It never takes over a Dashboard-owned
|
||||
conversation after sign-out or a route failure. Pairing adds the Relay URL, session
|
||||
token, terminal/bridge grants, and optional network candidates.
|
||||
|
||||
**What it is not:**
|
||||
@@ -42,7 +43,7 @@ token, terminal/bridge grants, and optional network candidates.
|
||||
|
||||
1. **Vanilla Hermes first** — chat, Manage, and voice must work against unmodified upstream Hermes before any Relay power path is considered.
|
||||
2. **Secure by default** — WSS/HTTPS for remote paths; dashboard, API, and Relay auth stay on their native surfaces.
|
||||
3. **Realtime where the surface supports it** — gateway chat can stream live thinking; API-server SSE remains the fallback; terminal and bridge stay realtime through Relay.
|
||||
3. **Realtime where the surface supports it** — gateway chat can stream live thinking; API-server SSE remains an explicit compatibility mode; terminal and bridge stay realtime through Relay.
|
||||
4. **Clean UX** — Material 3, minimal setup, and clear route identity for Vanilla Hermes vs Relay.
|
||||
5. **Offline-aware** — graceful degradation when connection drops. Auto-reconnect with exponential backoff.
|
||||
6. **Server-side state** — the app is a thin client. Sessions, history, memory, profiles, and dashboard state live on the Hermes server.
|
||||
@@ -51,6 +52,27 @@ token, terminal/bridge grants, and optional network candidates.
|
||||
selected Hermes profile, server, or agent child-safe. See ADR 66 and the
|
||||
[Supervised Mode guide](../user-docs/guide/supervised-mode.md).
|
||||
|
||||
Supervised Mode parent authority is an app-global PIN or password, not Android's
|
||||
screen lock, device credential, or biometric prompt. The app stores only
|
||||
independently salted PBKDF2-HMAC-SHA256 verifiers (310,000 iterations) for the
|
||||
parent credential and a one-time six-word recovery phrase in app-private DataStore.
|
||||
The phrase uses six distinct words from a 128-word app vocabulary (about 42 bits)
|
||||
to favor accurate reading, typing, and parent-to-parent handoff for this client policy.
|
||||
Verification uses constant-time byte comparison and a persisted, capped backoff.
|
||||
Missing, malformed, unsupported, or weakened records fail closed. Enrollment is
|
||||
allowed only when the record is missing; changing it requires the current
|
||||
credential, and recovery reset requires the current recovery phrase. Both
|
||||
successful rotation paths issue a new recovery phrase and invalidate the old one.
|
||||
An authenticated parent may remove the app-global credential without the
|
||||
recovery phrase; the same atomic write sets every supervised policy to disabled
|
||||
while preserving its pinned profile, capability toggles, appearance, visibility,
|
||||
session controls, and relock settings.
|
||||
If both the credential and recovery phrase are lost, the supported local escape
|
||||
hatch is Android Settings → Apps → Hermes-Relay → Storage → Clear data.
|
||||
An existing enabled policy from before this credential scheme has no safe parent
|
||||
identity to migrate, so it remains restricted and requires local app-data reset
|
||||
and supervised reconfiguration rather than silently trusting a device user.
|
||||
|
||||
---
|
||||
|
||||
## 3. Architecture
|
||||
@@ -59,7 +81,8 @@ token, terminal/bridge grants, and optional network candidates.
|
||||
|
||||
```
|
||||
Android app
|
||||
|-- Vanilla Hermes chat -> dashboard /api/ws, then API-server SSE fallback
|
||||
|-- Vanilla Hermes chat -> dashboard /api/ws (transport-affine)
|
||||
|-- API-only chat -> API-server SSE compatibility routes
|
||||
|-- Vanilla Hermes Manage -> dashboard /api/*
|
||||
|-- Vanilla Hermes voice -> dashboard /api/audio/*
|
||||
|-- Relay terminal -> Tailscale Serve WSS, or opt-in Hermes Secure Link :9443/relay/ws
|
||||
@@ -90,7 +113,7 @@ A saved **Connection** represents one Hermes installation, not one transport.
|
||||
Its stable identity is independent of endpoint URLs. Dashboard/Gateway is the
|
||||
standard upstream surface; API server and Relay endpoints are optional
|
||||
capabilities that can be discovered, added, removed, and diagnosed separately.
|
||||
The normal UI reports outcomes such as Chat, Manage, Voice, API fallback, and
|
||||
The normal UI reports outcomes such as Chat, Manage, Voice, Direct API, and
|
||||
Relay extensions instead of treating a missing optional endpoint as a broken
|
||||
connection.
|
||||
|
||||
@@ -196,8 +219,9 @@ to attach the PR a coding session created, then the repo-scoped read-only
|
||||
this metadata is optional; older Dashboard and API-server hosts retain the
|
||||
ordinary session row.
|
||||
|
||||
Chat availability is derived only from the authenticated Gateway and supported
|
||||
API-server fallback routes. A Send with no usable route remains fail-closed and
|
||||
Chat availability is derived only from the active conversation owner: the
|
||||
authenticated Gateway or an explicitly API-owned compatibility route. A Send
|
||||
with no usable owner remains fail-closed and
|
||||
surfaces a retryable conversation failure plus secret-free Diagnostics evidence.
|
||||
Profile-owned Gateway history is required to load through that exact profile;
|
||||
an unavailable scoped reader surfaces a history failure instead of accepting an
|
||||
@@ -586,8 +610,8 @@ Bottom navigation bar with 4 tabs:
|
||||
- **Bot group projection** — Android merges the bounded `ui_meta["hermes-bots-groups"]` v3 projection across gateways by durable room identity and newest revision. Rooms and recent messages are visibly read-only; Android does not create, rename, disband, join, send, coordinate member turns, or become a second room-log authority. Binary room images are ignored at this metadata boundary.
|
||||
- **Session drawer** (swipe from left or hamburger icon) — session list with title, timestamp, message count. Create, switch, rename, delete, pin/unpin, and archive/restore. A profile switch marks the replacement list loading before clearing the previous profile's rows and keeps that state until the exact-profile fetch settles, so an empty-state claim never flashes before server truth arrives. The process-owned conversation binding is the single connection/profile/session identity for Chat; selecting an All Profiles row atomically makes its owner the selected agent and persists that profile/session, while merely browsing All Profiles changes no agent state. Lifecycle or locale-driven Activity recreation cannot replace an explicit binding with stale persisted state, and asynchronous list/history/mutation work is accepted only for the binding's exact namespace. A profile lock hides All Profiles and rejects stale/deep-linked cross-profile opens. The All Profiles browser mode otherwise survives Activity state restoration and refetches its rows after recreation. Pin and archive are durable upstream session fields loaded and patched through the owning connection/profile's Dashboard session API; Android does not keep a second local flag registry. Archived rows are requested explicitly so they remain restorable after recreation. Failed mutations roll back the optimistic row, while refresh and deletion reconcile from server truth. When a persisted title is absent, use upstream's first-user-message `preview`, matching the Hermes Desktop session picker; show "Untitled" only when neither value exists.
|
||||
- **Cold profile hydration** — a persisted named profile scopes its Dashboard session directory and last-session restore immediately, before `/api/profiles` metadata is available. Server-default selection waits for the lightweight active-profile scope. Roster, avatars, pets, skills, and model metadata never precede the first directory result. The startup sphere releases after route selection; Chat keeps identity and cached rows mounted while its existing animated status surfaces show Gateway wake, session restore, and directory loading.
|
||||
- **Authoritative session activity** — one composite registry keyed by connection, normalized profile, and durable session id drives the drawer, filters, grouping, animation, accessibility, and the visible composer. Exact pending approval/clarify/sudo/secret/MCP requests produce **Needs input**; the Gateway's process-wide `session.active_list` supplies **Starting**, **Working**, and **Idle**; exact terminal or `session.info {running:false}` can settle the matching generation. Because active-list rows normally have no profile metadata, Android assigns a row only through exact foreground/detached ownership already held by that client, or explicit profile metadata if a future upstream sends it. A bounded REST directory never proves global uniqueness. Unresolved rows create no status. Resolved rows from a partial snapshot may update their exact owners, but disappearance settles a scope only when the successful process-wide snapshot was completely and unambiguously resolved for it. Restart/checkpoint recovery is **Checking**; a failed or unsupported live refresh is **Unavailable**, never inferred Idle. REST `is_active` remains recency metadata only. `process.list` may add a separate **Background work** indicator and never keeps the parent conversation Working. Old socket generations, bare session ids from another profile, and delayed snapshots cannot revive newer settled state.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible Android-owned turn without sending `session.interrupt`; each Android-owned running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Opening, foregrounding, or selecting a saved session without that exact checkpoint is read-only observation: Android warms only the socket, reads profile-scoped history, and polls `session.active_list` without `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`. A Desktop/TUI-owned turn therefore remains owned by its producing client; Android refreshes persisted progress and performs one final history read when the runtime settles. Explicit send/config actions may resume the destination session, explicit Stop still interrupts, and SSE fallback stays single-stream and cancels on navigation.
|
||||
- **Authoritative session activity** — one composite registry keyed by connection, normalized profile, and durable session id drives the drawer, filters, grouping, animation, accessibility, and the visible composer. Exact pending approval/clarify/sudo/secret/MCP requests produce **Needs input**; the Gateway's process-wide `session.active_list` supplies **Starting**, **Working**, and **Idle**; an exact terminal, `session.info {running:false}`, or an exact live/durable active-list row reporting Idle can settle only the matching Android-owned turn and progress generation. Because active-list rows normally have no profile metadata, Android assigns a row through exact foreground/detached ownership already held by that client, explicit profile metadata if a future upstream sends it, or the currently selected passive session when its durable id has exactly one owner in the current connection directory. Duplicate same-id owners across profiles remain unresolved and create no status. Resolved rows from a partial snapshot may update their exact owners, but disappearance settles a scope only when the successful process-wide snapshot was completely and unambiguously resolved for it. Restart/checkpoint recovery is **Checking**; a failed or unsupported live refresh is **Unavailable**, never inferred Idle. REST `is_active` remains recency metadata only. `process.list` may add a separate **Background work** indicator and never keeps the parent conversation Working. Old socket generations, ambiguous bare session ids, delayed snapshots, and snapshots crossed by newer turn events cannot settle or revive a newer generation.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible Android-owned turn without sending `session.interrupt`; each Android-owned running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Opening, foregrounding, or selecting a saved session without that exact checkpoint is read-only observation: Android warms only the socket, reads profile-scoped history, and polls `session.active_list` without `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`. A Desktop/TUI-owned turn therefore remains owned by its producing client; Android refreshes persisted progress and performs one final history read when the runtime settles. Explicit send/config actions may resume the destination session, explicit Stop still interrupts, and Direct API compatibility chat stays single-stream and cancels on navigation.
|
||||
- **Queued Gateway follow-ups** — every local queued item is immutably scoped to its originating connection, profile, stored session, transport, and run generation; only that run's completion can make it eligible, and switching sessions shows only that session's queue. Restored text queues retain the same scope, while unavailable/deleted destinations and non-restorable attachment queues fail visibly instead of following the current composer. Drained messages add `queued: true` to `prompt.submit`; ordinary sends omit the field. Authoritative submit rejections (`4004`, `4018`, `4028`, `4029`, `4030`, `4090`, `5008`, `5070`, and `5071`) preserve the server message and never fall through to API-server SSE.
|
||||
- **Durable composer drafts** — each connection/profile/session owns one app-private draft containing text, quote/edit context, and pending attachment bytes. Metadata and content-addressed blobs live under Android's no-backup directory, are capped at 64 drafts and 128 MB of retained blobs outside the active draft, flush when Chat backgrounds, and are removed after a successful send. Session/profile/connection navigation saves the previous owner before restoring the destination; an opened cross-profile session uses its actual owning profile rather than the global picker.
|
||||
- **Large paste review** — a default-on Chat setting converts any single insertion of at least 5,000 characters into a visible `pasted-text.txt` attachment before the normal message-length limit rejects it. Gateway uses upstream `file.attach`; API-server SSE and proactive Thread paths materialize the same UTF-8 text into the outgoing prompt and remove only the synthetic attachment from that transport, so the behavior never requires Relay or silently drops content.
|
||||
@@ -639,7 +663,7 @@ The bridge UI drives — and is driven by — Tier 5 safety-rails (`BridgeSafety
|
||||
### Settings Tab
|
||||
- **Active agent card (v0.6.0)** — top-of-screen summary card showing the current Connection / Profile / Personality. Tap navigates to Chat and auto-opens the agent sheet via the `openAgentSheet` nav arg, giving Settings-originating users a one-tap path to change agent context without leaving the flow.
|
||||
- **Connections** (v0.6.0+) — lists every paired Hermes server with a per-card status chip. Actions: rename (inline), re-pair (reuses `ConnectionWizard` with `connectionId` nav arg), revoke, remove. Add-connection button launches the standard QR flow. Settings briefly treats a paired + disconnected relay as **Connecting** during the reconnect grace window, then promotes it to **Relay unreachable - tap to reconnect** if the live socket does not recover. API / Relay / Session detail sheets include compact sanitized recent-activity tails, and **Settings -> Diagnostics** shows the consolidated app-level API, relay, session, endpoint, voice, Pair-readiness, credential-store recovery, history-failure, and rejected-Send evidence without secrets. See `docs/decisions.md` §19.
|
||||
- **Connection (single-server settings)** — summary-first detail for one Hermes installation. Dashboard/Gateway health drives standard Chat, Manage, Sessions, and Voice readiness. API fallback and Relay extensions appear as independently optional capabilities. Dashboard/Gateway address and network paths are edited under Routes. Advanced retains only the optional direct API credential, explicit direct Relay endpoint override, and insecure-development controls; missing API or Relay settings never make a healthy Dashboard/Gateway connection look broken. Every Relay QR, enter-code, and show-code method uses the shared connection-scoped Pair flow. Transport security posture and paired-device grants remain visible without leading the normal setup flow with ports or bearer keys.
|
||||
- **Connection (single-server settings)** — summary-first detail for one Hermes installation. Dashboard/Gateway health drives standard Chat, Manage, Sessions, and Voice readiness. Direct API compatibility and Relay extensions appear as independently optional capabilities. Dashboard/Gateway address and network paths are edited under Routes. Advanced retains only the optional direct API credential, explicit direct Relay endpoint override, and insecure-development controls; missing API or Relay settings never make a healthy Dashboard/Gateway connection look broken. Every Relay QR, enter-code, and show-code method uses the shared connection-scoped Pair flow. Transport security posture and paired-device grants remain visible without leading the normal setup flow with ports or bearer keys.
|
||||
- **Chat** — Show reasoning toggle, smooth auto-scroll toggle (live-follow streaming, default on), show token usage toggle, app context prompt toggle, tool call display (Off/Compact/Detailed), streaming endpoint selector (`auto` / `sessions` / `runs`), Stats for Nerds (analytics charts)
|
||||
- **Voice** — route-aware voice engine selector (`Vanilla Hermes` via dashboard audio, `Relay Voice Output`, and experimental `Realtime Agent`), global interaction mode (tap / hold / continuous), silence threshold slider, a final-answer-only speech policy, Auto-TTS toggle, selected-engine cards for dashboard or relay-backed settings, language picker, and a Test Current Engine card. Final-answer-only keeps tool/service progress and intermediate commentary visual while both voice engines wait to speak the settled answer; approvals, confirmation questions, and blocking failures remain actionable. Vanilla Hermes voice depends on Manage/dashboard auth; Relay-backed engines run a fast relay health preflight before uploading audio or opening a realtime provider session so a hung relay surfaces as a connection error instead of an indefinite Thinking state.
|
||||
- **Notification companion** — opt-in status, "Open Android Settings" action, test notification dump
|
||||
@@ -690,13 +714,15 @@ HTTP routes registered by `create_app()` in `plugin/relay/server.py`:
|
||||
| `/api/profiles/{name}/soul` | GET | Profile-scoped raw `SOUL.md` read. Returns `{profile, path, content, exists, size_bytes}` with optional `truncated: true` when content exceeds the 200KB inline cap. Absent SOUL.md returns 200 with `exists: false` and an empty content string so the Inspector can distinguish "no soul" from transport failure. Same auth model as `/config`. 404 on unknown profile; 500 `{error: "soul_read_failed"}` on decode error. See §22 in decisions.md. |
|
||||
| `/api/profiles/{name}/memory` | GET | Profile-scoped memory listing. Returns `{profile, memories_dir, entries: [{name, filename, path, content, size_bytes, truncated}], total}` for `*.md` files directly under `<profile>/memories/` (non-recursive). Ordering: `MEMORY.md` first, `USER.md` second, remainder alphabetical. Each entry capped at 50KB inline with `truncated: true` when larger. Absent memories dir → 200 with empty `entries` array. Same auth model as `/config`. 404 on unknown profile. See §22 in decisions.md. |
|
||||
|
||||
### 6.2 Chat — Dashboard/Gateway Primary with Optional API Fallback
|
||||
### 6.2 Chat — Dashboard/Gateway Primary with Explicit API Compatibility
|
||||
|
||||
Chat bypasses the Relay server entirely. In `Auto`, Android uses the upstream
|
||||
dashboard `/api/ws` gateway when dashboard auth is ready because that is the
|
||||
vanilla upstream path with live thinking/reasoning events. When that gateway is
|
||||
unavailable, Android falls back to API-server SSE routes. The native Sessions
|
||||
API fallback looks like:
|
||||
Chat bypasses the Relay server entirely. In `Auto`, a standard saved connection
|
||||
uses the upstream dashboard `/api/ws` gateway because that is the vanilla
|
||||
upstream path with live thinking/reasoning events. That owner is stable: sign-in
|
||||
expiry or a temporary route failure preserves the transcript and draft and
|
||||
offers sign-in/retry; it never dispatches the turn to another database. A
|
||||
legacy API-only record or an explicit advanced Direct API selection uses the
|
||||
API-server SSE routes. The native Sessions compatibility path looks like:
|
||||
|
||||
Model inventory also stays upstream-owned. Android may call the optional Relay
|
||||
`POST /relay/model-capabilities` route to refine reasoning-effort choices for
|
||||
@@ -1183,7 +1209,7 @@ See `docs/decisions.md` → **Voice Mode — Architecture** for the historical b
|
||||
|
||||
## 8. Current Scope
|
||||
|
||||
As of v1.0.0, the current scope is maintaining the vanilla-Hermes-first contract while keeping Relay power features additive and cleanly manageable. Vanilla Hermes Dashboard/Gateway chat, Manage, sessions, and dashboard voice must continue to work against unmodified upstream Hermes without an API-server or Relay requirement. API fallback remains optional and Relay work should be plugin-owned, diagnosable through `hermes relay doctor`, and removable without becoming a hidden requirement for the vanilla Hermes app path.
|
||||
As of v1.0.0, the current scope is maintaining the vanilla-Hermes-first contract while keeping Relay power features additive and cleanly manageable. Vanilla Hermes Dashboard/Gateway chat, Manage, sessions, and dashboard voice must continue to work against unmodified upstream Hermes without an API-server or Relay requirement. Direct API compatibility remains optional and Relay work should be plugin-owned, diagnosable through `hermes relay doctor`, and removable without becoming a hidden requirement for the vanilla Hermes app path.
|
||||
|
||||
**Still non-goals for the current cadence:**
|
||||
- Biometric session lock (fingerprint/face gate on terminal and/or chat resume). Tracked under Phase 4.
|
||||
@@ -1231,7 +1257,7 @@ Current Android dependency versions. Source of truth is `gradle/libs.versions.to
|
||||
| Surface | How We Connect |
|
||||
|---------|---------------|
|
||||
| **Gateway chat** | Dashboard `/api/auth/ws-ticket` + `/api/ws` for live thinking/reasoning and session-scoped `image.attach_bytes` / `pdf.attach` / `file.attach` uploads when Manage auth is ready |
|
||||
| **API-server chat fallback** | `/api/sessions/*/chat/stream`, `/v1/chat/completions`, or `/v1/runs` based on capability probes; a known selected multiplex profile uses the shared listener's `/p/<profile>` prefix and its own encrypted profile credential |
|
||||
| **API-only compatibility chat** | `/api/sessions/*/chat/stream`, `/v1/chat/completions`, or `/v1/runs` based on capability probes; a known selected multiplex profile uses the shared listener's `/p/<profile>` prefix and its own encrypted profile credential |
|
||||
| **API-server sessions** | `GET/POST/PATCH/DELETE /api/sessions` for CRUD |
|
||||
| **Manage** | Dashboard `/api/status`, `/api/auth/me`, `/api/config`, `/api/profiles/*`, `/api/env`, `/api/model/*`, `/api/mcp/*` |
|
||||
| **Vanilla Hermes voice** | Dashboard `POST /api/audio/transcribe`, WebSocket `/api/audio/speak-stream`, and `POST /api/audio/speak` compatibility fallback, all scoped by the selected profile when present |
|
||||
|
||||
@@ -34,15 +34,15 @@ Verified upstream source snapshot:
|
||||
|
||||
| Surface | Owner | Requires Relay | Android usage | Notes |
|
||||
|---------|-------|----------------|---------------|-------|
|
||||
| `/v1/capabilities` | Upstream API server | No | Optional fallback capability probe | Source of truth for API-server features; current upstream advertises no audio API. |
|
||||
| `/v1/chat/completions` | Upstream API server | No | Chat fallback | OpenAI-compatible streaming. Tool events may degrade to inline annotations. |
|
||||
| `/v1/runs`, `/v1/runs/{id}/events` | Upstream API server | No | Chat fallback | Structured run events and stop/approval support. |
|
||||
| `/v1/capabilities` | Upstream API server | No | Direct API capability probe | Source of truth for API-server features; current upstream advertises no audio API. |
|
||||
| `/v1/chat/completions` | Upstream API server | No | API-only compatibility chat | OpenAI-compatible streaming. Tool events may degrade to inline annotations. |
|
||||
| `/v1/runs`, `/v1/runs/{id}/events` | Upstream API server | No | API-only compatibility chat | Structured run events and stop/approval support. |
|
||||
| Dashboard `/api/health` | Upstream dashboard | No | Route/process readiness | Lightweight canonical readiness probe used by official Desktop. Android falls back to `/api/status` only for confirmed legacy hosts without this route; transient failures never trigger the heavyweight fallback. |
|
||||
| `/api/sessions/*` | Upstream Dashboard/Gateway and API server | No | Primary profile-scoped session directory/history or optional SSE fallback | Native upstream session list/create/read/update/delete/messages/fork/chat/chat-stream. The standard Android drawer and stored-history reader use authenticated Dashboard REST independently of `/api/ws` readiness; the Gateway socket owns live chat and activity, not whether persisted rows may be read. Dashboard lists expose profile-stamped `pinned`/`archived`, accept `archived=exclude\|only\|include`, and PATCH either durable flag in the owning profile DB. The API-server resource also exposes and patches both fields, but its current list omits archived rows and has no archive filter; Android therefore offers restart-safe archive/restore only on the Dashboard path while API-only pinning remains valid. Newer Dashboard hosts also expose single-session JSON export and guarded bulk cleanup; Android must dry-run prune first. The bootstrap no longer injects session CRUD/messages/fork routes; only `/api/sessions/search` remains a compatibility route. |
|
||||
| `/api/sessions/*` | Upstream Dashboard/Gateway and API server | No | Primary profile-scoped Dashboard directory/history or API-only compatibility storage | Native upstream session list/create/read/update/delete/messages/fork/chat/chat-stream. The standard Android drawer and stored-history reader use authenticated Dashboard REST independently of `/api/ws` readiness; the Gateway socket owns live chat and activity, not whether persisted rows may be read. Dashboard lists expose profile-stamped `pinned`/`archived`, accept `archived=exclude\|only\|include`, and PATCH either durable flag in the owning profile DB. The API-server resource also exposes and patches both fields, but its current list omits archived rows and has no archive filter; Android therefore offers restart-safe archive/restore only on the Dashboard path while API-only pinning remains valid. Newer Dashboard hosts also expose single-session JSON export and guarded bulk cleanup; Android must dry-run prune first. The bootstrap no longer injects session CRUD/messages/fork routes; only `/api/sessions/search` remains a compatibility route. |
|
||||
| `/v1/skills`, `/v1/toolsets` | Upstream API server | No | Discovery | Authenticated read-only API-server skill/toolset inventory; Android Diagnostics summarizes enabled toolsets and Relay tool visibility. |
|
||||
| Dashboard `/api/status`, `/api/auth/me` | Upstream dashboard | No | Manage auth and post-selection diagnostics | Dashboard cookie/session path; separate from API bearer. Optional status diagnostics include Nous bootstrap validity, resource pressure, and profile/gateway topology; these do not gate transport selection. |
|
||||
| Dashboard `/api/auth/ws-ticket`, `/api/ws` | Upstream dashboard/tui_gateway | No | Preferred chat transport | Vanilla Hermes gateway chat path with live reasoning/thinking events. `message.complete` is the ordinary terminal event; `session.info {running:false}` is the authoritative settle backstop when a replacement socket missed that terminal frame. A reconnect reactivates the exact live runtime with `session.activate`; durable `session.resume` remains the cold-open path and an explicit rejection never creates a replacement context. |
|
||||
| Gateway `session.active_list` | Upstream tui_gateway | No | Authoritative process-wide live activity | Returns attachable runtimes across the Gateway process, with live `id`, durable `session_key`, and `starting`, `working`, `waiting`, or `idle`. The only optional selector is `current_session_id`; rows normally carry no profile metadata. Android attributes a row only from exact foreground/detached ownership already held by that client, or from explicit profile metadata if a future upstream sends it. A bounded REST directory never proves global uniqueness. Unresolved rows remain unattributed, and absence settles a scope only after a complete, unambiguously resolved successful snapshot. Method-not-found or refresh failure is Unavailable, not Idle. Pending input outranks running work. |
|
||||
| Gateway `session.active_list` | Upstream tui_gateway | No | Authoritative process-wide live activity | Returns attachable runtimes across the Gateway process, with live `id`, durable `session_key`, and `starting`, `working`, `waiting`, or `idle`. The only optional selector is `current_session_id`; rows normally carry no profile metadata. Android attributes a row from exact foreground/detached ownership already held by that client, explicit profile metadata if a future upstream sends it, or a unique match to the currently selected passive session in the current connection directory. Duplicate same-id owners across profiles remain unresolved. An exact live/durable Idle row may settle only the same Android-owned turn and unchanged progress generation when a terminal frame is missing; it never claims a passively observed Desktop/TUI turn. Unresolved rows stay unattributed, and absence settles a scope only after a complete, unambiguously resolved successful snapshot. Method-not-found or refresh failure is Unavailable, not Idle. Pending input outranks running work. |
|
||||
| Dashboard `model.options` / `/api/model/*` | Upstream dashboard/tui_gateway | No | Provider/model inventory and selection | Source of truth for coherent provider/model identities. A reasoning boolean or exact effort list is consumed when present; clients do not infer provider identity from a model string alone. |
|
||||
| Gateway `pet.info`, `pet.gallery`, `pet.select`, `pet.disable` | Upstream tui_gateway | No | Profile-scoped animated companion | `pet.info` supplies bounded PNG/WebP sheet bytes, revision, geometry, real frame counts, loop timing, scale, and row taxonomy. Android passes `knownRevision` to avoid duplicate sheet transfer, renders the active pet through its native activity-aware companion, and keeps phone-local pet packs separate. All four RPCs carry the effective profile. |
|
||||
| Dashboard `/api/audio/transcribe`, `/api/audio/speak-stream`, `/api/audio/speak` | Upstream dashboard | No | Vanilla Hermes voice | Manage sign-in unlocks Vanilla Hermes voice. Assistant text streams into upstream speech when available; older hosts fall back to whole-request speech before audio starts. API server has no `/v1/audio/*` route today. |
|
||||
@@ -168,7 +168,7 @@ capabilities, not identity:
|
||||
| Surface | Product role | Required for the standard path |
|
||||
|---------|--------------|--------------------------------|
|
||||
| Dashboard/Gateway | Primary chat, auth, sessions, Manage, and Vanilla Hermes voice | Yes |
|
||||
| API server | Automatic chat fallback and advanced headless compatibility | No |
|
||||
| API server | Explicit API-only and advanced headless compatibility | No |
|
||||
| Relay | Pairing, terminal, bridge/device control, media, and enhanced voice; normally reached through the Dashboard plugin ingress | No |
|
||||
|
||||
Existing API-only records and headless deployments remain supported compatibility
|
||||
@@ -181,10 +181,10 @@ The app should present Vanilla Hermes as the default path:
|
||||
|
||||
1. Connect to and authenticate with the Dashboard/Gateway.
|
||||
2. Use gateway chat when `/api/ws` is ready.
|
||||
3. Discover or accept an API server as an optional automatic fallback; otherwise
|
||||
keep the connection healthy with API fallback marked unavailable.
|
||||
4. When needed, fall back to API-server
|
||||
SSE.
|
||||
3. Keep any discovered API server as an optional compatibility capability; it
|
||||
does not alter the owner of the active Dashboard conversation.
|
||||
4. Use API-server SSE only for a legacy API-only record or an explicit advanced
|
||||
Direct API selection/new chat.
|
||||
5. Use Vanilla Hermes dashboard voice when audio routes are present.
|
||||
6. Offer Relay pairing only for Relay-owned power features. Prefer the
|
||||
Dashboard-origin plugin ingress advertised by pairing; retain a direct Relay
|
||||
@@ -233,7 +233,7 @@ keeping route ownership explicit:
|
||||
- Connection/profile ownership plus request generation are rechecked before
|
||||
publication, so a late response cannot populate a newer profile selection.
|
||||
|
||||
## API Fallback Compatibility Details
|
||||
## Direct API Compatibility Details
|
||||
|
||||
- Dashboard/API session-list `is_active` is a persistence-recency hint: an
|
||||
unended row whose `last_active` is less than five minutes old. It is not a
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -53,7 +53,7 @@ function normalizeRoute(endpoint, index, globalPayload, endpointCount) {
|
||||
const surfaces = [
|
||||
dashboard ? { surface: "dashboard", label: "Dashboard", url: dashboard } : null,
|
||||
relay ? { surface: "relay", label: "Relay", url: relay } : null,
|
||||
api ? { surface: "api", label: "API fallback", url: api } : null,
|
||||
api ? { surface: "api", label: "Direct API", url: api } : null,
|
||||
].filter(Boolean);
|
||||
const issues = [];
|
||||
|
||||
@@ -72,7 +72,7 @@ function normalizeRoute(endpoint, index, globalPayload, endpointCount) {
|
||||
issues.push("public: Relay must use WSS");
|
||||
}
|
||||
if (api && !api.startsWith("https://")) {
|
||||
issues.push("public: API fallback must use HTTPS");
|
||||
issues.push("public: Direct API must use HTTPS");
|
||||
}
|
||||
} else if (normalizedRole === "public_legacy") {
|
||||
if (!relay) issues.push("public_legacy: missing Relay route");
|
||||
|
||||
@@ -149,7 +149,7 @@ function TailscaleCard({ status, onEnable, onDisable, busy, resultMessage }) {
|
||||
<div className="flex items-center gap-2">
|
||||
<Dot tone={apiServing ? "ok" : "muted"} />
|
||||
<span>
|
||||
API fallback → host :8642: {apiServing
|
||||
Direct API → host :8642: {apiServing
|
||||
? `active on ${listenerLabel(apiService)} · optional`
|
||||
: "off"}
|
||||
</span>
|
||||
|
||||
@@ -41,7 +41,7 @@ test("remote access presents Dashboard ingress and keeps direct Relay explicitly
|
||||
const source = read("../src/tabs/RemoteAccess.jsx");
|
||||
|
||||
assert.match(source, /Dashboard → host :9119/);
|
||||
assert.match(source, /API fallback → host :8642/);
|
||||
assert.match(source, /Direct API → host :8642/);
|
||||
assert.match(source, /Direct Relay → host :8767/);
|
||||
assert.match(source, /serve_services/);
|
||||
assert.match(source, /listen_ports/);
|
||||
|
||||
@@ -194,7 +194,7 @@ test("malformed or plaintext public candidates block the invite receipt", () =>
|
||||
assert.deepEqual(receipt.blockingIssues, [
|
||||
"public: Dashboard must use HTTPS",
|
||||
"public: Relay must use WSS",
|
||||
"public: API fallback must use HTTPS",
|
||||
"public: Direct API must use HTTPS",
|
||||
]);
|
||||
|
||||
assert.match(
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
name: hermes-relay
|
||||
manifest_version: 2
|
||||
# Temporary v1 shim for Hermes installers that reject manifests the runtime supports; see TODO.md.
|
||||
manifest_version: 1
|
||||
api_version: 1
|
||||
version: 1.11.0
|
||||
description: "Hermes-Relay plugin for QR pairing, relay sessions, dashboard management, remote desktop/phone tooling, and optional legacy compatibility diagnostics. Standard chat, Manage, and dashboard voice remain vanilla upstream Hermes surfaces."
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Regression coverage for the temporary Hermes installer compatibility manifest."""
|
||||
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
PLUGIN_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ManifestCompatibilityTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.manifest = yaml.safe_load(
|
||||
(PLUGIN_ROOT / "plugin.yaml").read_text(encoding="utf-8")
|
||||
)
|
||||
|
||||
def test_declares_installer_compatible_manifest_version(self) -> None:
|
||||
self.assertEqual(self.manifest["manifest_version"], 1)
|
||||
|
||||
def test_retains_additive_metadata_for_current_hosts(self) -> None:
|
||||
self.assertEqual(self.manifest["api_version"], 1)
|
||||
self.assertEqual(
|
||||
self.manifest["python_dependencies"],
|
||||
[
|
||||
"requests>=2.28.0,<3",
|
||||
"aiohttp>=3.14.1,<4",
|
||||
"segno>=1.6.0,<2",
|
||||
"pyyaml>=6.0,<7",
|
||||
"httpx>=0.25.0,<1",
|
||||
"websocket-client>=1.8.0,<2",
|
||||
],
|
||||
)
|
||||
self.assertEqual(self.manifest["license"], "MIT")
|
||||
self.assertEqual(
|
||||
self.manifest["homepage"],
|
||||
"https://github.com/Codename-11/hermes-relay",
|
||||
)
|
||||
self.assertEqual(
|
||||
self.manifest["tags"],
|
||||
["android", "dashboard", "gateway", "relay", "remote-access", "voice"],
|
||||
)
|
||||
|
||||
def test_retains_v1_hook_declarations(self) -> None:
|
||||
self.assertEqual(
|
||||
self.manifest["provides_hooks"],
|
||||
["on_session_start", "pre_llm_call", "post_llm_call"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -29,8 +29,8 @@ Run this from the `hermes-android/` repo root, or wherever `relay_server/` is lo
|
||||
### As a Hermes plugin + relay
|
||||
|
||||
```bash
|
||||
# 1. Install the Android plugin (18 android_* tools)
|
||||
cp -r plugin ~/.hermes/plugins/hermes-relay
|
||||
# 1. Install and enable the native Hermes plugin
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
|
||||
# 2. Install relay dependencies
|
||||
pip install -r relay_server/requirements.txt
|
||||
|
||||
@@ -34,7 +34,7 @@ Operators with the Hermes dashboard open can also mint the same QR from the web
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Hermes-Relay plugin installed into the Hermes venv.** Verify by running `python -m plugin.pair --help` — if it errors with `ModuleNotFoundError: No module named 'plugin'`, install it first: `pip install -e <path-to-hermes-relay-repo>`.
|
||||
1. **Hermes-Relay plugin installed and enabled.** Verify with `hermes pair --help`. If the command is unavailable, run `hermes plugins install Codename-11/hermes-relay/plugin --enable`. Use the full `install.sh` path instead only when the host also needs the relay service, editable package, and shell shims.
|
||||
2. **Hermes API server reachable** on `API_SERVER_HOST:API_SERVER_PORT` (default `127.0.0.1:8642`). `plugin.pair` auto-reads this from `~/.hermes/config.yaml` → `~/.hermes/.env` → env vars → defaults.
|
||||
3. **Relay server running** on `RELAY_HOST:RELAY_PORT` (default `0.0.0.0:8767`) if the user wants terminal/bridge channels. The Relay may stay host-internal: current Android pairing normally reaches it through the Dashboard's same-origin plugin transport. Tailscale Serve normally exposes dedicated HTTPS `10443` and proxies the host-local Dashboard on `9119`; a raw LAN/tailnet route may reach `9119` directly. Listener `443` is an advanced explicit override only when it is free. Without a live relay, the QR will configure chat only.
|
||||
4. **Host is Linux or macOS.** The relay uses a real PTY backend, which is POSIX-only. Windows hosts can generate API-only QRs but the terminal channel will not work.
|
||||
@@ -46,7 +46,7 @@ Operators with the Hermes dashboard open can also mint the same QR from the web
|
||||
2. **Generate the QR** — run via the `terminal` tool:
|
||||
|
||||
```bash
|
||||
python -m plugin.pair
|
||||
hermes pair
|
||||
```
|
||||
|
||||
When the current Hermes surface exposes an exact Dashboard origin, pass it
|
||||
@@ -65,7 +65,7 @@ Operators with the Hermes dashboard open can also mint the same QR from the web
|
||||
explicitly selects that advanced listener and confirms it is free. Never
|
||||
substitute the API server URL or infer public port `8767`.
|
||||
|
||||
If `python` resolves to the wrong interpreter (plugin not found), use the Hermes venv explicitly:
|
||||
On a full-relay or legacy editable install where an older Hermes host cannot register plugin CLI commands, use the Hermes venv explicitly:
|
||||
|
||||
```bash
|
||||
~/.hermes/hermes-agent/venv/bin/python -m plugin.pair
|
||||
@@ -156,7 +156,7 @@ Pass `--transport-hint wss` only when you know the relay is actually running beh
|
||||
## Pitfalls
|
||||
|
||||
- **Relay not running.** `plugin.pair` prints `[info] Relay not running ... QR will configure chat only` and renders an API-only QR. Terminal tab will then ask the user to paste a pairing code manually. Fix: start the relay first (`hermes relay start`) and re-run.
|
||||
- **Plugin not installed.** `ModuleNotFoundError: No module named 'plugin'`. Fix: `pip install -e <hermes-relay-repo>` into the same Python environment Hermes uses. Use `which python` / `where python` to confirm you're targeting the Hermes venv.
|
||||
- **Plugin not installed.** If `hermes pair --help` is unavailable, run `hermes plugins install Codename-11/hermes-relay/plugin --enable`. Use `install.sh` for the full relay/service/shim setup rather than constructing a manual editable install.
|
||||
- **Wrong venv.** If `hermes` CLI is global but plugin is in the Hermes venv, `python -m plugin.pair` may resolve to the wrong Python. Call the venv Python explicitly: `~/.hermes/hermes-agent/venv/bin/python -m plugin.pair`.
|
||||
- **Pairing code expired.** 10-minute TTL, one-shot. Re-run `python -m plugin.pair` to mint a fresh code; the previous code is automatically invalidated on the next run.
|
||||
- **QR won't scan on terminal.** Likely causes: terminal font too small (zoom in), dark-mode color inversion mangling the blocks, or terminal lacks Unicode half-block support. Fix: re-run with `--png` and point the camera at the saved image, or open the PNG in an image viewer on a second screen.
|
||||
|
||||
@@ -81,7 +81,7 @@ Do NOT use this skill to start or install the relay server itself — that is a
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Hermes-Relay plugin installed into the Hermes venv.** Verify by running `python -m plugin.status --help` — if it errors with `ModuleNotFoundError: No module named 'plugin'`, install it first: `pip install -e <path-to-hermes-relay-repo>`.
|
||||
1. **Hermes-Relay plugin installed and enabled.** Verify with `hermes plugins show hermes-relay`. If it is missing, run `hermes plugins install Codename-11/hermes-relay/plugin --enable`. The standalone `python -m plugin.status` fallback additionally requires the full `install.sh` editable-package path.
|
||||
2. **Relay server running** on `RELAY_HOST:RELAY_PORT` (default `0.0.0.0:8767`). Without a live relay, this skill exits with code `1` and a "relay unreachable" error.
|
||||
3. **Phone has connected at least once** since the last relay restart. The relay tracks live phone-*connection* state in memory, so a restart clears that presence — the phone **reconnects** automatically (its paired session persists across restart, so no re-pair is needed). Until then, status returns "no phone connected" with exit code `2`.
|
||||
|
||||
@@ -119,7 +119,7 @@ Do NOT use this skill to start or install the relay server itself — that is a
|
||||
## Pitfalls
|
||||
|
||||
- **Relay not running.** `status` prints `[error] Cannot reach hermes-relay on 127.0.0.1:8767` to stderr and exits `1`. Fix: start the relay first (`systemctl --user start hermes-relay` or `python -m plugin.relay --no-ssl`) and re-run.
|
||||
- **Plugin not installed.** `ModuleNotFoundError: No module named 'plugin'`. Fix: `pip install -e <hermes-relay-repo>` into the same Python environment Hermes uses. Use `which python` / `where python` to confirm you're targeting the Hermes venv.
|
||||
- **Plugin not installed.** If `hermes plugins show hermes-relay` fails, run `hermes plugins install Codename-11/hermes-relay/plugin --enable`. Use `install.sh` when the host also needs the relay service, editable package, and shell shims.
|
||||
- **Wrong venv.** If `hermes` CLI is global but plugin is in the Hermes venv, `python -m plugin.status` may resolve to the wrong Python. Call the venv Python explicitly: `~/.hermes/hermes-agent/venv/bin/python -m plugin.status`.
|
||||
- **Phone shows as disconnected immediately after a relay restart.** Expected — the relay holds phone state in memory and wipes it on restart. The phone reconnects automatically on its next ping cycle (within ~30s). If it doesn't, check the phone side: the session token may need re-pairing via `/hermes-relay-pair`.
|
||||
- **`bridge.accessibility_granted = false` but everything else looks fine.** The user has opened the Android app but not yet granted the Hermes-Relay accessibility service. Tell them: "Open Hermes-Relay → Bridge screen → the permission checklist will have Accessibility as the top row. Tap it to open Android Settings → Installed services → Hermes-Relay and flip the switch."
|
||||
|
||||
@@ -123,6 +123,23 @@ class FixtureTestCase(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(["user", "assistant"], [row["role"] for row in history["messages"]])
|
||||
self.assertEqual(2, history["pagination"]["returned"])
|
||||
|
||||
async def test_compaction_status_repeats_before_terminal_completion(self) -> None:
|
||||
fixture, base_url = await self.start("compaction_status")
|
||||
ws, _ = await self.connect(base_url)
|
||||
await self.rpc(ws, 1, "prompt.submit", {"text": "fixture"})
|
||||
frames = await self.frames_until(
|
||||
ws,
|
||||
lambda frame: frame.get("params", {}).get("type") == "message.complete",
|
||||
)
|
||||
events = [frame["params"] for frame in frames if frame.get("method") == "event"]
|
||||
compacting = [
|
||||
event for event in events
|
||||
if event.get("type") == "status.update"
|
||||
and event.get("payload", {}).get("kind") == "compacting"
|
||||
]
|
||||
self.assertEqual(2, len(compacting))
|
||||
self.assertEqual("message.complete", events[-1]["type"])
|
||||
|
||||
async def test_cross_client_observer_never_claims_or_interrupts_producer(self) -> None:
|
||||
fixture, base_url = await self.start("cross_client_observation")
|
||||
producer, _ = await self.connect(base_url)
|
||||
@@ -138,6 +155,7 @@ class FixtureTestCase(unittest.IsolatedAsyncioTestCase):
|
||||
await self.rpc(observer, 3, "session.active_list")
|
||||
active = (await observer.receive_json())["result"]["sessions"]
|
||||
self.assertEqual("working", active[0]["status"])
|
||||
self.assertNotIn("profile", active[0])
|
||||
async with self.session.get(
|
||||
f"{base_url}/api/sessions/{fixture.scenario.stored_session_id}/messages",
|
||||
params={"profile": "default", "limit": 500, "offset": 0, "order": "asc"},
|
||||
@@ -221,6 +239,37 @@ class FixtureTestCase(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(fixture.scenario.live_session_id, events[-1]["session_id"])
|
||||
self.assertNotIn("message.complete", [event["type"] for event in events])
|
||||
|
||||
async def test_active_list_idle_settles_without_message_complete(self) -> None:
|
||||
fixture, base_url = await self.start("terminal_gap_active_list")
|
||||
ws, _ = await self.connect(base_url)
|
||||
await self.rpc(ws, 1, "prompt.submit", {"text": "fixture"})
|
||||
frames = await self.frames_until(
|
||||
ws,
|
||||
lambda frame: frame.get("params", {}).get("type") == "message.delta",
|
||||
)
|
||||
for _ in range(50):
|
||||
async with self.session.get(f"{base_url}/__fixture__/state") as response:
|
||||
state = await response.json()
|
||||
if not state["running"]:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
self.assertFalse(state["running"])
|
||||
|
||||
await self.rpc(
|
||||
ws,
|
||||
2,
|
||||
"session.active_list",
|
||||
{"current_session_id": fixture.scenario.live_session_id},
|
||||
)
|
||||
snapshot = (await ws.receive_json())["result"]["sessions"]
|
||||
self.assertEqual("idle", snapshot[0]["status"])
|
||||
self.assertEqual(fixture.scenario.live_session_id, snapshot[0]["id"])
|
||||
self.assertEqual(fixture.scenario.stored_session_id, snapshot[0]["session_key"])
|
||||
self.assertNotIn(
|
||||
"message.complete",
|
||||
[frame.get("params", {}).get("type") for frame in frames],
|
||||
)
|
||||
|
||||
async def test_queued_follow_up_runs_after_first_turn(self) -> None:
|
||||
_, base_url = await self.start("queued_follow_up")
|
||||
ws, _ = await self.connect(base_url)
|
||||
@@ -335,6 +384,7 @@ class ScenarioTestCase(unittest.TestCase):
|
||||
"rapid_tools_interims",
|
||||
"subagent_child_preview",
|
||||
"terminal_gap_activate",
|
||||
"terminal_gap_active_list",
|
||||
"terminal_gap_session_info",
|
||||
"queued_follow_up",
|
||||
"scope_rejection_inputs",
|
||||
@@ -371,6 +421,10 @@ class ScenarioTestCase(unittest.TestCase):
|
||||
),
|
||||
load_scenario("terminal_gap_activate").contract_requirements,
|
||||
)
|
||||
self.assertEqual(
|
||||
("gateway.session_active_list",),
|
||||
load_scenario("terminal_gap_active_list").contract_requirements,
|
||||
)
|
||||
self.assertEqual(
|
||||
("gateway.settled_session_info",),
|
||||
load_scenario("terminal_gap_session_info").contract_requirements,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "compaction_status",
|
||||
"live_session_id": "fixture-live-1",
|
||||
"stored_session_id": "20260831_120000_compaction",
|
||||
"profile": "default",
|
||||
"contract_requirements": [
|
||||
"gateway.message_complete"
|
||||
],
|
||||
"initial_history": [],
|
||||
"turns": [
|
||||
{
|
||||
"steps": [
|
||||
{"op": "event", "type": "message.start"},
|
||||
{"op": "event", "type": "status.update", "payload": {"kind": "compacting", "text": "Compacting context"}},
|
||||
{"op": "sleep", "milliseconds": 50},
|
||||
{"op": "event", "type": "status.update", "payload": {"kind": "compacting", "text": "Compacting context"}},
|
||||
{
|
||||
"op": "persist",
|
||||
"messages": [
|
||||
{"id": 1, "role": "user", "content": "Exercise compaction status.", "timestamp": 1.0},
|
||||
{"id": 2, "role": "assistant", "content": "Compaction finished.", "timestamp": 2.0, "finish_reason": "stop"}
|
||||
]
|
||||
},
|
||||
{"op": "set_running", "value": false},
|
||||
{"op": "event", "type": "message.complete", "payload": {"text": "Compaction finished.", "status": "complete"}}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "terminal_gap_active_list",
|
||||
"live_session_id": "fixture-live-1",
|
||||
"stored_session_id": "20260831_112003_fixture",
|
||||
"profile": "default",
|
||||
"contract_requirements": [
|
||||
"gateway.session_active_list"
|
||||
],
|
||||
"turns": [
|
||||
{
|
||||
"steps": [
|
||||
{"op": "event", "type": "message.start"},
|
||||
{"op": "event", "type": "message.delta", "payload": {"text": "Persisted without a terminal frame."}},
|
||||
{
|
||||
"op": "persist",
|
||||
"messages": [
|
||||
{"id": 1, "role": "user", "content": "Exercise active-list settlement.", "timestamp": 1.0},
|
||||
{"id": 2, "role": "assistant", "content": "Persisted without a terminal frame.", "timestamp": 2.0, "finish_reason": "stop"}
|
||||
]
|
||||
},
|
||||
{"op": "set_running", "value": false}
|
||||
]
|
||||
}
|
||||
],
|
||||
"active_list": {
|
||||
"supported": true,
|
||||
"snapshots": [
|
||||
[
|
||||
{"id": "fixture-live-1", "session_key": "20260831_112003_fixture", "status": "idle", "current": true}
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -145,7 +145,7 @@ The `hermes-relay-tailscale` helper configures a dedicated HTTPS listener
|
||||
(`:10443` by default) for local Dashboard `:9119`, including the plugin's
|
||||
same-origin Relay transport. This avoids conflicts when Traefik, Caddy, nginx,
|
||||
or another service already owns `:443`.
|
||||
The API fallback on `:8642` remains optional:
|
||||
Direct API on `:8642` remains optional:
|
||||
|
||||
```bash
|
||||
hermes-relay-tailscale enable
|
||||
|
||||
@@ -56,9 +56,10 @@ v0.2 ran the bridge as a standalone service on port 8766 (`plugin/tools/android_
|
||||
|
||||
## ADR-4: Chat via Upstream Gateway/API, Not Relay Proxy
|
||||
|
||||
**Decision:** Chat uses upstream Hermes surfaces from the Android app. It
|
||||
prefers the dashboard `/api/ws` gateway when Manage auth is ready, then falls
|
||||
back to Hermes API Server HTTP/SSE. The relay server is only used for bridge,
|
||||
**Decision:** Chat uses upstream Hermes surfaces from the Android app. Standard
|
||||
connections use the Dashboard `/api/ws` Gateway; explicitly configured API-only
|
||||
connections use Hermes API Server HTTP/SSE. A conversation stays bound to its
|
||||
owner instead of moving when readiness changes. The relay server is only used for bridge,
|
||||
terminal, media, notifications, and relay-backed voice channels.
|
||||
|
||||
### Original Approach
|
||||
@@ -70,8 +71,8 @@ Chat was originally proxied through the relay server, which converted SSE respon
|
||||
- The relay was an unnecessary middleman — it just converted upstream events to
|
||||
another WebSocket.
|
||||
- Other Hermes frontends use upstream API or dashboard surfaces without Relay.
|
||||
- The dashboard gateway provides live thinking/reasoning events, while the
|
||||
Sessions API (`/api/sessions/{id}/chat/stream`) provides SSE fallback with rich
|
||||
- The dashboard Gateway provides live thinking/reasoning events, while the
|
||||
Direct API Sessions route (`/api/sessions/{id}/chat/stream`) provides SSE with rich
|
||||
event types.
|
||||
- Simpler, lower latency, removes relay as single point of failure for chat.
|
||||
|
||||
@@ -79,12 +80,12 @@ Chat was originally proxied through the relay server, which converted SSE respon
|
||||
|
||||
```
|
||||
Phone (WS) → Hermes dashboard (:9119) [gateway chat]
|
||||
Phone (HTTP/SSE) → Hermes API Server (:8642) [chat fallback]
|
||||
Phone (HTTP/SSE) → Hermes API Server (:8642) [Direct API chat]
|
||||
Phone (HTTP) → Hermes dashboard (:9119) [Manage + Vanilla Hermes voice]
|
||||
Phone (HTTP/WSS) → Relay Server (:8767) [relay voice, terminal, bridge, notifications]
|
||||
```
|
||||
|
||||
API-server fallback auth uses Bearer token (`API_SERVER_KEY`) when the optional
|
||||
Direct API auth uses a Bearer token (`API_SERVER_KEY`) when the optional
|
||||
API server is enabled. Dashboard gateway auth uses dashboard cookies plus
|
||||
`/api/auth/ws-ticket`.
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
|
||||
## Connection Model
|
||||
|
||||
The app maintains independent connection paths — chat over the upstream Hermes
|
||||
surfaces (preferring the Dashboard Gateway, falling back to API-server SSE), and
|
||||
The app maintains independent connection paths — standard chat over the upstream
|
||||
Dashboard Gateway, explicit API-only chat over Direct API, and
|
||||
persistent WSS for Relay extensions. Relay is optional for the upstream standard
|
||||
path but encouraged for the full current feature set; compatible upstream
|
||||
surfaces take precedence as they ship.
|
||||
@@ -20,8 +20,8 @@ For a compact shareable reference covering connection paths, transport boundarie
|
||||
|
||||
| Path | Protocol | Server | Purpose |
|
||||
|------|----------|--------|---------|
|
||||
| Chat (preferred) | WS | Dashboard origin (local target commonly `:9119`) | Gateway chat via `/api/ws` (`tui_gateway`) — live thinking/reasoning |
|
||||
| Chat (fallback) | HTTP/SSE | API Server `:8642` | Streaming conversations via the Sessions / runs / completions APIs |
|
||||
| Chat (standard) | WS | Dashboard origin (local target commonly `:9119`) | Gateway chat via `/api/ws` (`tui_gateway`) — live thinking/reasoning |
|
||||
| Chat (Direct API) | HTTP/SSE | API Server `:8642` | API-only compatibility conversations via Sessions / runs / completions |
|
||||
| Terminal | WS/WSS | Selected Dashboard origin · same-origin Relay ingress | Remote shell via tmux (Phase 2) |
|
||||
| Bridge | WS/WSS | Selected Dashboard origin · same-origin Relay ingress | Device control via AccessibilityService + MediaProjection (Phase 3) |
|
||||
| Notifications | WS/WSS | Selected Dashboard origin · same-origin Relay ingress | `NotificationListenerService` forwards posted notifications over a bounded channel |
|
||||
@@ -50,7 +50,7 @@ Traefik, Caddy, or nginx listener on `:443`.
|
||||
|
||||
## Chat Message Flow
|
||||
|
||||
When the dashboard gateway is available, the turn rides the `/api/ws` WebSocket (`GatewayChatClient`) and the same lifecycle events arrive over JSON-RPC, with live reasoning. The flow below is the **API-server SSE fallback**, used when there's no dashboard auth yet or the server is older:
|
||||
Standard chats ride the `/api/ws` WebSocket (`GatewayChatClient`) and receive lifecycle events over JSON-RPC with live reasoning. The flow below is the explicit **Direct API** path for API-only/headless compatibility connections:
|
||||
|
||||
<HermesFlow diagram="chat-flow" height="300px" />
|
||||
|
||||
@@ -94,12 +94,12 @@ Pairing codes use the full `A-Z / 0-9` alphabet (36 chars). The pair command (`h
|
||||
|
||||
## Vanilla Hermes chat vs Relay
|
||||
|
||||
Chat uses vanilla upstream Hermes either way (gateway preferred, API-server SSE as fallback); the relay is a separate, optional surface for bridge/terminal/notifications.
|
||||
Chat uses vanilla upstream Hermes either way (Gateway for standard connections, Direct API for API-only compatibility); the relay is a separate, optional surface for bridge/terminal/notifications.
|
||||
|
||||
| Aspect | Vanilla Hermes Chat (gateway / API fallback) | Relay (Bridge/Terminal/Notifications) |
|
||||
| Aspect | Vanilla Hermes Chat (Gateway / Direct API) | Relay (Bridge/Terminal/Notifications) |
|
||||
|--------|----------------------------------------|------------------------|
|
||||
| Protocol | WS (`/api/ws`) preferred · HTTP/SSE fallback | WSS |
|
||||
| Connection | Persistent gateway socket · per-request on SSE fallback | Persistent |
|
||||
| Auth | Dashboard ws-ticket (gateway) · API bearer token (SSE fallback) | Pairing code + session token. Voice endpoints may also accept the API bearer token. |
|
||||
| Protocol | WS (`/api/ws`) for Gateway · HTTP/SSE for Direct API | WSS |
|
||||
| Connection | Persistent Gateway socket · per-request on Direct API | Persistent |
|
||||
| Auth | Dashboard ws-ticket (Gateway) · API bearer token (Direct API) | Pairing code + session token. Voice endpoints may also accept the API bearer token. |
|
||||
| Server | Hermes Dashboard origin · Hermes API `:8642` | Dashboard origin → local `:9119` → internal Relay `:8767` |
|
||||
| Live reasoning | Yes on gateway · post-hoc only on SSE fallback | — |
|
||||
| Live reasoning | Yes on Gateway · post-hoc only on Direct API | — |
|
||||
|
||||
@@ -39,8 +39,8 @@ Android verwendet standardmäßig das Hermes Dashboard/Gateway unter `:9119`.
|
||||
Es stellt Chat, Sitzungen, Anmeldung, Manage und Standard-Voice bereit. Starte
|
||||
es mit `hermes dashboard` und mache diese Adresse für das Telefon erreichbar.
|
||||
|
||||
Der API-Server unter `:8642` ist optional: Er dient als automatischer
|
||||
Chat-Fallback oder für erweiterte headless Kompatibilität. Einen API-Schlüssel
|
||||
Der API-Server unter `:8642` ist optional: Er dient als explizite Direct-API-
|
||||
Verbindung oder für erweiterte headless Kompatibilität. Einen API-Schlüssel
|
||||
brauchst du nur, wenn du diesen optionalen Endpunkt konfigurierst. Der
|
||||
Serverbetreiber erstellt `API_SERVER_KEY` selbst; das Dashboard stellt keinen bereit.
|
||||
|
||||
@@ -67,7 +67,7 @@ unzuverlässig ist; Android prüft eine abweichende Anmeldeadresse vor dem Speic
|
||||
3. Melde dich bei Aufforderung am Dashboard an.
|
||||
4. Tippe auf **Connect** und prüfe **Chat · Ready**.
|
||||
5. Aktiviere unter **Einrichtung abschließen** Android-Benachrichtigungen, wenn du Chat-Hinweise im Hintergrund erhalten möchtest. Kamera, Mikrofon und weitere Funktionen bleiben optional und werden einzeln eingerichtet; mit **Jetzt nicht** kannst du direkt fortfahren.
|
||||
6. Füge API-Fallback, Relay oder weitere Remote-Routen bei Bedarf später unter **Advanced** hinzu.
|
||||
6. Füge Direct API, Relay oder weitere Remote-Routen bei Bedarf später unter **Advanced** hinzu.
|
||||
|
||||
`hermes-relay-tailscale enable` veröffentlicht `https://host.ts.net:10443` auf
|
||||
einem dedizierten Tailnet-Port und leitet an das lokale Dashboard `:9119` samt
|
||||
@@ -75,7 +75,7 @@ gleichnamigem Relay-Pfad weiter. So bleibt `:443` für Traefik, Caddy oder nginx
|
||||
`http://100.x.y.z:9119` funktioniert ebenfalls, besitzt aber kein Anwendungs-TLS.
|
||||
|
||||
Dieselbe Anmeldung schaltet Chat, Sitzungen, Manage und Voice frei. Ein
|
||||
ungepaartes Relay und ein nicht verfügbarer API-Fallback sind normal.
|
||||
ungepaartes Relay und eine nicht verfügbare Direct API sind normal.
|
||||
|
||||
## Empfohlen: Mit Relay vervollständigen {#relay-server-optional}
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ Desktop-Werkzeuge, erweiterte Voice und Device Control empfohlen.
|
||||
- **Chat · Ready** bedeutet, dass du Nachrichten senden kannst.
|
||||
- **Manage** kann noch eine Dashboard-Anmeldung verlangen.
|
||||
- **Voice** wird mit derselben Dashboard-Anmeldung freigeschaltet.
|
||||
- **API fallback** darf als nicht verfügbar angezeigt werden, ohne Chat zu blockieren.
|
||||
- **Direct API** darf als nicht verfügbar angezeigt werden, ohne Chat zu blockieren.
|
||||
- **Relay · Paired** bestätigt die empfohlenen Zusatzfunktionen; ein Relay-Ausfall
|
||||
darf den Upstream-Standardweg nicht blockieren.
|
||||
|
||||
|
||||
@@ -36,10 +36,10 @@ Tailnet-HTTPS `:10443` leitet an das lokale Dashboard `:9119` weiter.
|
||||
- Prüfe Dashboard/Gateway-URL, Anmeldung und `/api/ws`.
|
||||
- Tippe bei einem Fehlerbanner einmal auf **Retry**.
|
||||
- Prüfe die Hermes-Serverprotokolle.
|
||||
- Ein optionaler API-Fallback wird separat geprüft; sein Ausfall blockiert eine gesunde Gateway-Verbindung nicht.
|
||||
- Eine optionale Direct API wird separat geprüft; ihr Ausfall blockiert eine gesunde Gateway-Verbindung nicht.
|
||||
- Bei langen lokalen Modellläufen kann Android die Verbindung im Hintergrund trennen; die fertige Antwort wird nach der Wiederverbindung geladen.
|
||||
|
||||
Wenn der bewusst konfigurierte API-Fallback nicht verfügbar ist, prüfe
|
||||
Wenn die bewusst konfigurierte Direct API nicht verfügbar ist, prüfe
|
||||
`API_SERVER_ENABLED`, die Bind-Adresse, `http://<host>:8642/health`, den
|
||||
vom Serverbetreiber erstellten `API_SERVER_KEY` und die Firewall. Die Dashboard-Anmeldung erzeugt diesen Schlüssel nicht.
|
||||
|
||||
|
||||
@@ -38,8 +38,8 @@ Android usa normalmente el Dashboard/Gateway de Hermes en `:9119`. Proporciona
|
||||
Chat, sesiones, inicio de sesión, Manage y voz estándar. Inícialo con
|
||||
`hermes dashboard` y haz que esa dirección sea accesible desde el teléfono.
|
||||
|
||||
El servidor de API en `:8642` es opcional: sirve como fallback automático de
|
||||
Chat o para compatibilidad headless avanzada. Solo necesitas una clave de API
|
||||
El servidor de API en `:8642` es opcional: sirve como conexión explícita de
|
||||
Direct API o para compatibilidad headless avanzada. Solo necesitas una clave de API
|
||||
si configuras ese endpoint opcional. El operador del servidor crea
|
||||
`API_SERVER_KEY`; el Dashboard no proporciona esa clave.
|
||||
|
||||
@@ -66,7 +66,7 @@ es fiable; Android verifica un origen de inicio de sesión distinto antes de gua
|
||||
3. Inicia sesión en el dashboard cuando se solicite.
|
||||
4. Pulsa **Connect** y comprueba **Chat · Ready**.
|
||||
5. En **Finalizar configuración**, activa las notificaciones de Android si quieres alertas de chat en segundo plano. La cámara, el micrófono y las demás funciones siguen siendo opcionales y se configuran una a una; pulsa **Ahora no** para continuar directamente.
|
||||
6. Añade API fallback, Relay o rutas remotas después desde **Advanced** si lo necesitas.
|
||||
6. Añade Direct API, Relay o rutas remotas después desde **Advanced** si lo necesitas.
|
||||
|
||||
`hermes-relay-tailscale enable` publica `https://host.ts.net:10443` en un puerto
|
||||
dedicado del tailnet y lo redirige al Dashboard local `:9119` con su ruta Relay
|
||||
@@ -74,7 +74,7 @@ del mismo origen. Una ruta deliberadamente directa como
|
||||
`http://100.x.y.z:9119` también funciona, pero no tiene TLS de aplicación.
|
||||
|
||||
La misma sesión habilita Chat, sesiones, Manage y Voice. Es normal que Relay
|
||||
esté sin emparejar y que API fallback no esté disponible.
|
||||
esté sin emparejar y que Direct API no esté disponible.
|
||||
|
||||
## Recomendado: completa la configuración con Relay {#relay-server-optional}
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ herramientas de escritorio, voz mejorada y Device Control.
|
||||
- **Chat · Ready** significa que ya puedes enviar mensajes.
|
||||
- **Manage** puede pedir que inicies sesión en el dashboard.
|
||||
- **Voice** se habilita con esa misma sesión del dashboard.
|
||||
- **API fallback** puede no estar disponible sin bloquear Chat.
|
||||
- **Direct API** puede no estar disponible sin bloquear Chat.
|
||||
- **Relay · Paired** confirma las extensiones recomendadas; un fallo de Relay no
|
||||
debe bloquear el recorrido upstream estándar.
|
||||
|
||||
|
||||
@@ -36,10 +36,10 @@ HTTPS `:10443` del tailnet redirige al Dashboard local `:9119`.
|
||||
- Comprueba la URL del Dashboard/Gateway, la sesión y `/api/ws`.
|
||||
- Si aparece un error, pulsa **Retry** una sola vez.
|
||||
- Revisa los registros del servidor Hermes.
|
||||
- El API fallback opcional se diagnostica por separado; su fallo no bloquea un Gateway saludable.
|
||||
- La Direct API opcional se diagnostica por separado; su fallo no bloquea un Gateway saludable.
|
||||
- Los modelos locales pueden tardar varios minutos; si Android corta la conexión en segundo plano, la respuesta terminada se recuperará al reconectar.
|
||||
|
||||
Si el API fallback configurado intencionadamente no está disponible, comprueba
|
||||
Si la Direct API configurada intencionadamente no está disponible, comprueba
|
||||
`API_SERVER_ENABLED`, la dirección de escucha, `http://<host>:8642/health`, la
|
||||
`API_SERVER_KEY` creada por el operador y el firewall. El inicio de sesión del Dashboard no crea esa clave.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Each connection has a stable ID for one Hermes install and can hold several
|
||||
independent capabilities:
|
||||
|
||||
- Dashboard/Gateway URL (`http(s)://host:9119`) and dashboard session for primary Chat, sessions, Manage, and standard voice
|
||||
- Optional API server URL (`http(s)://host:8642`) and API key for automatic chat fallback or advanced headless compatibility
|
||||
- Optional API server URL (`http(s)://host:8642`) and API key for explicit Direct API or advanced headless compatibility
|
||||
- Optional Relay URL (`ws(s)://host:8767`) and pairing record for Terminal, Bridge, and relay-only power tools
|
||||
- Connection-scoped Dashboard cookies or native sign-in tokens, API credentials,
|
||||
and Relay session credentials; authentication never carries into another
|
||||
@@ -36,7 +36,7 @@ The whole thing takes under a second on a healthy connection.
|
||||
|
||||
Open **Settings → Connections** for the connection **list**. Each card shows the
|
||||
connection's label, an **Active** badge on the one in use, a one-line status, and
|
||||
a compact capability summary (Chat · Manage · Voice · API fallback · Relay) so you can scan the
|
||||
a compact capability summary (Gateway · Manage · Voice · Direct API · Relay) so you can scan the
|
||||
health of every server at a glance. Tap a card to open its **detail** screen.
|
||||
|
||||
With two or more saved connections, **On app start** defaults to **Last used**.
|
||||
@@ -50,8 +50,8 @@ The detail screen is organized into tabs:
|
||||
- **Routes** — shows the primary Dashboard route even when no API or Relay is
|
||||
configured. LAN, Tailscale (`100.x` or `.ts.net`), and public Dashboard routes
|
||||
can be added and tested without API configuration. Optional API routes are
|
||||
only for direct chat fallback on the same networks.
|
||||
- **Advanced** — optional direct API fallback credentials, an explicit direct
|
||||
only for explicit Direct API chat on the same networks.
|
||||
- **Advanced** — optional Direct API credentials, an explicit direct
|
||||
Relay endpoint override, and the development-only insecure-connection toggle.
|
||||
Dashboard addresses stay under **Routes**. **Pair Relay** opens the same shared
|
||||
QR / enter-code / show-code flow used everywhere else.
|
||||
@@ -108,7 +108,7 @@ To validate a local CA on a device or emulator:
|
||||
proxy to present the leaf certificate plus any required intermediate chain.
|
||||
5. Add the HTTPS Dashboard address in Hermes-Relay. Verify Dashboard discovery
|
||||
and sign-in, start a Chat reply to exercise the Gateway WSS route, open
|
||||
Manage, and run a Standard Voice preview. If API fallback or Relay uses the
|
||||
Manage, and run a Standard Voice preview. If Direct API or Relay uses the
|
||||
same private CA, test those capabilities from the connection detail screen.
|
||||
6. Negative-check hostname verification by trying the same server through an
|
||||
address absent from the certificate SAN. It must still fail with a certificate
|
||||
@@ -121,7 +121,7 @@ Pairing and live reachability are shown separately. A connection can still be
|
||||
Relay row shows **Relay unreachable - tap to reconnect** rather than treating
|
||||
the saved session as proof of a live server.
|
||||
|
||||
Tap the Dashboard/Gateway, API fallback, Relay, or Session rows in the active connection's **Overview**
|
||||
Tap the Dashboard/Gateway, Direct API, Relay, or Session rows in the active connection's **Overview**
|
||||
tab to open detail sheets with a compact **Recent activity** tail. The tail shows
|
||||
sanitized API, route, relay, session, and voice events such as health timeouts,
|
||||
selected routes, reconnect attempts, and voice relay checks. Raw payloads, query
|
||||
@@ -144,7 +144,7 @@ rather than being incorrectly marked current.
|
||||
Connection feedback sits where it matters and never covers the nav or shifts the
|
||||
screen. There are really two connections, shown in two places:
|
||||
|
||||
- **Your agent** (the Dashboard/Gateway chat connection, or API fallback when used) shows in the header **subtitle under the agent
|
||||
- **Your agent** (the Dashboard/Gateway chat connection, or Direct API when explicitly used) shows in the header **subtitle under the agent
|
||||
name** — the model line swaps to **Reconnecting…** / **Connecting…** /
|
||||
**Disconnected** (amber or red) and fades back to the model once it recovers, the
|
||||
same place messaging apps show "connecting…". This is the one that tells you whether
|
||||
@@ -163,7 +163,7 @@ A pairing QR can carry multiple endpoint candidates for the same server: LAN, Ta
|
||||
The split is intentional:
|
||||
|
||||
- Standard Chat, sessions, Manage, and voice use the Dashboard/Gateway route.
|
||||
- Optional API fallback uses its own route and bearer only when configured.
|
||||
- Direct API uses its own route and bearer only when configured.
|
||||
- Terminal, bridge, TUI, media, clipboard, profile-file operations, Android
|
||||
control, and Relay voice extensions use the Relay route and require a paired
|
||||
Relay session.
|
||||
@@ -177,7 +177,7 @@ hermes pair --mode auto --prefer tailscale
|
||||
|
||||
The helper publishes dedicated tailnet HTTPS `:10443` for local Dashboard
|
||||
`:9119` and its same-origin Relay path. The dedicated port avoids conflicts
|
||||
with Traefik, Caddy, or nginx on `:443`. The API fallback remains optional on
|
||||
with Traefik, Caddy, or nginx on `:443`. Direct API remains optional on
|
||||
`:8642`; direct Relay `:8767` is legacy compatibility. A manually exposed
|
||||
`http://100.x.y.z:9119` Dashboard also works over the encrypted tailnet, but it
|
||||
is not the recommended helper route and has no application TLS.
|
||||
|
||||
@@ -82,7 +82,7 @@ For support, open **Settings → Diagnostics** and filter to **Auth**. Native si
|
||||
|
||||
This is separate from Relay pairing and from `API_SERVER_KEY`. A dashboard
|
||||
session does not become an API bearer token: Android uses it for primary Gateway
|
||||
chat and asks for an API bearer only when the optional API fallback is configured.
|
||||
chat and asks for an API bearer only when the optional Direct API is configured.
|
||||
Relay-only capabilities — Terminal, Bridge, Relay sessions, Media inspector, and
|
||||
profile memory file editing — stay under **Settings → Power tools** and show
|
||||
**Requires pairing** until the phone has a paired Relay session. Profile
|
||||
@@ -213,7 +213,7 @@ the full backward-compatible wire format.
|
||||
mint again with **Auto**. Dashboard commonly listens locally on `:9119`; the
|
||||
recommended Tailscale route is dedicated external HTTPS `:10443` → local
|
||||
`:9119`. Old `:443`/`:9119` routes remain explicit migration compatibility.
|
||||
Port `:8642` is the optional API fallback. The Relay process may still listen
|
||||
Port `:8642` is the optional Direct API. The Relay process may still listen
|
||||
internally on `:8767`, but that direct port is legacy pairing compatibility and
|
||||
is not advertised in new QRs. Re-pair old clients before explicitly disabling
|
||||
a served `:8767` route.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Vanilla Hermes Chat Transport
|
||||
|
||||
Hermes-Relay talks to your Hermes server's own surfaces for chat — no Hermes-Relay relay plugin is ever in the chat path. By default it **prefers the dashboard gateway** (`/api/ws`, the same `tui_gateway` transport hermes-desktop and the TUI speak) when your Manage sign-in is ready, because that's the only Vanilla Hermes path with **live thinking/reasoning** as it streams. When the gateway isn't available — no dashboard auth yet, an older server, or a forced override — it **falls back to the API server's SSE routes**.
|
||||
Hermes-Relay talks to your Hermes server's own surfaces for chat — no Hermes-Relay relay plugin is ever in the chat path. Standard connections use the dashboard **Gateway** (`/api/ws`, the same `tui_gateway` transport Hermes Desktop and the TUI speak), because that's the Vanilla Hermes path with live thinking/reasoning and full attachment support. That owner is stable: if sign-in expires or Gateway is temporarily unavailable, Android preserves the conversation and offers sign-in or retry instead of sending the turn to another database. Legacy API-only and explicitly selected **Direct API** chats keep using the API server's SSE routes.
|
||||
|
||||
## How It Works
|
||||
|
||||
```
|
||||
Phone (WS) → Hermes dashboard (:9119) [preferred — gateway chat, live thinking]
|
||||
Phone (HTTP/SSE) → Hermes API Server (:8642) [fallback — sessions / runs / completions]
|
||||
Phone (WS) → Hermes dashboard (:9119) [standard — Gateway chat, live thinking]
|
||||
Phone (HTTP/SSE) → Hermes API Server (:8642) [Direct API — sessions / runs / completions]
|
||||
```
|
||||
|
||||
Both paths are **vanilla upstream Hermes** surfaces. The dashboard gateway `/api/ws` is *not* the Hermes-Relay relay (`:8767`); it's a vanilla dashboard endpoint, reached with a short-lived ticket minted from your Manage dashboard session. The Relay plugin is not the owner of standard chat. It is the encouraged extension for current upstream gaps such as Terminal/TUI, notifications, media handoff, desktop tools, Relay sessions, enhanced voice, and optional Device Control; compatible upstream surfaces take precedence as they become available.
|
||||
@@ -22,7 +22,7 @@ were omitted. Multi-text shares preserve each supplied text item in source order
|
||||
Nothing is sent automatically: edit, remove, reorder, or discard the draft, then
|
||||
tap Send when it is ready.
|
||||
|
||||
When it falls back, the app uses the Hermes `/api/sessions` REST API:
|
||||
For an API-only or explicitly selected Direct API chat, the app uses the Hermes `/api/sessions` REST API:
|
||||
|
||||
| Method | Endpoint | Purpose |
|
||||
|--------|----------|---------|
|
||||
@@ -43,15 +43,15 @@ the API server starts. The app sends that server-created value as:
|
||||
Authorization: Bearer <API_SERVER_KEY>
|
||||
```
|
||||
|
||||
The direct API fallback itself is optional. If you enable it, generate a strong
|
||||
Direct API itself is optional. If you enable it, generate a strong
|
||||
server-side key (for example, `openssl rand -hex 32`; upstream requires at least
|
||||
16 characters) and enter the same value in Android.
|
||||
|
||||
When provided, the key is stored in Android's `EncryptedSharedPreferences` using AES-256-GCM encryption backed by the Android Keystore.
|
||||
|
||||
## SSE Streaming (fallback path)
|
||||
## SSE Streaming (Direct API path)
|
||||
|
||||
On the API-server fallback, chat responses stream via Server-Sent Events with these Hermes-native event types. (On the preferred gateway path the same lifecycle arrives over the `/api/ws` WebSocket instead, with live `reasoning.delta`/`thinking.delta` as the model reasons — the API-server SSE surface only surfaces reasoning after the fact via `tool.progress` and the final `run.completed` messages.)
|
||||
On Direct API, chat responses stream via Server-Sent Events with these Hermes-native event types. (On Gateway the same lifecycle arrives over the `/api/ws` WebSocket instead, with live `reasoning.delta`/`thinking.delta` as the model reasons — the API-server SSE surface only surfaces reasoning after the fact via `tool.progress` and the final `run.completed` messages.)
|
||||
|
||||
| Event | Description | Key Fields |
|
||||
|-------|-------------|------------|
|
||||
@@ -71,4 +71,4 @@ On the API-server fallback, chat responses stream via Server-Sent Events with th
|
||||
|
||||
## Why two paths?
|
||||
|
||||
Chat always rides vanilla upstream Hermes — never the Hermes-Relay relay plugin. The gateway `/api/ws` path is preferred because it's the only Vanilla Hermes surface with **live** reasoning streaming and full attachment support, matching what hermes-desktop and the Hermes TUI use. The API-server SSE path is the resilient fallback: it needs only the API server (no dashboard sign-in), works on older builds, and aligns with how other Hermes frontends talk to the API. The app probes both and picks the best available on each connect, so you get live thinking when your server can serve it and a working chat either way.
|
||||
Chat always rides vanilla upstream Hermes — never the Hermes-Relay relay plugin. Gateway `/api/ws` is the standard owner because it provides live reasoning streaming and full attachment support, matching Hermes Desktop and the Hermes TUI. Direct API remains useful for existing API-only/headless deployments, compatibility testing, and an explicit advanced selection. The app probes both surfaces for diagnostics, but reachability never changes the owner of an open conversation.
|
||||
|
||||
@@ -8,7 +8,7 @@ A **<span class="track-badge track-badge--sideload">Sideload only</span>** badge
|
||||
|
||||
| Feature | Description |
|
||||
|---------|-------------|
|
||||
| [Vanilla Hermes Chat Transport](/features/direct-api) | Gateway `/api/ws` (live thinking) preferred, API-server SSE fallback — never the relay |
|
||||
| [Vanilla Hermes Chat Transport](/features/direct-api) | Gateway `/api/ws` for standard chats; explicit Direct API for API-only compatibility — never the relay |
|
||||
| [Voice Mode](/features/voice) | Real-time voice conversation — you talk, the agent answers aloud via your server's configured TTS/STT providers |
|
||||
| [Markdown Rendering](/features/markdown) | Full markdown with syntax-highlighted code blocks |
|
||||
| [Reasoning Display](/features/reasoning) | Collapsible extended-thinking blocks |
|
||||
@@ -18,7 +18,7 @@ A **<span class="track-badge track-badge--sideload">Sideload only</span>** badge
|
||||
| [Personalities](/features/personalities) | Dynamic from `GET /api/config` — picker, agent name on bubbles |
|
||||
| [Command Palette](/guide/chat#slash-commands) | Searchable command browser — 29 gateway commands, personalities, 90+ skills |
|
||||
| [Slash Commands](/guide/chat#slash-commands) | Inline autocomplete as you type `/` |
|
||||
| [Vanilla Hermes Setup](/guide/getting-started#_3-connect-chat) | Connect through the Dashboard/Gateway; add API fallback or Relay later when needed |
|
||||
| [Vanilla Hermes Setup](/guide/getting-started#_3-connect-chat) | Connect through the Dashboard/Gateway; add Direct API or Relay later when needed |
|
||||
| [Token Tracking](/features/tokens) | Per-message usage and cost |
|
||||
| [Tool Progress](/features/tools) | Configurable display — Off, Compact, or Detailed |
|
||||
| [Plugins](/features/plugins) | Native reactive pages, including Relay-assisted agent-created previews |
|
||||
|
||||
@@ -214,7 +214,7 @@ reattaches its live reply, reasoning, tool state, and pending interaction card;
|
||||
if it finished while detached, the saved transcript is loaded instead. Multiple
|
||||
running chats keep separate recovery state across an app restart.
|
||||
|
||||
Tapping **Stop** still interrupts the visible turn. Servers using an SSE fallback
|
||||
Tapping **Stop** still interrupts the visible turn. Direct API connections
|
||||
cannot multiplex live chats, so switching there stops the current stream before
|
||||
opening the next conversation.
|
||||
|
||||
|
||||
@@ -108,9 +108,9 @@ instance with the Dashboard/Gateway enabled. The optional API server is a
|
||||
fallback or headless compatibility surface. The Relay power-user plugin
|
||||
(step 4) additionally needs Python 3.11+ on the server.
|
||||
|
||||
::::details Advanced: add the optional API fallback
|
||||
::::details Advanced: add optional Direct API
|
||||
The standard app path does not require the API server or an API key. Enable this
|
||||
surface when you want automatic SSE fallback or an API-only headless
|
||||
surface when you want an explicit API-only/headless compatibility
|
||||
configuration. Installing Hermes and choosing a provider/model is ordinary
|
||||
Hermes setup, so we defer that to the official docs
|
||||
([Installation](https://hermes-agent.nousresearch.com/docs/getting-started/installation),
|
||||
@@ -148,7 +148,7 @@ hermes gateway
|
||||
iex (irm https://hermes-agent.nousresearch.com/install.ps1)
|
||||
hermes setup --portal # log in / pick a provider — skip if already configured
|
||||
|
||||
# You, the server operator, create this key for the optional API fallback.
|
||||
# You, the server operator, create this key for optional Direct API.
|
||||
# Hermes Dashboard does not supply an API_SERVER_KEY.
|
||||
# Current Hermes requires a usable key of at least 16 characters when the API
|
||||
# server is enabled.
|
||||
@@ -243,7 +243,7 @@ reads and writes `~/.hermes/.env`, which holds your keys and secrets.)
|
||||
Dashboard sign-in on `:9119` uses a native bearer on current gateways, or
|
||||
exact-origin cookies on compatibility gateways, plus short-lived `/api/ws`
|
||||
tickets. It is sufficient for the standard connection. An API key authenticates
|
||||
only the optional API fallback on `:8642`; dashboard login does not create one,
|
||||
only optional Direct API on `:8642`; dashboard login does not create one,
|
||||
and you should not enter a fake key when no API endpoint is configured.
|
||||
:::
|
||||
::::
|
||||
@@ -259,7 +259,7 @@ On first launch:
|
||||
- **Scan setup QR** → scan a current payload with an explicit
|
||||
Dashboard/Gateway URL. Existing API-first QRs remain accepted for legacy
|
||||
and headless configurations.
|
||||
3. Optional: add API fallback, Relay, or remote routes under **Advanced**.
|
||||
3. Optional: add Direct API, Relay, or remote routes under **Advanced**.
|
||||
4. Tap **Connect**.
|
||||
5. On **Finish setup**, enable Android notifications if you want background
|
||||
chat alerts. Camera, microphone, notification companion, and Device Control
|
||||
@@ -363,7 +363,7 @@ signed pairing contract as the Web Dashboard.
|
||||
- Or choose **Show Relay code** in Android, run the displayed
|
||||
`hermes pair --register-code <code>` command on the host, then tap **Connect**.
|
||||
|
||||
Keep manual URL, port, TLS, API fallback, and route-priority overrides under the
|
||||
Keep manual URL, port, TLS, Direct API, and route-priority overrides under the
|
||||
advanced path. The Dashboard's **Auto** pairing mode and the app's confirmed QR
|
||||
receipt should be the default.
|
||||
|
||||
@@ -467,7 +467,7 @@ back to API-server SSE when it is not.
|
||||
1. On the **Connect** page, tap **Hermes**.
|
||||
2. Type your Dashboard/Gateway URL — e.g. `http://192.168.1.100:9119` — or discover it on LAN.
|
||||
3. Sign in through the dashboard's configured provider when prompted.
|
||||
4. Optional: expand **Advanced** to add an API fallback URL/key or Relay route.
|
||||
4. Optional: expand **Advanced** to add a Direct API URL/key or Relay route.
|
||||
5. Tap **Connect**.
|
||||
|
||||
**After onboarding:** open **Settings → Gateways** and select a Hermes host.
|
||||
|
||||
@@ -16,13 +16,12 @@ Relay, and pairing Relay never replaces the upstream connection.
|
||||
|
||||
```
|
||||
Phone (WS) → Hermes dashboard (:9119) [gateway chat with live thinking]
|
||||
Phone (HTTP/SSE) → Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (HTTP/SSE) → Hermes API Server (:8642) [Direct API compatibility, sessions, runs]
|
||||
Phone (HTTP) → Hermes dashboard (:9119) [Manage + Vanilla Hermes voice]
|
||||
Phone (WSS/HTTP) → Relay Server (:8767) [Bridge Core, terminal, TUI, media, relay voice]
|
||||
```
|
||||
|
||||
Chat prefers the dashboard gateway when Manage auth is ready and falls back to
|
||||
the Hermes API Server's SSE routes. The relay server handles Bridge Core,
|
||||
Standard Chat remains on the dashboard Gateway and asks for sign-in or retry when unavailable. API-only and explicitly selected Direct API chats use the Hermes API Server's SSE routes. The relay server handles Bridge Core,
|
||||
terminal, TUI, media, notification companion, relay sessions, and relay-backed
|
||||
voice routes. Sideload builds additionally expose Android Device Control routes.
|
||||
|
||||
@@ -30,7 +29,7 @@ voice routes. Sideload builds additionally expose Android Device Control routes.
|
||||
|
||||
| Feature | Status |
|
||||
|---------|--------|
|
||||
| Chat (Dashboard/Gateway primary, optional API fallback) | Complete |
|
||||
| Chat (Gateway standard, explicit Direct API compatibility) | Complete |
|
||||
| Session management | Complete |
|
||||
| Profiles and personalities | Complete |
|
||||
| Markdown + syntax highlighting | Complete |
|
||||
|
||||
@@ -6,11 +6,11 @@ Hermes-Relay can keep one paired phone connected as it moves between LAN, Tailsc
|
||||
|
||||
Vanilla Hermes setup saves the Dashboard/Gateway address as the standard route.
|
||||
Remote LAN, Tailscale, VPN, or public routes can be added to the same connection
|
||||
and Android uses the highest-priority reachable one. API fallback and Relay
|
||||
and Android uses the highest-priority reachable one. Direct API and Relay
|
||||
routes remain independently optional:
|
||||
|
||||
- **Chat, sessions, Manage, and standard voice** use the Dashboard/Gateway route and its dashboard session.
|
||||
- **API fallback/headless compatibility** uses the API server URL and bearer only when configured.
|
||||
- **Direct API/headless compatibility** uses the API server URL and bearer only when configured.
|
||||
- **Terminal, bridge, TUI, media/session management, clipboard, profile writes, Android control, and relay-token voice fallback** use the relay URL and require a paired relay session token.
|
||||
|
||||
The app stores these capabilities under one stable connection identity. One
|
||||
@@ -28,7 +28,7 @@ hermes pair --mode auto --prefer tailscale
|
||||
|
||||
The recommended Tailscale stack listens on dedicated HTTPS `:10443` and proxies the local
|
||||
Dashboard/Gateway on `:9119`, including the plugin's same-origin Relay
|
||||
transport. Port `8642` remains an optional API fallback. The Relay process
|
||||
transport. Port `8642` remains optional Direct API. The Relay process
|
||||
still listens internally on `:8767`, but direct serving of that port is legacy
|
||||
compatibility for already-paired clients and is not part of new QRs.
|
||||
|
||||
@@ -103,7 +103,7 @@ both Secure Link and Tailscale Serve in one pairing invite for failover.
|
||||
One Secure Link origin carries fixed Relay, API, and authenticated Dashboard
|
||||
namespaces, but it does not merge their trust domains. Relay pairing/session
|
||||
auth, API bearer auth, and Dashboard cookie/native bearer auth remain separate.
|
||||
Chat, Manage, voice, and API fallback may therefore use the Secure Link
|
||||
Chat, Manage, voice, and Direct API may therefore use the Secure Link
|
||||
namespaces when their own credentials are present, or use independent direct or
|
||||
Tailscale HTTPS fallback routes. Tailscale Serve remains the normal recommended
|
||||
setup; Secure Link is opt-in.
|
||||
@@ -151,7 +151,7 @@ Normal connection and route fields use the **Dashboard/Gateway** address. On
|
||||
LAN that is commonly local `:9119`; recommended Tailscale uses the external
|
||||
dedicated HTTPS `:10443` listener that proxies local `:9119`. Relay rides the selected
|
||||
Dashboard origin under the plugin transport path. Advanced endpoint settings
|
||||
expose optional API fallback (`8642`). Direct Relay (`8767`) is legacy-only; do
|
||||
expose optional Direct API (`8642`). Direct Relay (`8767`) is legacy-only; do
|
||||
not substitute it for a Dashboard or API address. The editor previews every
|
||||
resolved surface before saving.
|
||||
|
||||
@@ -220,7 +220,7 @@ optional capabilities you use:
|
||||
- Dashboard/Gateway: `https://...` to local `127.0.0.1:9119`
|
||||
- Relay: the Dashboard origin's `/api/plugins/hermes-relay/transport` base,
|
||||
which derives `/ws` and `/health` and proxies internally to `127.0.0.1:8767`
|
||||
- Optional API fallback: `https://...` to local `127.0.0.1:8642`
|
||||
- Optional Direct API: `https://...` to local `127.0.0.1:8642`
|
||||
|
||||
Plain `ws://` and `http://` are acceptable only on a LAN or VPN you trust. The app requires explicit plain-transport consent before it uses those routes. Do not expose plain relay or API ports to the open internet.
|
||||
|
||||
@@ -237,7 +237,7 @@ https://<tailnet-host>.ts.net:8642/health
|
||||
```
|
||||
|
||||
If the optional API health check fails while Dashboard/Gateway works, standard
|
||||
chat remains available and only API fallback is unavailable. If Relay health
|
||||
chat remains available and only Direct API is unavailable. If Relay health
|
||||
fails, terminal/bridge and Relay voice extensions are unavailable without
|
||||
affecting the standard upstream path.
|
||||
|
||||
|
||||
@@ -41,11 +41,16 @@ From full Android Settings, the parent:
|
||||
|
||||
1. Open **Settings → Advanced → Supervised Mode** for the active Hermes
|
||||
Connection.
|
||||
2. Choose one existing named profile. Android requires a secure device screen
|
||||
lock before the mode can be enabled.
|
||||
3. Select the allowed features and any stricter attachment or history limits.
|
||||
4. Choose a visibility preset or customize what appears in Chat.
|
||||
5. Review the summary, then enable the mode.
|
||||
2. Choose one existing named profile.
|
||||
3. Choose either an app-specific six-digit parent PIN or a parent password of
|
||||
at least eight characters. The PIN uses the app keypad; passwords use the
|
||||
normal keyboard and password-manager flow. This is separate from the phone's screen lock.
|
||||
4. Save the one-time six-word recovery phrase somewhere the supervised user
|
||||
cannot access. You may share it to a parent-only destination; delete the
|
||||
message or saved copy from this phone afterward.
|
||||
5. Select the allowed features and any stricter attachment or history limits.
|
||||
6. Choose a visibility preset or customize what appears in Chat.
|
||||
7. Review the summary, then verify the parent credential to enable the mode.
|
||||
|
||||
The app returns to the pinned profile's Chat screen. If the Connection or
|
||||
profile is unavailable, the restricted client shows a recovery state
|
||||
@@ -58,8 +63,9 @@ Supervised Mode banner consuming conversation space. The agent name and avatar
|
||||
remain the primary identity, with a small connection state when permitted.
|
||||
|
||||
The existing Settings button opens **Restricted Settings**, which contains only
|
||||
approved preferences. A clearly labelled **Parent access** row starts device
|
||||
authentication before any parent controls or full application settings appear.
|
||||
approved preferences. A clearly labelled **Parent access** row asks for the
|
||||
app-specific parent PIN or password before any parent controls or full
|
||||
application settings appear.
|
||||
|
||||
Restricted Settings may include:
|
||||
|
||||
@@ -166,14 +172,38 @@ and avatar provide the normal identity in the Simple preset.
|
||||
|
||||
## Parent access and relocking
|
||||
|
||||
Enabling, changing, or ending Supervised Mode requires Android device
|
||||
authentication. Parent access should relock when its authenticated task closes,
|
||||
after the configured inactivity period, when the app backgrounds, or after
|
||||
process recreation.
|
||||
Enabling, changing, or ending Supervised Mode requires the app-specific parent
|
||||
PIN or password. Parent access relocks when its authenticated task closes, after
|
||||
the configured inactivity period, when the app backgrounds, or after process
|
||||
recreation. Failure delays persist across app restart.
|
||||
|
||||
Android's device-credential prompt authenticates any user enrolled for that
|
||||
device; it does not establish a separate parent identity. Use a device lock the
|
||||
supervised user does not know, or keep the device under direct supervision.
|
||||
The credential is global to this Android app installation, not scoped to one
|
||||
Connection. Changing it or resetting it with the current recovery phrase rotates
|
||||
the phrase, which is shown only once. If the credential record is missing
|
||||
or damaged, Supervised Mode fails closed. A legacy installation that was already
|
||||
enabled before app-specific parent credentials existed must reset local app
|
||||
data, reconnect, and configure the mode again; it does not silently trust the
|
||||
current Android user. That reset does not delete server-owned Hermes history.
|
||||
|
||||
While parent access is unlocked, **Remove parent credential** is available in
|
||||
the parent controls even if the recovery phrase has been lost. Confirming it
|
||||
disables Supervised Mode for every Connection and removes the app-wide PIN or
|
||||
password and recovery verifier. Pinned profiles, capability toggles, appearance,
|
||||
visibility, session controls, and relock settings are preserved. Server sessions
|
||||
and history are preserved.
|
||||
|
||||
If both the parent credential and recovery phrase are lost, use Android
|
||||
**Settings → Apps → Hermes-Relay → Storage → Clear data**. This also removes
|
||||
local Connections, sign-ins, preferences, and caches, but does not delete
|
||||
server-owned Hermes sessions. Uninstall/reinstall is not the documented escape
|
||||
hatch because Android may restore backed-up local app state.
|
||||
|
||||
The app stores salted PBKDF2 verifiers, not the parent password or recovery phrase,
|
||||
and applies persisted attempt delays. Prefer a strong password: a six-digit PIN
|
||||
still has limited resistance if a privileged attacker copies the app-private
|
||||
data and guesses offline. Stock Android cannot create parent-only biometric
|
||||
enrollment for one app or tell the app which enrolled fingerprint or face was
|
||||
used, so device biometrics are not accepted as parent identity.
|
||||
|
||||
The restricted root is restored before the first interactive screen. Deep
|
||||
links, notification actions, shortcuts, saved back stacks, and share intents
|
||||
@@ -209,6 +239,10 @@ Supervised Mode cannot control:
|
||||
- the developmental suitability or factual accuracy of model output;
|
||||
- Android behavior outside the Hermes-Relay app.
|
||||
|
||||
The experimental Supervised Mode and parent-authentication screens currently use
|
||||
canonical English in every app locale pending fluent review of the complete
|
||||
security and recovery wording. Do not assume those screens are localized.
|
||||
|
||||
Use it alongside a restrictive Hermes profile, parental supervision, Android
|
||||
parental or enterprise controls where appropriate, and regular review of the
|
||||
profile and its conversations.
|
||||
|
||||
@@ -51,7 +51,7 @@ If a Tailscale route fails its probe:
|
||||
tailnet HTTPS `:10443` and proxies local Dashboard `:9119` plus the
|
||||
same-origin Relay path. Open `https://<tailnet-host>:10443/api/health` from
|
||||
the phone. Old `:443`/`:9119` listeners are migration or explicit routes;
|
||||
API fallback `:8642` is optional and direct Relay `:8767` is legacy-only.
|
||||
Direct API `:8642` is optional and direct Relay `:8767` is legacy-only.
|
||||
|
||||
## Android Studio can't see a phone over Tailscale ADB
|
||||
|
||||
@@ -74,10 +74,10 @@ If `adb connect` is refused, the pairing succeeded but the wrong port was used,
|
||||
or Wireless debugging rotated ports. Reopen **Developer options -> Wireless
|
||||
debugging** on the phone and copy the current main port.
|
||||
|
||||
## Optional API fallback is unavailable
|
||||
## Optional Direct API is unavailable
|
||||
|
||||
This does not block a healthy Dashboard/Gateway connection. If you intentionally
|
||||
configured API fallback or an API-only headless connection, its
|
||||
configured Direct API or an API-only headless connection, its
|
||||
`API_SERVER_KEY` is a secret created by the server operator; Dashboard sign-in
|
||||
does not create or reveal one:
|
||||
|
||||
@@ -90,7 +90,7 @@ does not create or reveal one:
|
||||
- Confirm the dashboard session is signed in and `/api/ws` is available
|
||||
- Look for error banners in the chat — tap **Retry** to resend
|
||||
- Check the Hermes server logs for errors
|
||||
- If optional API fallback is configured, check its status separately
|
||||
- If optional Direct API is configured, check its status separately
|
||||
|
||||
## Long turns with local models
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ Android の標準接続先は `:9119` の Hermes Dashboard/Gateway です。Chat
|
||||
セッション、ログイン、Manage、標準 Voice を提供します。`hermes dashboard`
|
||||
で起動し、スマートフォンから到達できるようにします。
|
||||
|
||||
`:8642` の API サーバーはオプションです。Chat の自動フォールバックまたは
|
||||
`:8642` の API サーバーはオプションです。明示的な Direct API 接続または
|
||||
高度な headless 互換用途でのみ設定し、その場合だけ API キーが必要です。
|
||||
`API_SERVER_KEY` はサーバー管理者が作成するもので、Dashboard からは発行されません。
|
||||
|
||||
@@ -65,7 +65,7 @@ Android は異なるサインイン origin を保存前に検証します。
|
||||
3. 求められた場合はダッシュボードへログインします。
|
||||
4. **Connect** をタップし、**Chat · Ready** を確認します。
|
||||
5. **セットアップを完了** で、バックグラウンドのチャット通知が必要なら Android の通知を有効にします。カメラ、マイク、その他の機能は引き続き任意で、個別に設定できます。すぐ進む場合は **今はしない** を選びます。
|
||||
6. 必要なら後から **Advanced** で API fallback、Relay、リモートルートを追加します。
|
||||
6. 必要なら後から **Advanced** で Direct API、Relay、リモートルートを追加します。
|
||||
|
||||
`hermes-relay-tailscale enable` は tailnet の専用 `:10443` に
|
||||
`https://host.ts.net:10443` を公開し、同一 origin の Relay パスとともにローカル
|
||||
@@ -73,7 +73,7 @@ Dashboard `:9119` へ転送します。意図的に直接公開した
|
||||
`http://100.x.y.z:9119` も使用できますが、アプリケーション TLS はありません。
|
||||
|
||||
同じログインで Chat、セッション、Manage、Voice が有効になります。Relay が
|
||||
未ペアリングでも、API fallback が利用不可でも正常です。
|
||||
未ペアリングでも、Direct API が利用不可でも正常です。
|
||||
|
||||
## 推奨: Relay でセットアップを完成する {#relay-server-optional}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user