Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8a6bf0ce6 | ||
|
|
9e96111813 | ||
|
|
42efc01d58 | ||
|
|
dc93d5eab2 | ||
|
|
cafbadc583 | ||
|
|
607c26660c | ||
|
|
3882b857e3 | ||
|
|
81c186c6ba | ||
|
|
4ad0709fbe | ||
|
|
0324c9f5dd | ||
|
|
f8c31f8b59 | ||
|
|
abb4bc0ced | ||
|
|
07b683fbb5 | ||
|
|
759ac490c9 | ||
|
|
150e375284 | ||
|
|
1f49f08dbe | ||
|
|
e96aa435f2 | ||
|
|
592affca40 | ||
|
|
7e5123b22f | ||
|
|
ad3786fb0b | ||
|
|
8bd67e3363 | ||
|
|
17cf12fff9 | ||
|
|
b55e798c3b | ||
|
|
a128e910f1 | ||
|
|
a7cbf377a0 | ||
|
|
9435d43b04 | ||
|
|
52170f76ea | ||
|
|
9871b0cb7c | ||
|
|
14500096c6 | ||
|
|
1ea84630d2 | ||
|
|
d98e0b113b | ||
|
|
ea2110fa14 | ||
|
|
43357a387d | ||
|
|
336475e451 | ||
|
|
13492610a8 | ||
|
|
4e75564d33 | ||
|
|
50adab99fa | ||
|
|
284f19d62d | ||
|
|
1302da4846 | ||
|
|
dc8e076836 | ||
|
|
ce5f9c7c98 | ||
|
|
ad4e9d7b81 | ||
|
|
774ab90ad5 | ||
|
|
b296b56bce | ||
|
|
a74ad0738f | ||
|
|
6bb186ee2b | ||
|
|
db4a6f37c7 | ||
|
|
0f19deae7f | ||
|
|
fa2d17338d | ||
|
|
bc2f2b0010 | ||
|
|
dcc8d54916 | ||
|
|
a1cc34e649 | ||
|
|
47e27f6ac9 | ||
|
|
e7f882f8b5 | ||
|
|
5e53d5cfd1 | ||
|
|
b21b9c225c | ||
|
|
971a9a7e39 | ||
|
|
635aaa44e7 | ||
|
|
e088469dbf | ||
|
|
2d202bdeac | ||
|
|
798441c1e1 | ||
|
|
b424678f44 | ||
|
|
d5210bcd5e | ||
|
|
6458a854a8 | ||
|
|
65fe37a2ba | ||
|
|
9ac10cf645 | ||
|
|
bd904e26e4 | ||
|
|
ba5a2c82a5 | ||
|
|
6119f3ba79 | ||
|
|
2bcdca09e9 | ||
|
|
e2e9cc72b7 | ||
|
|
ca555fd617 | ||
|
|
3b5e61e149 |
@@ -183,11 +183,21 @@ jobs:
|
||||
./gradlew :app:testSideloadDebugUnitTest \
|
||||
--tests com.hermesandroid.relay.network.ArchitectureBoundaryTest \
|
||||
--tests com.hermesandroid.relay.network.relay.RelayUrlDeriverTest \
|
||||
--tests com.hermesandroid.relay.network.shared.PluginProxyTransportTest \
|
||||
--tests '*GatewayChatClientTest*retarget*' \
|
||||
--tests '*RelayVoiceClientRoutingTest.proxyProviderOwnsBothVoiceSessionAndWebSocketRequests' \
|
||||
--tests com.hermesandroid.relay.network.relay.RelayHttpClientDiagnosticsTest \
|
||||
--tests com.hermesandroid.relay.ui.components.GatewayRoutesAccessPresentationTest \
|
||||
--tests com.hermesandroid.relay.ui.components.EndpointsCardCompactLayoutTest \
|
||||
--tests com.hermesandroid.relay.ui.screens.ConnectionDetailPresentationTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ConnectionSwitchTest \
|
||||
--tests com.hermesandroid.relay.util.ServerAddressTest \
|
||||
--tests com.hermesandroid.relay.util.IssueReportAndDiagnosticsTest \
|
||||
--tests com.hermesandroid.relay.data.AppLanguageTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ChatStreamRecoveryTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ChatViewModelGatewayInboundTurnTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.VoiceInboundCompletionTest \
|
||||
--tests com.hermesandroid.relay.voice.VoiceViewModelBargeInTest \
|
||||
--tests com.hermesandroid.relay.viewmodel.ChatViewModelRealtimeTurnTest \
|
||||
--tests com.hermesandroid.relay.network.relay.RealtimeVoiceEventParsingTest \
|
||||
--tests com.hermesandroid.relay.voice.VoiceCommandInterpreterTest \
|
||||
|
||||
@@ -103,6 +103,10 @@ jobs:
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_secure_proxy.py \
|
||||
plugin/tests/test_secure_proxy_contract.py \
|
||||
plugin/tests/test_secure_link_setup.py \
|
||||
plugin/tests/test_secure_proxy_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
plugin/tests/test_native_layout_imports.py \
|
||||
|
||||
@@ -6,6 +6,28 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Provider usage shows Grok subscription periods, product usage, and on-demand credit state for hosts signed in with `xai-oauth`. Android shows SuperGrok by default when no provider visibility choice is saved.
|
||||
- Guided Secure Link setup in Dashboard and the Desktop Relay pane, with shared read-only host CLI checks, restart instructions, and signed pairing handoff.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Desktop tray notices, screenshot evidence, and grant prompts stay reusable after dismissal; screenshot evidence keeps the most recently selected image. (#606)
|
||||
- Proactive phone Thread messages render relay-token and host-path media as attachments while preserving multiline text; notification previews omit media markers. (#485)
|
||||
- Desktop computer screenshots attach validated image bytes to the host tool result instead of returning base64 as plain text.
|
||||
- Relay-owned media uploads are removed on token expiry, eviction, and shutdown; media activity logs omit tokens, file paths, and screenshot bytes.
|
||||
- Plugin screenshot and navigation tools resolve Android's authenticated media token, attach the actual bounded image to host vision, and keep legacy inline screenshots readable. (#593)
|
||||
- Android Chat can open the model picker before the first turn, loads Gateway models when opened, and distinguishes loading, unavailable, and empty catalogs.
|
||||
- Secure Link configuration failures leave ordinary Relay available; route details and pairing previews resolve the advertised service namespaces.
|
||||
- Dashboard pairing QR codes support larger certificate-bearing Secure Link invites.
|
||||
- Secure Link preserves Gateway ticket authentication and Dashboard login paths, bounds rewritten responses, and serves compatible health information without additional loopback probes.
|
||||
- Android Secure Link enforces the paired certificate pin for HTTP, Gateway, and voice traffic, retains the correct TLS policy during Gateway route changes, and displays the active HTTPS Dashboard route.
|
||||
- Android cold start restores the saved Appearance palette and platform light/dark mode before the first app frame.
|
||||
- Android Gateway onboarding verifies Dashboard access without overstating Chat or voice readiness, explains common authentication setup failures, and requires exact-address consent before using HTTP. Custom Dashboard ports are accepted and shown throughout setup and route editing. (#604)
|
||||
- Android safely settles Gateway foreground-service starts before stopping local retention, preventing the startup/shutdown race reported in #603. Turning off always-on connectivity preserves active turns.
|
||||
- Android Standard Voice speaks live background completions in its active conversation after the original reply finishes. Stop and conversation changes discard pending speech. (#545)
|
||||
|
||||
## [Android 1.17.0] - 2026-09-13
|
||||
|
||||
### Added
|
||||
|
||||
@@ -458,8 +458,8 @@ dependencies {
|
||||
// [POC] Roborazzi host-side screenshot rendering (src/test, Robolectric).
|
||||
// Renders real composables on the JVM at an exact canvas — no device, no
|
||||
// status bar, no clipping. See StoreScreenshotTest.
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.73.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.73.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.74.0")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.74.0")
|
||||
testImplementation(libs.compose.ui.test.junit4)
|
||||
testImplementation(libs.compose.ui.test.manifest)
|
||||
testImplementation("androidx.test.ext:junit:1.3.0")
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import com.hermesandroid.relay.data.setGatewayKeepAlive
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Real ActivityManager/notification lifecycle; no Gateway or personal data. */
|
||||
class GatewayKeepAliveServiceInstrumentedTest {
|
||||
@get:Rule val activity = createAndroidComposeRule<ComponentActivity>()
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
private val context get() = instrumentation.targetContext
|
||||
|
||||
@Before fun setup() {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
instrumentation.uiAutomation.executeShellCommand(
|
||||
"pm grant ${context.packageName} android.permission.POST_NOTIFICATIONS",
|
||||
).close()
|
||||
}
|
||||
runBlocking { context.setGatewayKeepAlive(false) }
|
||||
}
|
||||
|
||||
@After fun cleanup() {
|
||||
instrumentation.runOnMainSync {
|
||||
GatewayKeepAliveService.stop(context)
|
||||
ActiveTurnKeepAliveRegistry.releaseAll()
|
||||
}
|
||||
await("service shutdown") { serviceState() == null }
|
||||
runBlocking { context.setGatewayKeepAlive(false) }
|
||||
}
|
||||
|
||||
@Test fun immediateStopsAndOverlappingStartsSurviveThePlatformWatchdog() {
|
||||
// All changes happen before Android can dispatch onCreate/onStartCommand.
|
||||
instrumentation.runOnMainSync {
|
||||
repeat(25) {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
GatewayKeepAliveService.stop(context)
|
||||
}
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2, 1))
|
||||
}
|
||||
await("foreground promotion") { serviceState()?.foreground == true }
|
||||
instrumentation.runOnMainSync { GatewayKeepAliveService.stop(context) }
|
||||
await("settled shutdown") { serviceState() == null }
|
||||
// Observation window, not a startup workaround: an asynchronous system
|
||||
// foreground-start crash fails the instrumentation process during it.
|
||||
CountDownLatch(1).await(12, TimeUnit.SECONDS)
|
||||
assertTrue(serviceState() == null)
|
||||
}
|
||||
|
||||
@Test fun notificationDisablesAlwaysOnWhileANewerTurnStaysProtected() {
|
||||
runBlocking { context.setGatewayKeepAlive(true) }
|
||||
instrumentation.runOnMainSync {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
}
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
await("persistent notification") {
|
||||
manager.activeNotifications.any { it.id == GatewayKeepAliveService.NOTIFICATION_ID }
|
||||
}
|
||||
val action = manager.activeNotifications.single {
|
||||
it.id == GatewayKeepAliveService.NOTIFICATION_ID
|
||||
}.notification.actions.single().actionIntent
|
||||
instrumentation.runOnMainSync {
|
||||
ActiveTurnKeepAliveRegistry.acquire("fixture::profile-a::session")
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
}
|
||||
action.send()
|
||||
await("persisted notification action") {
|
||||
runBlocking { context.relayDataStore.data.first()[KEY_GATEWAY_KEEP_ALIVE] == false }
|
||||
}
|
||||
instrumentation.runOnMainSync {
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
}
|
||||
assertTrue(serviceState()?.foreground == true)
|
||||
assertTrue(ActiveTurnKeepAliveRegistry.snapshot.value.required)
|
||||
await("active-turn notification without always-on action") {
|
||||
manager.activeNotifications.singleOrNull {
|
||||
it.id == GatewayKeepAliveService.NOTIFICATION_ID
|
||||
}?.notification?.let { it.actions.isNullOrEmpty() } == true
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun serviceState(): ActivityManager.RunningServiceInfo? =
|
||||
context.getSystemService(ActivityManager::class.java).getRunningServices(100)
|
||||
.singleOrNull { it.service.className == GatewayKeepAliveService::class.java.name }
|
||||
|
||||
private fun await(description: String, condition: () -> Boolean) {
|
||||
val deadline = SystemClock.uptimeMillis() + 10_000
|
||||
while (!condition() && SystemClock.uptimeMillis() < deadline) {
|
||||
instrumentation.waitForIdleSync()
|
||||
SystemClock.sleep(20)
|
||||
}
|
||||
assertTrue(description, condition())
|
||||
}
|
||||
}
|
||||
+63
-196
@@ -3,230 +3,97 @@ package com.hermesandroid.relay.ui.onboarding
|
||||
import android.app.Application
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import androidx.compose.ui.test.performTextReplacement
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Instrumented tests for the Standard-first onboarding pager.
|
||||
*/
|
||||
/** Standard setup stays separate from Direct API and optional Relay grants. */
|
||||
class OnboardingFlowTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@get:Rule
|
||||
val composeTestRule = createComposeRule()
|
||||
|
||||
private fun setOnboardingContent() {
|
||||
val app = ApplicationProvider.getApplicationContext<Application>()
|
||||
val connectionViewModel = ConnectionViewModel(app)
|
||||
composeTestRule.setContent {
|
||||
HermesRelayTheme {
|
||||
OnboardingScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onComplete = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
private fun start() {
|
||||
val model = ConnectionViewModel(ApplicationProvider.getApplicationContext<Application>())
|
||||
compose.setContent { HermesRelayTheme { OnboardingScreen(model, onComplete = {}) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstPage_showsHermesForAndroidTitle() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes-Relay for Android")
|
||||
.assertIsDisplayed()
|
||||
private fun connectPage() {
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
repeat(3) { compose.onNodeWithText("Next").performClick(); compose.waitForIdle() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstPage_showsStandardFirstDescription() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Chat with Hermes and manage your dashboard from your phone.")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Standard")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Advanced")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Setup Guide")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes Docs")
|
||||
.assertIsDisplayed()
|
||||
@Test fun welcomeOffersStartAndDemo() {
|
||||
start()
|
||||
compose.onNodeWithText("Hermes,\nin your pocket").assertIsDisplayed()
|
||||
compose.onNodeWithText("Get started").assertIsDisplayed().assertIsEnabled()
|
||||
compose.onNodeWithText("Try the demo").assertIsDisplayed().assertIsEnabled()
|
||||
compose.onNodeWithText("Back").assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nextButton_navigatesForward_toChatPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Chat")
|
||||
.assertIsDisplayed()
|
||||
@Test fun introNavigationAndSkipRemainAvailable() {
|
||||
start()
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
compose.onNodeWithText("Chat").assertIsDisplayed()
|
||||
compose.onNodeWithText("Back").performClick()
|
||||
compose.onNodeWithText("Get started").assertIsDisplayed()
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
compose.onNodeWithText("Skip").performClick()
|
||||
compose.onNodeWithText("Skip setup?").assertIsDisplayed()
|
||||
compose.onNodeWithText("Go back").performClick()
|
||||
compose.onNodeWithText("Chat").assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canNavigateForward_throughStandardAndPowerPages() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule.onNodeWithText("Hermes-Relay for Android").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Chat").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Manage").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Power tools").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText("Connect").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule.onNodeWithText("Add gateway").assertIsDisplayed()
|
||||
@Test fun standardMethodsDoNotAskForApiCredentials() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Hermes nearby").assertIsDisplayed()
|
||||
compose.onNodeWithText("Remote gateway").assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Hermes address").assertIsDisplayed()
|
||||
compose.onNodeWithText("API key").assertDoesNotExist()
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backButton_hiddenOnFirstPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Back")
|
||||
.assertDoesNotExist()
|
||||
@Test fun publicHttpConsentResetsWhenAddressChanges() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Remote gateway").performClick()
|
||||
compose.onNodeWithText("Hermes address").performTextReplacement("http://11.0.0.1:9119")
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsNotEnabled()
|
||||
compose.onNodeWithText("I accept the risk and allow HTTP for this address").performScrollTo().performClick()
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsEnabled()
|
||||
compose.onNodeWithText("Hermes address").performScrollTo().performTextReplacement("http://11.0.0.1:9120")
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsNotEnabled()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backButton_navigatesBackward() {
|
||||
setOnboardingContent()
|
||||
|
||||
composeTestRule.onNodeWithText("Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
composeTestRule.onNodeWithText("Chat").assertIsDisplayed()
|
||||
|
||||
composeTestRule.onNodeWithText("Back").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
composeTestRule.onNodeWithText("Hermes-Relay for Android").assertIsDisplayed()
|
||||
@Test fun advancedKeepsApiAndRelaySeparate() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Advanced").performScrollTo().performClick()
|
||||
compose.onNodeWithText("API-only connection").assertIsDisplayed()
|
||||
compose.onNodeWithText("Pair Relay by code").performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addGatewayPage_leadsWithStandardGatewayMethods() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes nearby")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Remote gateway")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Scan Hermes setup QR")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Recommended")
|
||||
.assertDoesNotExist()
|
||||
@Test fun setupSkipIsScrollReachable() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Skip for now — set up later in Settings").performScrollTo().assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Skip setup?").assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualSetup_showsHermesAddressWithoutApiCredentials() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Remote gateway").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Hermes address")
|
||||
.assertIsDisplayed()
|
||||
@Test fun hostedGatewayKeepsItsSeparateAddressEntry() {
|
||||
start(); connectPage()
|
||||
compose.onNodeWithText("Nous-hosted Hermes").performClick()
|
||||
compose.onNodeWithText("Connect to Nous-hosted Hermes").assertIsDisplayed()
|
||||
compose.onNodeWithText("Find Hermes").performScrollTo().assertIsNotEnabled()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualSetup_findButton_isShown() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Remote gateway").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Find Hermes")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cloudSetup_requestsTheHostedDashboardAddress() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Nous-hosted Hermes").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Connect to Nous-hosted Hermes")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Use the complete HTTPS address shown for your hosted agent.")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addGatewayPage_keepsPairingOptional() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(4)
|
||||
|
||||
composeTestRule.onNodeWithText("Advanced").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Pair Relay by code")
|
||||
.assertIsDisplayed()
|
||||
composeTestRule
|
||||
.onNodeWithText("Power-user path for Terminal, Bridge, Relay sessions, and grants")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun powerPage_linksToPermissionReview() {
|
||||
setOnboardingContent()
|
||||
navigateToPage(3)
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Review permissions")
|
||||
.assertIsDisplayed()
|
||||
.assertIsEnabled()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipButton_visibleOnIntroPages_andWizardSkipOnAddGatewayPage() {
|
||||
setOnboardingContent()
|
||||
|
||||
repeat(4) {
|
||||
composeTestRule.onNodeWithText("Skip").assertIsDisplayed()
|
||||
composeTestRule.onNodeWithText(if (it == 3) "Connect" else "Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
}
|
||||
|
||||
composeTestRule
|
||||
.onNodeWithText("Skip for now — set up later in Settings")
|
||||
.assertIsDisplayed()
|
||||
}
|
||||
|
||||
private fun navigateToPage(pageIndex: Int) {
|
||||
repeat(pageIndex) {
|
||||
composeTestRule.onNodeWithText(if (it == 3) "Connect" else "Next").performClick()
|
||||
composeTestRule.waitForIdle()
|
||||
}
|
||||
@Test fun optionalPowerPermissionsRemainReachable() {
|
||||
start()
|
||||
compose.onNodeWithText("Get started").performClick()
|
||||
repeat(2) { compose.onNodeWithText("Next").performClick(); compose.waitForIdle() }
|
||||
compose.onNodeWithText("Review permissions").performScrollTo().assertIsDisplayed().assertIsEnabled()
|
||||
}
|
||||
}
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package com.hermesandroid.relay.ui.theme
|
||||
|
||||
import android.app.UiModeManager
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.hermesandroid.relay.HermesRelayApp
|
||||
import com.hermesandroid.relay.MainActivity
|
||||
import com.hermesandroid.relay.data.AppearancePreferences
|
||||
import com.hermesandroid.relay.data.CustomThemePreset
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import com.hermesandroid.relay.runtime.HermesRuntimeInitializationState
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/** Real Activity/DataStore/Compose ownership, with the device set to dark mode. */
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class AppearanceColdStartInstrumentedTest {
|
||||
@Test
|
||||
fun savedAppearanceOwnsColdStartAndLaterModeChanges() {
|
||||
val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
val app = ApplicationProvider.getApplicationContext<HermesRelayApp>()
|
||||
val previousPreferences = runBlocking { app.relayDataStore.data.first() }
|
||||
val originalNightMode =
|
||||
(app.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager).nightMode
|
||||
assumeTrue(
|
||||
originalNightMode == UiModeManager.MODE_NIGHT_AUTO ||
|
||||
originalNightMode == UiModeManager.MODE_NIGHT_NO ||
|
||||
originalNightMode == UiModeManager.MODE_NIGHT_YES,
|
||||
)
|
||||
val custom = CustomThemePreset(
|
||||
id = "day",
|
||||
name = "Day",
|
||||
mode = CustomThemePreset.MODE_LIGHT,
|
||||
backgroundHex = "#F5F5F5",
|
||||
surfaceHex = "#FFFFFF",
|
||||
accentHex = "#0E18D6",
|
||||
textHex = "#111111",
|
||||
)
|
||||
instrumentation.uiAutomation.executeShellCommand("cmd uimode night yes").close()
|
||||
try {
|
||||
runBlocking {
|
||||
app.relayDataStore.edit { preferences ->
|
||||
preferences[AppearancePreferences.themeKey] = "light"
|
||||
preferences[AppearancePreferences.appThemeKey] = AppThemes.DEFAULT_ID
|
||||
}
|
||||
}
|
||||
instrumentation.runOnMainSync {
|
||||
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
|
||||
}
|
||||
ActivityScenario.launch(MainActivity::class.java).use {
|
||||
runBlocking {
|
||||
withTimeout(30_000) {
|
||||
app.runtime.connectionViewModel.isReady.first { it }
|
||||
app.runtime.initializationState.first {
|
||||
it == HermesRuntimeInitializationState.Ready
|
||||
}
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = false, nightMode = AppCompatDelegate.MODE_NIGHT_NO)
|
||||
|
||||
runBlocking {
|
||||
app.relayDataStore.edit {
|
||||
it[AppearancePreferences.themeKey] = "dark"
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = true, nightMode = AppCompatDelegate.MODE_NIGHT_YES)
|
||||
|
||||
runBlocking {
|
||||
app.relayDataStore.edit {
|
||||
it[AppearancePreferences.themeKey] = "auto"
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = true, nightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
|
||||
|
||||
runBlocking {
|
||||
app.relayDataStore.edit {
|
||||
it[AppearancePreferences.customThemesKey] =
|
||||
AppearancePreferences.encodeCustomThemes(listOf(custom))
|
||||
it[AppearancePreferences.appThemeKey] = custom.appThemeId
|
||||
}
|
||||
}
|
||||
awaitTheme(isDark = false, nightMode = AppCompatDelegate.MODE_NIGHT_NO)
|
||||
}
|
||||
} finally {
|
||||
runBlocking {
|
||||
app.relayDataStore.edit { preferences ->
|
||||
previousPreferences[AppearancePreferences.themeKey]?.let {
|
||||
preferences[AppearancePreferences.themeKey] = it
|
||||
} ?: preferences.remove(AppearancePreferences.themeKey)
|
||||
previousPreferences[AppearancePreferences.appThemeKey]?.let {
|
||||
preferences[AppearancePreferences.appThemeKey] = it
|
||||
} ?: preferences.remove(AppearancePreferences.appThemeKey)
|
||||
previousPreferences[AppearancePreferences.customThemesKey]?.let {
|
||||
preferences[AppearancePreferences.customThemesKey] = it
|
||||
} ?: preferences.remove(AppearancePreferences.customThemesKey)
|
||||
}
|
||||
}
|
||||
val restoreMode = when (originalNightMode) {
|
||||
UiModeManager.MODE_NIGHT_YES -> "yes"
|
||||
UiModeManager.MODE_NIGHT_NO -> "no"
|
||||
else -> "auto"
|
||||
}
|
||||
instrumentation.uiAutomation.executeShellCommand("cmd uimode night $restoreMode").close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun awaitTheme(isDark: Boolean, nightMode: Int) {
|
||||
val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
val deadline = SystemClock.uptimeMillis() + 15_000
|
||||
while (SystemClock.uptimeMillis() < deadline) {
|
||||
instrumentation.waitForIdleSync()
|
||||
if (RelayRefresh.activePalette.isDark == isDark &&
|
||||
AppCompatDelegate.getDefaultNightMode() == nightMode
|
||||
) {
|
||||
assertEquals(nightMode, AppCompatDelegate.getDefaultNightMode())
|
||||
if (isDark) assertTrue(RelayRefresh.activePalette.isDark)
|
||||
else assertFalse(RelayRefresh.activePalette.isDark)
|
||||
return
|
||||
}
|
||||
SystemClock.sleep(25)
|
||||
}
|
||||
fail(
|
||||
"Appearance did not settle: paletteDark=${RelayRefresh.activePalette.isDark}, " +
|
||||
"nightMode=${AppCompatDelegate.getDefaultNightMode()}",
|
||||
)
|
||||
}
|
||||
}
|
||||
+82
@@ -62,9 +62,17 @@ class GatewayExternalFixtureInstrumentedTest {
|
||||
private var gatewayScope: CoroutineScope? = null
|
||||
private var gatewayClient: GatewayChatClient? = null
|
||||
private var viewModel: ChatViewModel? = null
|
||||
private var voiceViewModel: VoiceViewModel? = null
|
||||
private var voicePlayer: com.hermesandroid.relay.audio.VoicePlayer? = null
|
||||
private var voiceSfx: com.hermesandroid.relay.audio.VoiceSfxPlayer? = null
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
compose.runOnUiThread {
|
||||
voiceViewModel?.exitVoiceMode()
|
||||
voicePlayer?.release()
|
||||
voiceSfx?.release()
|
||||
}
|
||||
viewModel?.updateGatewayClient(null)
|
||||
gatewayClient?.shutdown()
|
||||
gatewayScope?.cancel()
|
||||
@@ -250,6 +258,80 @@ class GatewayExternalFixtureInstrumentedTest {
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unsolicitedVoiceCompletions_surviveActivityPauseWithoutHistorySpeech() {
|
||||
val base = InstrumentationRegistry.getArguments().getString(ARG_FIXTURE_BASE_URL)
|
||||
?.trim()?.trimEnd('/')
|
||||
assumeTrue("Pass the unsolicited_voice_completions fixture URL", !base.isNullOrBlank())
|
||||
requireNotNull(base)
|
||||
val http = OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).build()
|
||||
assertEquals("unsolicited_voice_completions", readFixtureJson(http, "$base/__fixture__/state")["scenario"]?.jsonString())
|
||||
val dashboard = DashboardApiClient(base, http)
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { gatewayScope = it }
|
||||
val gateway = GatewayChatClient(
|
||||
initialDashboardClient = dashboard, okHttpClient = http,
|
||||
callbackDispatcher = { Handler(Looper.getMainLooper()).post(it) }, scope = scope,
|
||||
).also { gatewayClient = it }
|
||||
val handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
val spoken = java.util.concurrent.CopyOnWriteArrayList<String>()
|
||||
lateinit var vm: ChatViewModel
|
||||
compose.runOnUiThread {
|
||||
val app = compose.activity.application
|
||||
vm = ChatViewModel().also {
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoaderWithMode { profile, id, mode ->
|
||||
dashboard.getSessionMessages(id, profile, mode)
|
||||
}
|
||||
it.updateGatewayClient(gateway)
|
||||
viewModel = it
|
||||
}
|
||||
val audio = object : com.hermesandroid.relay.network.shared.VoiceAudioClient {
|
||||
override val route = com.hermesandroid.relay.data.VoiceAudioRoute.Standard
|
||||
override suspend fun transcribe(audioFile: java.io.File) = Result.success("")
|
||||
override suspend fun synthesize(text: String): Result<java.io.File> {
|
||||
spoken.add(text)
|
||||
// A short silent WAV exercises the production play/drain path without a provider.
|
||||
val pcm = ByteArray(3200)
|
||||
val header = java.nio.ByteBuffer.allocate(44).order(java.nio.ByteOrder.LITTLE_ENDIAN)
|
||||
.put("RIFF".toByteArray()).putInt(36 + pcm.size).put("WAVEfmt ".toByteArray())
|
||||
.putInt(16).putShort(1).putShort(1).putInt(16000).putInt(32000)
|
||||
.putShort(2).putShort(16).put("data".toByteArray()).putInt(pcm.size).array()
|
||||
val file = java.io.File.createTempFile("fixture-voice", ".wav", app.cacheDir)
|
||||
file.writeBytes(header + pcm)
|
||||
return Result.success(file)
|
||||
}
|
||||
}
|
||||
val player = com.hermesandroid.relay.audio.VoicePlayer(app).also { voicePlayer = it }
|
||||
val sfx = com.hermesandroid.relay.audio.VoiceSfxPlayer(app).also { voiceSfx = it }
|
||||
voiceViewModel = VoiceViewModel(app).also {
|
||||
it.initialize(
|
||||
voiceClient = com.hermesandroid.relay.network.relay.RelayVoiceClient(app, http, { null }, { null }),
|
||||
voiceAudioClient = audio, chatViewModel = vm,
|
||||
recorder = com.hermesandroid.relay.audio.VoiceRecorder(app, scope),
|
||||
player = player, sfxPlayer = sfx,
|
||||
)
|
||||
it.enterVoiceMode()
|
||||
}
|
||||
}
|
||||
compose.setContent {
|
||||
val messages by vm.messages.collectAsStateWithLifecycle()
|
||||
Text(messages.joinToString("\n") { it.content }, Modifier.testTag("voice-fixture-history"))
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
compose.runOnUiThread { vm.sendMessage("Start background work.") }
|
||||
compose.waitUntil(10_000) { handler.messages.value.any { it.content == "Work started." } }
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.STARTED)
|
||||
compose.waitUntil(15_000) { spoken.size == 3 }
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
compose.runOnUiThread { voiceViewModel?.onAppResumed() }
|
||||
compose.waitForIdle()
|
||||
assertEquals(listOf("Process finished.", "Watch matched.", "Delegated work finished."), spoken.toList())
|
||||
assertEquals(1, readFixtureJson(http, "$base/__fixture__/evidence")["entries"].let { it as JsonArray }.rpcCount("prompt.submit"))
|
||||
assertTrue(handler.messages.value.any { it.content == "Delegated work finished." })
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
}
|
||||
|
||||
private fun JsonArray.rpcCount(method: String): Int = count { element ->
|
||||
val entry = element as? JsonObject ?: return@count false
|
||||
entry["kind"]?.jsonString() == "rpc" && entry["method"]?.jsonString() == method
|
||||
|
||||
@@ -13,10 +13,15 @@ import coil3.network.okhttp.OkHttpNetworkFetcherFactory
|
||||
import coil3.request.crossfade
|
||||
import com.hermesandroid.relay.bridge.UnattendedAccessManager
|
||||
import com.hermesandroid.relay.data.AppAnalytics
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import com.hermesandroid.relay.power.WakeLockManager
|
||||
import com.hermesandroid.relay.runtime.HermesProcessRuntime
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceNightMode
|
||||
import com.hermesandroid.relay.util.AppForegroundTracker
|
||||
import com.hermesandroid.relay.util.CrashReporter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
|
||||
@@ -57,6 +62,10 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
// Install the crash handler FIRST so any failure in the rest of app
|
||||
// init (or anywhere later) is captured and surfaced on next launch.
|
||||
CrashReporter.install(this)
|
||||
// Apply saved Light/Dark/Auto before the first Activity frame so DayNight
|
||||
// does not briefly follow the system when Appearance is explicitly Light.
|
||||
// Bounded + best-effort: HermesRelayTheme SideEffect is the durable path.
|
||||
applyPersistedAppearanceNightMode()
|
||||
AppAnalytics.initialize(this)
|
||||
// A8 — wire the bridge-gesture wake-lock wrapper so
|
||||
// ActionExecutor.tap/tapText/typeText/swipe/scroll can hold
|
||||
@@ -76,6 +85,19 @@ class HermesRelayApp : Application(), SingletonImageLoader.Factory {
|
||||
AppForegroundTracker.initialize()
|
||||
}
|
||||
|
||||
private fun applyPersistedAppearanceNightMode() {
|
||||
try {
|
||||
runBlocking {
|
||||
val preferences = withTimeoutOrNull(400L) {
|
||||
relayDataStore.data.first()
|
||||
} ?: return@runBlocking
|
||||
AppearanceNightMode.applyFromPreferences(preferences)
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// Non-fatal — theme root reapplies once DataStore is ready.
|
||||
}
|
||||
}
|
||||
|
||||
private fun isMainApplicationProcess(): Boolean {
|
||||
val processName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
getProcessName()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.floatPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.hermesandroid.relay.ui.theme.AppFont
|
||||
@@ -35,23 +36,25 @@ internal object AppearancePreferences {
|
||||
private val serializer = ListSerializer(CustomThemePreset.serializer())
|
||||
|
||||
fun state(context: Context): Flow<PersistedAppearance> = context.applicationContext.relayDataStore.data
|
||||
.map { preferences ->
|
||||
val customThemes = decodeCustomThemes(preferences[customThemesKey])
|
||||
val requestedThemeId = preferences[appThemeKey]
|
||||
val customTheme = CustomThemePreset.idFromAppTheme(requestedThemeId)
|
||||
?.let { id -> customThemes.firstOrNull { it.id == id } }
|
||||
PersistedAppearance(
|
||||
themePreference = preferences[themeKey]
|
||||
?.takeIf { it == "auto" || it == "light" || it == "dark" }
|
||||
?: "auto",
|
||||
appThemeId = customTheme?.appThemeId ?: AppThemes.byId(requestedThemeId).id,
|
||||
accentHex = normalizeAccentHex(preferences[accentKey]),
|
||||
shapeId = AppearanceShape.fromId(preferences[shapeKey]).id,
|
||||
appFontId = AppFont.byId(preferences[appFontKey]).id,
|
||||
fontScale = (preferences[fontScaleKey] ?: 1.0f).coerceIn(0.85f, 1.3f),
|
||||
customTheme = customTheme,
|
||||
)
|
||||
}
|
||||
.map(::decode)
|
||||
|
||||
fun decode(preferences: Preferences): PersistedAppearance {
|
||||
val customThemes = decodeCustomThemes(preferences[customThemesKey])
|
||||
val requestedThemeId = preferences[appThemeKey]
|
||||
val customTheme = CustomThemePreset.idFromAppTheme(requestedThemeId)
|
||||
?.let { id -> customThemes.firstOrNull { it.id == id } }
|
||||
return PersistedAppearance(
|
||||
themePreference = preferences[themeKey]
|
||||
?.takeIf { it == "auto" || it == "light" || it == "dark" }
|
||||
?: "auto",
|
||||
appThemeId = customTheme?.appThemeId ?: AppThemes.byId(requestedThemeId).id,
|
||||
accentHex = normalizeAccentHex(preferences[accentKey]),
|
||||
shapeId = AppearanceShape.fromId(preferences[shapeKey]).id,
|
||||
appFontId = AppFont.byId(preferences[appFontKey]).id,
|
||||
fontScale = (preferences[fontScaleKey] ?: 1.0f).coerceIn(0.85f, 1.3f),
|
||||
customTheme = customTheme,
|
||||
)
|
||||
}
|
||||
|
||||
fun shape(context: Context): Flow<String> = state(context).map { it.shapeId }
|
||||
|
||||
|
||||
@@ -44,7 +44,9 @@ val Connection.automaticChatTransport: SessionTransport
|
||||
get() {
|
||||
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
|
||||
!authenticatedDashboardOrigin.isNullOrBlank()
|
||||
return if (dashboardPersisted) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
// An empty first-setup placeholder is standard Gateway intent, not an
|
||||
// API-only conversation. Only an actual API endpoint selects legacy SSE.
|
||||
return if (dashboardPersisted || apiServerUrl.isBlank()) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
}
|
||||
|
||||
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
|
||||
|
||||
@@ -67,6 +67,8 @@ data class Connection(
|
||||
* "derive from [apiServerUrl] using the conventional same-host :9119".
|
||||
*/
|
||||
val dashboardUrl: String? = null,
|
||||
/** User-accepted cleartext origins. This does not assert or monitor VPN protection. */
|
||||
val dashboardHttpConsentOrigins: Set<String> = emptySet(),
|
||||
/**
|
||||
* Credential-free origin that most recently completed Dashboard
|
||||
* authentication for this connection. Public origins require HTTPS;
|
||||
@@ -116,7 +118,7 @@ data class Connection(
|
||||
*/
|
||||
val resolvedDashboardUrl: String
|
||||
get() = authenticatedDashboardOrigin
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
?.let { normalizeCredentialFreeAuthenticatedDashboardOrigin(it, dashboardHttpConsentOrigins) }
|
||||
?: configuredDashboardUrl
|
||||
|
||||
/** Stable display/host identity that does not depend on the API surface. */
|
||||
@@ -628,7 +630,10 @@ internal fun normalizeCredentialFreeHttpsOrigin(raw: String): String? {
|
||||
* HTTPS; cleartext is accepted only for literal loopback, RFC1918/link-local,
|
||||
* or Tailscale CGNAT addresses.
|
||||
*/
|
||||
internal fun normalizeCredentialFreeAuthenticatedDashboardOrigin(raw: String): String? {
|
||||
internal fun normalizeCredentialFreeAuthenticatedDashboardOrigin(
|
||||
raw: String,
|
||||
httpConsentOrigins: Set<String> = emptySet(),
|
||||
): String? {
|
||||
normalizeCredentialFreeHttpsOrigin(raw)?.let { return it }
|
||||
val parsed = runCatching { URI(raw.trim()) }.getOrNull() ?: return null
|
||||
if (!parsed.scheme.equals("http", ignoreCase = true)) return null
|
||||
@@ -651,6 +656,6 @@ internal fun normalizeCredentialFreeAuthenticatedDashboardOrigin(raw: String): S
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
if (!trustedHost) return null
|
||||
if (!trustedHost && !dashboardHttpConsentMatches(raw, httpConsentOrigins)) return null
|
||||
return parsed.normalize().toASCIIString().trimEnd('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
@@ -581,7 +581,7 @@ internal fun Connection.withDashboardDefaults(): Connection {
|
||||
it.role.equals(LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE, ignoreCase = true)
|
||||
}
|
||||
val migratedAuthenticatedOrigin = authenticatedDashboardOrigin
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
?.let { normalizeCredentialFreeAuthenticatedDashboardOrigin(it, dashboardHttpConsentOrigins) }
|
||||
?: legacyAuthenticatedRoute?.dashboard?.url
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
val routesWithoutLegacyAuthentication = routeCandidates.filterNot {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
|
||||
/** An explicit HTTP exception is scoped to a connection and exact origin, never a VPN claim. */
|
||||
fun dashboardHttpOrigin(address: String): String? {
|
||||
val url = address.trim().toHttpUrlOrNull() ?: return null
|
||||
if (url.scheme != "http" || url.username.isNotEmpty() || url.password.isNotEmpty() ||
|
||||
url.query != null || url.fragment != null
|
||||
) return null
|
||||
return url.newBuilder().encodedPath("/").build().toString().trimEnd('/')
|
||||
}
|
||||
|
||||
fun dashboardHttpConsentRequired(address: String): Boolean =
|
||||
dashboardHttpOrigin(address) != null && Connection.inferRouteRole(address) == "public"
|
||||
|
||||
fun dashboardHttpConsentMatches(address: String, approvedOrigins: Set<String>): Boolean =
|
||||
dashboardHttpOrigin(address)?.let { it in approvedOrigins } == true
|
||||
|
||||
/** Editing an origin retires its old exception; another address requires its own confirmation. */
|
||||
fun updatedDashboardHttpConsents(
|
||||
previous: Set<String>,
|
||||
oldAddress: String?,
|
||||
newAddress: String,
|
||||
confirmedOrigin: String?,
|
||||
): Set<String> {
|
||||
val oldOrigin = oldAddress?.let(::dashboardHttpOrigin)
|
||||
val newOrigin = dashboardHttpOrigin(newAddress)
|
||||
val retained = if (oldOrigin != newOrigin) previous - setOfNotNull(oldOrigin) else previous
|
||||
return if (newOrigin != null && confirmedOrigin == newOrigin) retained + newOrigin else retained
|
||||
}
|
||||
@@ -197,15 +197,34 @@ fun EndpointCandidate.isDashboardOnlyRoute(): Boolean =
|
||||
/** Dashboard-first URL identity for routing, diagnostics, and UI labels. */
|
||||
fun EndpointCandidate.primaryRouteUrl(): String? =
|
||||
dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxyDashboardBaseUrlOrNull()
|
||||
?: api?.url
|
||||
?: relay?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxy?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
|
||||
/** Dashboard/Gateway identity only; Relay and broker transports are extensions. */
|
||||
/**
|
||||
* Dashboard/Gateway identity only; Relay and broker transports are extensions.
|
||||
*
|
||||
* Hermes Secure Link stores the dashboard surface under [ProxyEndpoint.surfaces]
|
||||
* (`…/dashboard`), not [DashboardEndpoint.url]. Without that hop, Routes/Access
|
||||
* fall back to the saved plain `:9119` URL while Overview already rides the
|
||||
* live Secure Link origin.
|
||||
*/
|
||||
fun EndpointCandidate.gatewayRouteUrl(): String? =
|
||||
dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }
|
||||
?: proxyDashboardBaseUrlOrNull()
|
||||
?: api?.url?.let(Connection::deriveDefaultDashboardUrl)
|
||||
|
||||
/** Secure Link dashboard base when the proxy advertises a dashboard surface. */
|
||||
internal fun EndpointCandidate.proxyDashboardBaseUrlOrNull(): String? {
|
||||
val proxy = proxy ?: return null
|
||||
if (!proxy.isValidPinnedProxy()) return null
|
||||
val surfaces = proxy.surfaces.map { it.trim().lowercase() }.toSet()
|
||||
if ("dashboard" !in surfaces) return null
|
||||
val base = proxy.url.trim().trimEnd('/').takeIf { it.isNotBlank() } ?: return null
|
||||
return "$base/dashboard"
|
||||
}
|
||||
|
||||
/** Stable host/port identity without assuming that an API surface exists. */
|
||||
fun EndpointCandidate.routeAuthority(): String? {
|
||||
val rawUrl = primaryRouteUrl() ?: return null
|
||||
|
||||
@@ -27,7 +27,7 @@ data class ProviderUsagePreferences(
|
||||
val visibleProviders: Set<String> = DEFAULT_VISIBLE_PROVIDERS,
|
||||
) {
|
||||
companion object {
|
||||
val DEFAULT_VISIBLE_PROVIDERS = setOf("openai-codex", "nous", "opencode-go")
|
||||
val DEFAULT_VISIBLE_PROVIDERS = setOf("openai-codex", "nous", "opencode-go", "supergrok")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-1
@@ -131,7 +131,7 @@ class ProactiveMessageHandler(
|
||||
ProactiveMessageNotifier.notify(
|
||||
context = context,
|
||||
title = msg.title,
|
||||
text = msg.text,
|
||||
text = mediaFreeProactivePreview(msg.text),
|
||||
messageId = msg.messageId,
|
||||
chatId = msg.chatId,
|
||||
)
|
||||
@@ -156,6 +156,30 @@ class ProactiveMessageHandler(
|
||||
}
|
||||
}
|
||||
|
||||
/** Notification text is a preview; the Thread owns attachment rendering. */
|
||||
internal fun mediaFreeProactivePreview(text: String): String {
|
||||
var fence: String? = null
|
||||
val lines = mutableListOf<String>()
|
||||
for (line in text.lines()) {
|
||||
val trimmed = line.trim()
|
||||
val delimiter = when {
|
||||
trimmed.startsWith("```") -> "```"
|
||||
trimmed.startsWith("~~~") -> "~~~"
|
||||
else -> null
|
||||
}
|
||||
if (delimiter != null) {
|
||||
fence = if (fence == delimiter) null else if (fence == null) delimiter else fence
|
||||
}
|
||||
val markerOnly = fence == null && (
|
||||
trimmed.startsWith("MEDIA:hermes-relay://") ||
|
||||
trimmed.startsWith("MEDIA:/") ||
|
||||
Regex("^MEDIA:[A-Za-z]:\\\\").containsMatchIn(trimmed)
|
||||
)
|
||||
if (!markerOnly && trimmed.isNotEmpty()) lines += trimmed
|
||||
}
|
||||
return lines.joinToString(" ").ifBlank { "Attachment" }
|
||||
}
|
||||
|
||||
/**
|
||||
* A parsed agent-initiated message. `surfacing` is the optional route hint
|
||||
* (null = app default); Phase 2 keys inbox/session delivery off it.
|
||||
|
||||
@@ -75,16 +75,25 @@ class RelayHttpClient(
|
||||
private val context: Context? = null,
|
||||
/** Dashboard-authenticated client for same-origin plugin ingress calls. */
|
||||
private val dashboardHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/**
|
||||
* Pinned-TLS client for Hermes Secure Link (`plugin_proxy`) relay URLs.
|
||||
* Without this, HTTPS probes against the self-signed Secure Link cert fail
|
||||
* with "Trust anchor for certification path not found" while the WSS path
|
||||
* (which already uses buildPluginProxyClient) stays healthy — the UI then
|
||||
* reports dashboard/relay surfaces offline despite an Active connection.
|
||||
*/
|
||||
private val pluginProxyHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
) {
|
||||
|
||||
private fun relayHttpBaseOrNull(url: String): String? =
|
||||
RelayEndpointContract.parseOrNull(url)?.httpBaseUrl
|
||||
|
||||
private fun callClient(relayUrl: String): OkHttpClient =
|
||||
if (isDashboardRelayIngressUrl(relayUrl)) {
|
||||
dashboardHttpClientProvider?.invoke(relayUrl) ?: okHttpClient
|
||||
} else {
|
||||
okHttpClient
|
||||
when {
|
||||
isDashboardRelayIngressUrl(relayUrl) ->
|
||||
dashboardHttpClientProvider?.invoke(relayUrl) ?: okHttpClient
|
||||
else ->
|
||||
pluginProxyHttpClientProvider?.invoke(relayUrl) ?: okHttpClient
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -327,11 +336,11 @@ class RelayHttpClient(
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "fetchMedia failed: ${e.message}")
|
||||
Result.failure(e)
|
||||
Log.w(TAG, "fetchMedia failed")
|
||||
Result.failure(if (e is RelayMediaLimitException) e else IOException("Relay media request failed"))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "fetchMedia unexpected error: ${e.message}")
|
||||
Result.failure(e)
|
||||
Log.w(TAG, "fetchMedia unexpected error")
|
||||
Result.failure(IOException("Relay media request failed"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,7 +416,7 @@ class RelayHttpClient(
|
||||
val reason = when (response.code) {
|
||||
401 -> "Unauthorized — re-pair with the relay"
|
||||
403 -> "Path not allowed by relay sandbox"
|
||||
404 -> "File not found on relay: $path"
|
||||
404 -> "File not found on relay"
|
||||
400 -> "Bad request — missing path"
|
||||
in 500..599 -> "Relay error (HTTP ${response.code})"
|
||||
else -> "HTTP ${response.code}: ${response.message.ifBlank { "request failed" }}"
|
||||
@@ -437,15 +446,15 @@ class RelayHttpClient(
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "fetchMediaByPath failed for $path: ${e.message}")
|
||||
Log.w(TAG, "fetchMediaByPath failed")
|
||||
if (e is RelayMediaLimitException) {
|
||||
Result.failure(e)
|
||||
} else {
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
Result.failure(IOException("Relay media request failed"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "fetchMediaByPath unexpected error for $path: ${e.message}")
|
||||
Result.failure(e)
|
||||
Log.w(TAG, "fetchMediaByPath unexpected error")
|
||||
Result.failure(IOException("Relay media request failed"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1360,7 +1369,16 @@ class RelayHttpClient(
|
||||
IOException("Relay reports status=${status ?: "missing"} (expected 'ok')")
|
||||
)
|
||||
}
|
||||
val version = (parsed["version"] as? kotlinx.serialization.json.JsonPrimitive)?.content
|
||||
val surface = (parsed["surface"] as? kotlinx.serialization.json.JsonPrimitive)?.content
|
||||
val versionRaw = (parsed["version"] as? kotlinx.serialization.json.JsonPrimitive)?.content
|
||||
// Secure Link /relay/health historically returned status=ok without
|
||||
// version (surface=hermes_secure_proxy). Treat that as healthy so
|
||||
// route probes don't spam "Missing version field".
|
||||
val version = when {
|
||||
!versionRaw.isNullOrBlank() -> versionRaw
|
||||
surface.equals("hermes_secure_proxy", ignoreCase = true) -> "secure-link"
|
||||
else -> null
|
||||
}
|
||||
if (version.isNullOrBlank()) {
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Relay,
|
||||
|
||||
@@ -103,6 +103,8 @@ class RelayVoiceClient(
|
||||
private val voiceOutputFirstAudioTimeoutMs: Long = VOICE_OUTPUT_FIRST_AUDIO_TIMEOUT_MS,
|
||||
/** Dashboard-authenticated transport for same-origin plugin ingress. */
|
||||
private val dashboardHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/** Pinned-TLS client for Hermes Secure Link relay URLs (self-signed leaf). */
|
||||
private val pluginProxyHttpClientProvider: ((String) -> OkHttpClient?)? = null,
|
||||
/** Fresh Dashboard ticket request for every ingress voice socket dial. */
|
||||
private val dashboardIngressWebSocketRequestProvider:
|
||||
(suspend (String) -> Request?)? = null,
|
||||
@@ -114,11 +116,7 @@ class RelayVoiceClient(
|
||||
private val okHttpClient: OkHttpClient
|
||||
get() {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
return if (isDashboardRelayIngressUrl(relayUrl)) {
|
||||
dashboardHttpClientProvider?.invoke(relayUrl) ?: directOkHttpClient
|
||||
} else {
|
||||
directOkHttpClient
|
||||
}
|
||||
return resolveClient(relayUrl)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -163,13 +161,16 @@ class RelayVoiceClient(
|
||||
}
|
||||
}
|
||||
|
||||
private fun callClient(url: String): OkHttpClient =
|
||||
if (isDashboardRelayIngressUrl(url)) {
|
||||
dashboardHttpClientProvider?.invoke(url) ?: directOkHttpClient
|
||||
} else {
|
||||
directOkHttpClient
|
||||
private fun resolveClient(url: String): OkHttpClient =
|
||||
when {
|
||||
isDashboardRelayIngressUrl(url) ->
|
||||
dashboardHttpClientProvider?.invoke(url) ?: directOkHttpClient
|
||||
else ->
|
||||
pluginProxyHttpClientProvider?.invoke(url) ?: directOkHttpClient
|
||||
}
|
||||
|
||||
private fun callClient(url: String): OkHttpClient = resolveClient(url)
|
||||
|
||||
private fun sessionClient(): OkHttpClient =
|
||||
okHttpClient.newBuilder()
|
||||
.callTimeout(SESSION_CALL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||
|
||||
@@ -124,8 +124,15 @@ class EndpointResolver(
|
||||
* expected path for plain JVM tests.
|
||||
*/
|
||||
private val context: Context? = null,
|
||||
/** Route-aware client for pinned plugin proxy probes. */
|
||||
private val clientForCandidate: ((EndpointCandidate) -> OkHttpClient?)? = null,
|
||||
/**
|
||||
* Route-aware client for pinned plugin proxy probes.
|
||||
* Second arg is the concrete probe request URL when known — callers must
|
||||
* pin only when *this* request targets the Secure Link authority. Using a
|
||||
* pin client for every surface on a LAN candidate that merely *stores* a
|
||||
* Secure Link relay URL breaks plain :9119/:8642 probes (authority guard
|
||||
* throws IOException → "Unreachable - IOException").
|
||||
*/
|
||||
private val clientForCandidate: ((EndpointCandidate, probeRequestUrl: String?) -> OkHttpClient?)? = null,
|
||||
) {
|
||||
|
||||
/**
|
||||
@@ -556,7 +563,9 @@ class EndpointResolver(
|
||||
)
|
||||
}
|
||||
}
|
||||
val fastClient = (clientForCandidate?.invoke(candidate) ?: httpClient).newBuilder()
|
||||
val fastClient = (
|
||||
clientForCandidate?.invoke(candidate, target.requestUrl) ?: httpClient
|
||||
).newBuilder()
|
||||
.connectTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
.readTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
.writeTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
|
||||
+11
-13
@@ -3,7 +3,6 @@ package com.hermesandroid.relay.network.shared
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.ProxyEndpoint
|
||||
import com.hermesandroid.relay.data.isValidPinnedProxy
|
||||
import okhttp3.CertificatePinner
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import java.net.URI
|
||||
@@ -66,9 +65,10 @@ fun EndpointCandidate.pluginProxyRoutesOrNull(): PluginProxyRoutes? =
|
||||
private fun formatHost(host: String): String = if (':' in host) "[$host]" else host
|
||||
|
||||
/**
|
||||
* Build a client that trusts the system normally, plus exactly the
|
||||
* pairing-advertised SPKI for this proxy. The authority guard keeps a pin
|
||||
* scoped to host *and port*; OkHttp's CertificatePinner alone is host-only.
|
||||
* Require the paired leaf SPKI for both system-trusted and self-signed chains.
|
||||
* Validate it in the trust manager, before OkHttp's chain cleaning, so a
|
||||
* self-signed paired leaf does not depend on a platform-supplied cleaned chain.
|
||||
* The authority guard applies to HTTP calls and WebSocket upgrades alike.
|
||||
*/
|
||||
fun buildPluginProxyClient(
|
||||
baseBuilder: OkHttpClient.Builder,
|
||||
@@ -88,12 +88,12 @@ fun buildPluginProxyClient(
|
||||
if (rawSocketFactory != null) baseBuilder.socketFactory(rawSocketFactory)
|
||||
return baseBuilder
|
||||
.sslSocketFactory(sslContext.socketFactory, pinnedTrust)
|
||||
.certificatePinner(
|
||||
CertificatePinner.Builder().add(expectedHost, routes.pinSha256).build(),
|
||||
)
|
||||
.addNetworkInterceptor(Interceptor { chain ->
|
||||
.followRedirects(false)
|
||||
.followSslRedirects(false)
|
||||
.addInterceptor(Interceptor { chain ->
|
||||
val requestUrl = chain.request().url
|
||||
if (!requestUrl.host.equals(expectedHost, ignoreCase = true) ||
|
||||
if (!requestUrl.isHttps ||
|
||||
!requestUrl.host.equals(expectedHost, ignoreCase = true) ||
|
||||
requestUrl.port != expectedPort
|
||||
) {
|
||||
throw java.io.IOException("Pinned proxy redirect left its paired authority")
|
||||
@@ -122,7 +122,7 @@ private fun systemTrustManager(): X509TrustManager {
|
||||
return factory.trustManagers.filterIsInstance<X509TrustManager>().single()
|
||||
}
|
||||
|
||||
private class PinnedOrSystemTrustManager(
|
||||
internal class PinnedOrSystemTrustManager(
|
||||
private val system: X509TrustManager,
|
||||
private val expectedPin: String,
|
||||
) : X509TrustManager {
|
||||
@@ -133,10 +133,8 @@ private class PinnedOrSystemTrustManager(
|
||||
val certificates = chain?.takeIf { it.isNotEmpty() }
|
||||
?: throw CertificateException("Proxy supplied no certificate chain")
|
||||
val systemAccepted = runCatching { system.checkServerTrusted(chain, authType) }.isSuccess
|
||||
if (systemAccepted) return
|
||||
|
||||
val leaf = certificates.first()
|
||||
leaf.checkValidity()
|
||||
if (!systemAccepted) leaf.checkValidity()
|
||||
val actual = "sha256/" + java.util.Base64.getEncoder().encodeToString(
|
||||
MessageDigest.getInstance("SHA-256").digest(leaf.publicKey.encoded),
|
||||
)
|
||||
|
||||
@@ -479,12 +479,15 @@ class ChatHandler {
|
||||
arrivedWhileAway: Boolean = false,
|
||||
) {
|
||||
val id = messageId?.let { "proactive-$it" } ?: "proactive-${java.util.UUID.randomUUID()}"
|
||||
val mediaHits = mutableListOf<Pair<String, MediaMarkerHit>>()
|
||||
val cleanedText = extractMediaMarkersFromContent(id, text, mediaHits)
|
||||
val visibleText = if (mediaHits.isEmpty()) text else cleanedText
|
||||
_messages.update { list ->
|
||||
if (messageId != null && list.any { it.id == id }) return@update list
|
||||
val msg = ChatMessage(
|
||||
id = id,
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = text,
|
||||
content = visibleText,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
agentName = agentName,
|
||||
badges = if (arrivedWhileAway) listOf("While away") else emptyList(),
|
||||
@@ -492,6 +495,8 @@ class ChatHandler {
|
||||
)
|
||||
(list + msg).let { if (it.size > MAX_MESSAGES) it.drop(it.size - MAX_MESSAGES) else it }
|
||||
}
|
||||
// The row must exist before the ViewModel attaches a loading card.
|
||||
mediaHits.forEach { (_, hit) -> dispatchMediaHit(id, hit) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1735,34 +1740,7 @@ class ChatHandler {
|
||||
// Now that the reloaded messages are in state, fire callbacks so the
|
||||
// ViewModel can insert LOADING/FAILED attachments via mutateMessage.
|
||||
for ((messageId, hit) in pendingMediaHits) {
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.token } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.path } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatchMediaHit(messageId, hit)
|
||||
}
|
||||
for ((messageId, path) in pendingPersistedUserImages) {
|
||||
onPersistedUserImageRequested(messageId, path)
|
||||
@@ -1996,29 +1974,33 @@ class ChatHandler {
|
||||
content: String,
|
||||
out: MutableList<Pair<String, MediaMarkerHit>>,
|
||||
): String {
|
||||
var cleaned = content
|
||||
val visibleLines = mutableListOf<String>()
|
||||
var openFence: String? = null
|
||||
for (rawLine in content.lines()) {
|
||||
val trimmed = rawLine.trim()
|
||||
if (trimmed.isEmpty()) continue
|
||||
if (trimmed.isEmpty()) {
|
||||
visibleLines += rawLine
|
||||
continue
|
||||
}
|
||||
val delimiter = fenceDelimiter(rawLine)
|
||||
if (delimiter != null) {
|
||||
openFence = if (openFence == delimiter) null else if (openFence == null) delimiter else openFence
|
||||
visibleLines += rawLine
|
||||
continue
|
||||
}
|
||||
if (openFence != null) {
|
||||
visibleLines += rawLine
|
||||
continue
|
||||
}
|
||||
if (openFence != null) continue
|
||||
|
||||
val hits = parseMediaMarkerLine(trimmed)
|
||||
if (hits.isNotEmpty()) {
|
||||
hits.forEach { out.add(messageId to it) }
|
||||
cleaned = cleaned
|
||||
.replace("\n$rawLine\n", "\n")
|
||||
.replace("\n$rawLine", "")
|
||||
.replace("$rawLine\n", "")
|
||||
.replace(rawLine, "")
|
||||
} else {
|
||||
visibleLines += rawLine
|
||||
}
|
||||
}
|
||||
return cleaned.trim()
|
||||
return visibleLines.joinToString("\n").trim()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2625,27 +2607,28 @@ class ChatHandler {
|
||||
*/
|
||||
private fun tryDispatchMediaMarker(messageId: String, line: String): Boolean {
|
||||
val hits = parseMediaMarkerLine(line)
|
||||
for (hit in hits) {
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker accepted from Relay stream")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits.forEach { dispatchMediaHit(messageId, it) }
|
||||
return hits.isNotEmpty()
|
||||
}
|
||||
|
||||
private fun dispatchMediaHit(messageId: String, hit: MediaMarkerHit) {
|
||||
val (key, reference) = when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> "$messageId:relay:${hit.token}" to hit.token
|
||||
is MediaMarkerHit.BarePath -> "$messageId:bare:${hit.path}" to hit.path
|
||||
}
|
||||
if (!dispatchedMediaMarkers.add(key)) return
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == reference } == true
|
||||
if (alreadyHydrated) return
|
||||
Log.d(TAG, "Media marker accepted")
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> onMediaAttachmentRequested(messageId, hit.token)
|
||||
is MediaMarkerHit.BarePath -> onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a matched annotation line from the message's displayed content.
|
||||
* This prevents the raw annotation text (e.g., `💻 terminal`) from showing
|
||||
|
||||
@@ -363,7 +363,7 @@ data class DashboardFetchedFile(
|
||||
*/
|
||||
class DashboardApiClient(
|
||||
baseUrl: String,
|
||||
private val okHttpClient: OkHttpClient = defaultClient(),
|
||||
internal val okHttpClient: OkHttpClient = defaultClient(),
|
||||
private val ownsHttpClient: Boolean = true,
|
||||
private val json: Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
@@ -2157,9 +2157,10 @@ fun sameDashboardBase(candidate: String, trusted: String): Boolean {
|
||||
fun trustedDashboardBearerAuthOrNull(
|
||||
candidate: String,
|
||||
trusted: String,
|
||||
httpConsentOrigins: Set<String> = emptySet(),
|
||||
tokenStoreProvider: () -> NativeDashboardTokenStore,
|
||||
): DashboardBearerAuth? =
|
||||
if (isNativeDashboardTransportEligible(candidate) &&
|
||||
if (isNativeDashboardTransportEligible(candidate, httpConsentOrigins) &&
|
||||
sameDashboardBase(candidate, trusted)
|
||||
) {
|
||||
DashboardBearerAuth(candidate, tokenStoreProvider())
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import java.io.IOException
|
||||
|
||||
data class DashboardSetupVerification(
|
||||
val status: DashboardStatus,
|
||||
val session: DashboardAuthSession,
|
||||
val ticketAvailable: Boolean,
|
||||
) {
|
||||
val authenticated: Boolean get() = session.authenticated && ticketAvailable
|
||||
}
|
||||
|
||||
/** Public status is discovery, not proof that a phone can use protected Dashboard routes. */
|
||||
suspend fun DashboardApiClient.verifySetup(): DashboardSetupVerification {
|
||||
val status = getStatus().getOrThrow()
|
||||
var session = currentSession().getOrThrow()
|
||||
val ticketAvailable = if (session.authenticated) {
|
||||
val ticket = requestWsTicket()
|
||||
val failure = ticket.exceptionOrNull()
|
||||
if (failure?.isDashboardSignInRequiredFailure() == true) {
|
||||
session = session.copy(authenticated = false)
|
||||
false
|
||||
} else {
|
||||
ticket.getOrThrow()
|
||||
true
|
||||
}
|
||||
} else false
|
||||
if (!status.authRequired && !session.authenticated) {
|
||||
throw DashboardLocalAuthenticationRequiredException()
|
||||
}
|
||||
return DashboardSetupVerification(status, session, ticketAvailable)
|
||||
}
|
||||
|
||||
class DashboardLocalAuthenticationRequiredException : IOException(
|
||||
"Hermes is reachable, but protected requests are not authorized. If the Dashboard is forwarded " +
|
||||
"from loopback, check its bind address, authentication provider, and dashboard.public_url " +
|
||||
"on the host. A 401 alone does not identify the cause.",
|
||||
)
|
||||
@@ -277,7 +277,7 @@ class GatewayChatClient(
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
private val client: OkHttpClient = (okHttpClient ?: OkHttpClient())
|
||||
private fun socketClient(base: OkHttpClient): OkHttpClient = base
|
||||
.newBuilder()
|
||||
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
||||
// reached over Tailscale (DERP cold start) can take longer to complete
|
||||
@@ -294,8 +294,19 @@ class GatewayChatClient(
|
||||
* being torn down — the in-flight turn's session is server-side and the
|
||||
* same shared gateway sits behind both routes.
|
||||
*/
|
||||
private data class RouteTransport(
|
||||
val dashboard: DashboardApiClient,
|
||||
val socket: OkHttpClient,
|
||||
)
|
||||
|
||||
@Volatile
|
||||
private var dashboardClient: DashboardApiClient = initialDashboardClient
|
||||
private var routeTransport = RouteTransport(
|
||||
initialDashboardClient,
|
||||
socketClient(okHttpClient ?: initialDashboardClient.okHttpClient),
|
||||
)
|
||||
|
||||
private val dashboardClient: DashboardApiClient
|
||||
get() = routeTransport.dashboard
|
||||
|
||||
private val _connectionState = MutableStateFlow(GatewayConnectionState.Idle)
|
||||
val connectionState: StateFlow<GatewayConnectionState> = _connectionState.asStateFlow()
|
||||
@@ -1001,7 +1012,7 @@ class GatewayChatClient(
|
||||
fun retarget(newDashboardClient: DashboardApiClient) {
|
||||
if (dashboardClient === newDashboardClient) return
|
||||
Log.i(TAG, "Gateway retargeting to a new route (turn active=${hasActiveTurn()})")
|
||||
dashboardClient = newDashboardClient
|
||||
routeTransport = RouteTransport(newDashboardClient, socketClient(newDashboardClient.okHttpClient))
|
||||
if (hasActiveTurn()) {
|
||||
retargetedThisTurn = activeTurn?.ended == false
|
||||
webSocket?.cancel()
|
||||
@@ -3080,12 +3091,14 @@ class GatewayChatClient(
|
||||
}
|
||||
|
||||
private suspend fun connectOnce() {
|
||||
// Ticket, URL and TLS/auth policy must belong to one route snapshot.
|
||||
val transport = routeTransport
|
||||
val connectStart = System.nanoTime()
|
||||
_processCapability.value = GatewayProcessCapability.Unknown
|
||||
_activeSessionCapability.value = GatewayActiveSessionCapability.Unknown
|
||||
_approvalModeCapability.value = GatewayApprovalModeCapability.Unknown
|
||||
_connectionState.value = GatewayConnectionState.MintingTicket
|
||||
val ticket = dashboardClient.requestWsTicket().getOrElse { e ->
|
||||
val ticket = transport.dashboard.requestWsTicket().getOrElse { e ->
|
||||
val statusCode = (e as? DashboardHttpException)?.statusCode
|
||||
val authFailure = statusCode in setOf(401, 403)
|
||||
val rateLimited = statusCode == 429
|
||||
@@ -3108,8 +3121,15 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
val ticketMs = (System.nanoTime() - connectStart) / 1_000_000
|
||||
if (transport !== routeTransport) {
|
||||
throw GatewayConnectAttemptException(
|
||||
"Gateway route changed while minting a ticket",
|
||||
GatewayConnectFailureStage.Ticket,
|
||||
retryable = true,
|
||||
)
|
||||
}
|
||||
val socketProfile = currentSessionProfile()
|
||||
val url = dashboardClient.gatewayWebSocketUrl(
|
||||
val url = transport.dashboard.gatewayWebSocketUrl(
|
||||
ticket = ticket.ticket,
|
||||
profile = socketProfile,
|
||||
)
|
||||
@@ -3122,7 +3142,7 @@ class GatewayChatClient(
|
||||
_connectionState.value = GatewayConnectionState.Connecting
|
||||
val ready = CompletableDeferred<Unit>()
|
||||
readySignal = ready
|
||||
val socket = client.newWebSocket(
|
||||
val socket = transport.socket.newWebSocket(
|
||||
Request.Builder().url(url).build(),
|
||||
createListener(ready),
|
||||
)
|
||||
|
||||
+135
-63
@@ -9,18 +9,23 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.content.res.Configuration
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.annotation.MainThread
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import com.hermesandroid.relay.MainActivity
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.setGatewayKeepAlive
|
||||
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Foreground service that holds the app process up so work the user already
|
||||
@@ -48,16 +53,16 @@ import kotlinx.coroutines.launch
|
||||
*
|
||||
* The service's only job is to hold the process in the foreground. The socket
|
||||
* stays open because [GatewayChatClient.setKeepAliveInBackground] stops its
|
||||
* idle-close timer while retention is required. On task removal (user swipes the app
|
||||
* away) the ViewModel + socket die with the process, so the service stops
|
||||
* itself rather than leave a notification that lies about being connected.
|
||||
* idle-close timer while retention is required. Task removal releases local
|
||||
* foreground protection; it does not terminate server-owned work or assume
|
||||
* that removing a task kills the application process.
|
||||
*
|
||||
* # Android 15 watchdog
|
||||
* # Foreground-start obligation (Android 8+)
|
||||
*
|
||||
* On target SDK 35 any intent to a service that declares a foregroundServiceType
|
||||
* must call `startForeground` within 5s — so [onStartCommand] always does that
|
||||
* first, before branching on the action. Shutdown goes through [stop]
|
||||
* (`stopService`) to bypass [onStartCommand] entirely.
|
||||
* An accepted startForegroundService must promote promptly, even if demand
|
||||
* disappears before delivery. Never stopService a pending start: Android 12
|
||||
* also treats teardown before promotion as a foreground-start failure.
|
||||
* Main-thread demand is coalesced until onStartCommand acknowledges the start.
|
||||
*/
|
||||
class GatewayKeepAliveService : Service() {
|
||||
companion object {
|
||||
@@ -67,47 +72,76 @@ class GatewayKeepAliveService : Service() {
|
||||
const val NOTIFICATION_ID = 4713
|
||||
const val ACTION_STOP = "com.hermesandroid.relay.gateway.KEEPALIVE_STOP"
|
||||
private const val ACTION_REFRESH = "com.hermesandroid.relay.gateway.KEEPALIVE_REFRESH"
|
||||
private const val EXTRA_PERSISTENT = "persistent"
|
||||
private const val EXTRA_ACTIVE_TURNS = "active_turns"
|
||||
private const val EXTRA_WAITING_SESSIONS = "waiting_sessions"
|
||||
@Volatile private var runningInstance: GatewayKeepAliveService? = null
|
||||
private const val EXTRA_START_TOKEN = "start_token"
|
||||
private var runningInstance: GatewayKeepAliveService? = null
|
||||
private var pendingStart: String? = null
|
||||
private var desiredPersistent = false
|
||||
private var desiredTurns = ActiveTurnKeepAliveRegistry.Snapshot()
|
||||
private var wasForeground = false
|
||||
private var taskRemoved = false
|
||||
@Volatile private var persistentToken: String? = null
|
||||
// Preference writes must survive service teardown, but never process death.
|
||||
private val preferenceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
@MainThread
|
||||
fun update(
|
||||
context: Context,
|
||||
persistent: Boolean,
|
||||
activeTurns: ActiveTurnKeepAliveRegistry.Snapshot,
|
||||
appForeground: Boolean = true,
|
||||
) {
|
||||
if (!persistent && !activeTurns.required) {
|
||||
stop(context)
|
||||
return
|
||||
checkMainThread()
|
||||
if (appForeground && !wasForeground) taskRemoved = false
|
||||
wasForeground = appForeground
|
||||
if (persistent != desiredPersistent) {
|
||||
persistentToken = if (persistent) UUID.randomUUID().toString() else null
|
||||
}
|
||||
runningInstance?.let { service ->
|
||||
service.applyState(persistent, activeTurns)
|
||||
service.startForegroundNotification()
|
||||
desiredPersistent = persistent
|
||||
desiredTurns = activeTurns
|
||||
// Keep the accepted start alive until Android delivers its command.
|
||||
if (pendingStart != null) return
|
||||
runningInstance?.let {
|
||||
it.reconcile()
|
||||
return
|
||||
}
|
||||
if (taskRemoved || !appForeground || (!persistent && !activeTurns.required)) return
|
||||
val token = UUID.randomUUID().toString()
|
||||
pendingStart = token
|
||||
val intent = Intent(context.applicationContext, GatewayKeepAliveService::class.java)
|
||||
.setAction(ACTION_REFRESH)
|
||||
.putExtra(EXTRA_PERSISTENT, persistent)
|
||||
.putExtra(EXTRA_ACTIVE_TURNS, activeTurns.activeTurnCount)
|
||||
.putExtra(EXTRA_WAITING_SESSIONS, activeTurns.waitingSessionCount)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.applicationContext.startForegroundService(intent)
|
||||
} else {
|
||||
context.applicationContext.startService(intent)
|
||||
.putExtra(EXTRA_START_TOKEN, token)
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.applicationContext.startForegroundService(intent)
|
||||
} else {
|
||||
context.applicationContext.startService(intent)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
pendingStart = null
|
||||
Log.w(TAG, "Foreground service launch rejected; retaining server-owned work", e)
|
||||
}
|
||||
}
|
||||
|
||||
@MainThread
|
||||
fun stop(context: Context) {
|
||||
// stopService() bypasses onStartCommand, so a "please shut down"
|
||||
// never trips the Android 15 foreground-start watchdog.
|
||||
context.applicationContext.stopService(
|
||||
Intent(context.applicationContext, GatewayKeepAliveService::class.java),
|
||||
)
|
||||
update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(), wasForeground)
|
||||
}
|
||||
|
||||
private fun checkMainThread() {
|
||||
check(Looper.myLooper() == Looper.getMainLooper())
|
||||
}
|
||||
|
||||
internal fun resetForTest() {
|
||||
runningInstance = null
|
||||
pendingStart = null
|
||||
desiredPersistent = false
|
||||
desiredTurns = ActiveTurnKeepAliveRegistry.Snapshot()
|
||||
persistentToken = null
|
||||
wasForeground = false
|
||||
taskRemoved = false
|
||||
}
|
||||
}
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private var persistent = false
|
||||
private var activeTurns = 0
|
||||
private var waitingSessions = 0
|
||||
@@ -116,45 +150,63 @@ class GatewayKeepAliveService : Service() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
runningInstance = this
|
||||
// No datastore, socket, coroutine or other owner work ahead of promotion.
|
||||
// A cold stale notification action has no accepted foreground start.
|
||||
if (pendingStart != null) {
|
||||
applyState(desiredPersistent, desiredTurns)
|
||||
startForegroundNotification()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val token = intent?.getStringExtra(EXTRA_START_TOKEN)
|
||||
if (intent?.action == ACTION_REFRESH) {
|
||||
persistent = intent.getBooleanExtra(EXTRA_PERSISTENT, false)
|
||||
activeTurns = intent.getIntExtra(EXTRA_ACTIVE_TURNS, 0).coerceAtLeast(0)
|
||||
waitingSessions = intent.getIntExtra(EXTRA_WAITING_SESSIONS, 0)
|
||||
.coerceIn(0, activeTurns)
|
||||
}
|
||||
startForegroundNotification()
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
Log.i(TAG, "ACTION_STOP → user disabled continuous background connection")
|
||||
scope.launch { runCatching { applicationContext.setGatewayKeepAlive(false) } }
|
||||
persistent = false
|
||||
if (activeTurns == 0) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
} else {
|
||||
startForegroundNotification()
|
||||
applyState(desiredPersistent, desiredTurns)
|
||||
// Also promote reused service instances before acknowledging the start.
|
||||
// A delivered start still owes promotion if process-local demand
|
||||
// was lost or its token is stale. Never replay its old demand.
|
||||
if (startForegroundNotification()) {
|
||||
if (token == pendingStart) pendingStart = null
|
||||
if (pendingStart == null) {
|
||||
runningInstance = this
|
||||
reconcile()
|
||||
}
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
} else if (intent?.action == ACTION_STOP &&
|
||||
intent.data?.lastPathSegment == persistentToken && persistentToken != null
|
||||
) {
|
||||
val actionToken = persistentToken
|
||||
val context = applicationContext
|
||||
preferenceScope.launch {
|
||||
try {
|
||||
context.relayDataStore.edit { preferences ->
|
||||
// Recheck inside the serialized edit; an old action must
|
||||
// not undo a subsequent disable/re-enable cycle.
|
||||
if (persistentToken == actionToken) preferences[KEY_GATEWAY_KEEP_ALIVE] = false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not disable persistent connection", e)
|
||||
}
|
||||
}
|
||||
// The preference collector reconciles current active-turn demand
|
||||
// after persistence. Never stop from the notification's old snapshot.
|
||||
}
|
||||
if (runningInstance !== this && pendingStart == null) stopSelfResult(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
super.onTaskRemoved(rootIntent)
|
||||
// The socket lives in the ViewModel, which dies when the task is
|
||||
// removed — keeping the notification would be a lie. Stop cleanly.
|
||||
Log.i(TAG, "onTaskRemoved → app swiped away; stopping keep-alive")
|
||||
ActiveTurnKeepAliveRegistry.releaseAll()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
taskRemoved = true
|
||||
// Leases belong to chat owners. Keep them intact so a surviving
|
||||
// process can protect unfinished turns again when the user returns.
|
||||
// A queued new start still owes Android promotion before retirement.
|
||||
if (pendingStart == null) retire()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (runningInstance === this) runningInstance = null
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -164,7 +216,23 @@ class GatewayKeepAliveService : Service() {
|
||||
// this foreground service (and its Gateway socket) alive. Re-post the
|
||||
// existing notification so its localized title/body follow the new
|
||||
// application resources without restarting either owner.
|
||||
startForegroundNotification()
|
||||
if (runningInstance === this) reconcile()
|
||||
}
|
||||
|
||||
private fun reconcile() {
|
||||
if (taskRemoved || (!desiredPersistent && !desiredTurns.required)) {
|
||||
retire()
|
||||
} else {
|
||||
applyState(desiredPersistent, desiredTurns)
|
||||
startForegroundNotification()
|
||||
}
|
||||
}
|
||||
|
||||
private fun retire() {
|
||||
if (runningInstance === this) runningInstance = null
|
||||
// Let Android remove the foreground notification with service teardown.
|
||||
// Do not demote an instance while another start may be queued for it.
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun applyState(
|
||||
@@ -181,10 +249,10 @@ class GatewayKeepAliveService : Service() {
|
||||
// satisfied. Suppress retained defensively — lint's ForegroundServiceType
|
||||
// check is finicky about correlating the runtime type arg with the manifest.
|
||||
@SuppressLint("ForegroundServiceType")
|
||||
private fun startForegroundNotification() {
|
||||
ensureChannel()
|
||||
val notification = buildNotification()
|
||||
private fun startForegroundNotification(): Boolean {
|
||||
try {
|
||||
ensureChannel()
|
||||
val notification = buildNotification()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
@@ -194,9 +262,12 @@ class GatewayKeepAliveService : Service() {
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "startForeground failed — stopping keep-alive", t)
|
||||
stopSelf()
|
||||
return true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Foreground notification failed; retaining server-owned work", e)
|
||||
pendingStart = null
|
||||
retire()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,6 +279,7 @@ class GatewayKeepAliveService : Service() {
|
||||
val tapPending = PendingIntent.getActivity(this, 0, tapIntent, pendingFlags)
|
||||
|
||||
val stopIntent = Intent(this, GatewayKeepAliveService::class.java).setAction(ACTION_STOP)
|
||||
.setData(Uri.parse("hermes-relay://keep-alive/$persistentToken"))
|
||||
val stopPending = PendingIntent.getService(this, 1, stopIntent, pendingFlags)
|
||||
|
||||
val (title, body) = when {
|
||||
|
||||
+17
-2
@@ -111,6 +111,8 @@ class NativeDashboardAuthClient(
|
||||
private val tokenStore: NativeDashboardTokenStore,
|
||||
private val client: OkHttpClient = OkHttpClient.Builder()
|
||||
.dns(RetryingNativeAuthDns())
|
||||
.followRedirects(false)
|
||||
.followSslRedirects(false)
|
||||
.retryOnConnectionFailure(false)
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(15, TimeUnit.SECONDS)
|
||||
@@ -390,15 +392,28 @@ internal class NativeDashboardCallbackException(
|
||||
val retryable: Boolean = true,
|
||||
) : IOException(message)
|
||||
|
||||
internal fun isNativeDashboardTransportEligible(baseUrl: String): Boolean {
|
||||
internal fun isNativeDashboardTransportEligible(
|
||||
baseUrl: String,
|
||||
httpConsentOrigins: Set<String> = emptySet(),
|
||||
): Boolean {
|
||||
val url = baseUrl.trim().trimEnd('/').toHttpUrlOrNull() ?: return false
|
||||
return url.scheme == "https" ||
|
||||
(
|
||||
url.scheme == "http" &&
|
||||
(url.host == "127.0.0.1" || isPrivateNetworkLiteral(url.host))
|
||||
(url.host == "127.0.0.1" || isPrivateNetworkLiteral(url.host) ||
|
||||
com.hermesandroid.relay.data.dashboardHttpConsentMatches(baseUrl, httpConsentOrigins))
|
||||
)
|
||||
}
|
||||
|
||||
/** A cleartext exception never authorizes following a request onto another origin. */
|
||||
internal fun dashboardClientWithHttpConsent(
|
||||
client: OkHttpClient,
|
||||
baseUrl: String,
|
||||
httpConsentOrigins: Set<String>,
|
||||
): OkHttpClient = if (com.hermesandroid.relay.data.dashboardHttpConsentMatches(baseUrl, httpConsentOrigins)) {
|
||||
client.newBuilder().followRedirects(false).followSslRedirects(false).build()
|
||||
} else client
|
||||
|
||||
/**
|
||||
* Hermes already permits explicitly configured HTTP dashboard sessions on
|
||||
* local routes. The brokered flow is no less protected than that cookie flow,
|
||||
|
||||
@@ -106,6 +106,9 @@ internal class HermesRuntimeBinder(
|
||||
},
|
||||
apiBearerTokenProvider = connection::getApiKey,
|
||||
dashboardHttpClientProvider = connection::dashboardHttpClientForRelayIngress,
|
||||
pluginProxyHttpClientProvider = { url ->
|
||||
connection.pluginProxyClientForUrl(url, includeRelaySessionHeader = false)
|
||||
},
|
||||
dashboardIngressWebSocketRequestProvider = connection::dashboardRelayRequestForIngress,
|
||||
)
|
||||
val standardVoiceClient = StandardHermesVoiceClient(
|
||||
@@ -327,7 +330,8 @@ internal class HermesRuntimeBinder(
|
||||
connection.serverCapabilities,
|
||||
connection.gatewayAvailability,
|
||||
connection.effectiveDashboardUrl,
|
||||
) { preference, _, gateway, dashboardUrl ->
|
||||
connection.activeConnection,
|
||||
) { preference, _, gateway, dashboardUrl, _ ->
|
||||
Triple(preference, gateway, dashboardUrl)
|
||||
}.collectLatest { (preference, _, dashboardUrl) ->
|
||||
if (
|
||||
|
||||
@@ -1095,14 +1095,16 @@ fun RelayApp() {
|
||||
}
|
||||
}
|
||||
|
||||
// Observe theme preference
|
||||
val themePreference by connectionViewModel.theme.collectAsState()
|
||||
val appThemeId by connectionViewModel.appTheme.collectAsState()
|
||||
val fontScale by connectionViewModel.fontScale.collectAsState()
|
||||
val appFontId by connectionViewModel.appFont.collectAsState()
|
||||
val appearanceAccent by connectionViewModel.appearanceAccent.collectAsState()
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
val activeCustomTheme by connectionViewModel.activeCustomTheme.collectAsState()
|
||||
// The same decoded emission that releases splash readiness owns the first
|
||||
// real frame; individual settings flows can hydrate independently later.
|
||||
val appearance by connectionViewModel.appearance.collectAsState()
|
||||
val themePreference = appearance.themePreference
|
||||
val appThemeId = appearance.appThemeId
|
||||
val fontScale = appearance.fontScale
|
||||
val appFontId = appearance.appFontId
|
||||
val appearanceAccent = appearance.accentHex
|
||||
val appearanceShape = appearance.shapeId
|
||||
val activeCustomTheme = appearance.customTheme
|
||||
val navController = rememberNavController()
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
@@ -1964,7 +1966,7 @@ fun RelayApp() {
|
||||
// (WhatsApp-style; see ChatScreen). That's the "can I talk to the
|
||||
// agent?" signal.
|
||||
// • Relay socket (bridge/terminal/relay-voice) → the bottom
|
||||
// RelayStatusStrip's "Reconnecting…" cue only. It never blocks chat,
|
||||
// RelayStatusStrip is reserved for the active chat owner's status.
|
||||
// so it stays ambient. (`connectionReconnecting` below.)
|
||||
// A routine in-progress reconnect surfaces only in the bottom strip.
|
||||
// Computed off the raw status (not the dismiss-gated `toast`) because the
|
||||
|
||||
+10
-3
@@ -1198,12 +1198,18 @@ fun ActiveCardSecurityPosture(
|
||||
val authState by connectionViewModel.authState.collectAsState()
|
||||
val currentPairedSession by connectionViewModel.currentPairedSession.collectAsState()
|
||||
val pairedDevices by connectionViewModel.pairedDevices.collectAsState()
|
||||
// Live dashboard path (Secure Link / preferred route), not only the saved
|
||||
// plain :9119 configuredDashboardUrl that pairing still stores alongside.
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val dashboardDisplayUrl = effectiveDashboardUrl.trim().trimEnd('/').ifBlank {
|
||||
activeConnection?.resolvedDashboardUrl.orEmpty()
|
||||
}
|
||||
|
||||
val dashboardStatus = activeConnection?.dashboardLastStatus
|
||||
val dashboardSignInRequired = dashboardStatus?.authRequired == true &&
|
||||
dashboardStatus.authenticated != true
|
||||
val dashboardValue = when {
|
||||
activeConnection?.resolvedDashboardUrl.isNullOrBlank() ->
|
||||
dashboardDisplayUrl.isBlank() ->
|
||||
stringResource(R.string.active_section_not_configured)
|
||||
dashboardStatus == null -> stringResource(R.string.active_section_not_checked)
|
||||
!dashboardStatus.reachable -> stringResource(R.string.active_section_unreachable)
|
||||
@@ -1255,7 +1261,7 @@ fun ActiveCardSecurityPosture(
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Text(
|
||||
text = activeConnection?.resolvedDashboardUrl.orEmpty().ifBlank {
|
||||
text = dashboardDisplayUrl.ifBlank {
|
||||
stringResource(R.string.active_section_not_configured)
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -2031,11 +2037,12 @@ fun ActiveCardRoutesSection(
|
||||
original = routeEditorOriginal,
|
||||
relayEnabled = connection.relayUrl.isNotBlank() ||
|
||||
endpoints.any { it.relay != null },
|
||||
onSave = { role, dashboardUrl, onResult ->
|
||||
onSave = { role, dashboardUrl, httpConsentOrigin, onResult ->
|
||||
connectionViewModel.saveExtraRoute(
|
||||
role = role,
|
||||
dashboardUrl = dashboardUrl,
|
||||
original = routeEditorOriginal,
|
||||
httpConsentOrigin = httpConsentOrigin,
|
||||
onResult = onResult,
|
||||
)
|
||||
},
|
||||
|
||||
@@ -20,6 +20,8 @@ import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -249,9 +251,10 @@ fun ConnectionWizard(
|
||||
var nearbyBusy by remember { mutableStateOf(false) }
|
||||
var nearbyResults by remember { mutableStateOf<List<HermesLanDiscoveryResult>>(emptyList()) }
|
||||
var nearbyMessage by remember { mutableStateOf<String?>(null) }
|
||||
var dashboardAddress by rememberSaveable(wizardDraftIdentity, currentDashboardUrl) {
|
||||
mutableStateOf(currentDashboardUrl)
|
||||
var dashboardAddress by rememberSaveable(wizardDraftIdentity) {
|
||||
mutableStateOf(if (connectionDraftId != null) "" else currentDashboardUrl)
|
||||
}
|
||||
var dashboardHttpConsentOrigin by rememberSaveable(wizardDraftIdentity) { mutableStateOf<String?>(null) }
|
||||
var dashboardProbeBusy by remember { mutableStateOf(false) }
|
||||
var dashboardProbeError by remember { mutableStateOf<String?>(null) }
|
||||
var dashboardProbeResult by remember {
|
||||
@@ -425,16 +428,24 @@ fun ConnectionWizard(
|
||||
val inspectDashboard: (String, String?) -> Unit = { address, suggestedHostname ->
|
||||
dashboardAddress = address
|
||||
dashboardSuggestedHostname = suggestedHostname
|
||||
dashboardProbeBusy = true
|
||||
dashboardProbeError = null
|
||||
connectionViewModel.probeHermesDashboard(address) { result ->
|
||||
dashboardProbeBusy = false
|
||||
if (result.ok) {
|
||||
dashboardProbeResult = result
|
||||
dashboardAddress = result.dashboardUrl
|
||||
step = WizardStep.DashboardFound
|
||||
} else {
|
||||
dashboardProbeError = result.message
|
||||
val normalized = Connection.normalizeDashboardUrlInput(address)
|
||||
if (com.hermesandroid.relay.data.dashboardHttpConsentRequired(normalized) &&
|
||||
dashboardHttpConsentOrigin != com.hermesandroid.relay.data.dashboardHttpOrigin(normalized)
|
||||
) {
|
||||
dashboardEntryIntent = DashboardEntryIntent.Server
|
||||
step = WizardStep.DashboardManual
|
||||
} else {
|
||||
dashboardProbeBusy = true
|
||||
connectionViewModel.probeHermesDashboard(address, dashboardHttpConsentOrigin) { result ->
|
||||
dashboardProbeBusy = false
|
||||
if (result.ok) {
|
||||
dashboardProbeResult = result
|
||||
dashboardAddress = result.dashboardUrl
|
||||
step = WizardStep.DashboardFound
|
||||
} else {
|
||||
dashboardProbeError = result.message
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,6 +563,7 @@ fun ConnectionWizard(
|
||||
connectionViewModel.saveDashboardConnection(
|
||||
dashboardUrl = draft.dashboardUrl,
|
||||
discoveredHostname = draft.discoveredHostname,
|
||||
httpConsentOrigin = draft.httpConsentOrigin,
|
||||
) { saved ->
|
||||
standardBusy = false
|
||||
saved.fold(
|
||||
@@ -652,7 +664,7 @@ fun ConnectionWizard(
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (step != WizardStep.Nearby) {
|
||||
WizardStepIndicator(currentStep = step.indicatorIndex, method = chosenMethod)
|
||||
WizardStepIndicator(currentStep = step.indicatorIndex, method = chosenMethod, directApi = step == WizardStep.StandardEntry)
|
||||
}
|
||||
|
||||
AnimatedContent(
|
||||
@@ -707,8 +719,11 @@ fun ConnectionWizard(
|
||||
address = dashboardAddress,
|
||||
onAddressChange = {
|
||||
dashboardAddress = it
|
||||
dashboardHttpConsentOrigin = null
|
||||
dashboardProbeError = null
|
||||
},
|
||||
httpConsentOrigin = dashboardHttpConsentOrigin,
|
||||
onHttpConsentChange = { dashboardHttpConsentOrigin = it },
|
||||
busy = dashboardProbeBusy,
|
||||
error = dashboardProbeError,
|
||||
onBack = { step = WizardStep.Nearby },
|
||||
@@ -729,6 +744,7 @@ fun ConnectionWizard(
|
||||
dashboardUrl = result.dashboardUrl,
|
||||
signInRequired = result.signInRequired,
|
||||
discoveredHostname = dashboardSuggestedHostname,
|
||||
httpConsentOrigin = result.httpConsentOrigin,
|
||||
)
|
||||
val existing = findDuplicateFor("", "", result.dashboardUrl)
|
||||
if (existing != null) {
|
||||
@@ -1526,6 +1542,7 @@ private data class DashboardConnectionDraft(
|
||||
val dashboardUrl: String,
|
||||
val signInRequired: Boolean,
|
||||
val discoveredHostname: String? = null,
|
||||
val httpConsentOrigin: String? = null,
|
||||
)
|
||||
|
||||
private const val SetupGuideUrl = "https://hermes-relay.dev/docs/guide/getting-started"
|
||||
@@ -1537,7 +1554,7 @@ private fun openExternalUrl(context: android.content.Context, url: String) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WizardStepIndicator(currentStep: Int, method: PairMethod) {
|
||||
private fun WizardStepIndicator(currentStep: Int, method: PairMethod, directApi: Boolean = false) {
|
||||
val totalSteps = 3
|
||||
Row(
|
||||
modifier = Modifier
|
||||
@@ -1599,7 +1616,7 @@ private fun WizardStepIndicator(currentStep: Int, method: PairMethod) {
|
||||
text = when (currentStep) {
|
||||
0 -> stringResource(R.string.cw_step_1_3)
|
||||
1 -> when (method) {
|
||||
PairMethod.Standard -> stringResource(R.string.cw_step_2_3_standard)
|
||||
PairMethod.Standard -> stringResource(if (directApi) R.string.cw_hermes_label else R.string.cw_step_2_3_standard)
|
||||
PairMethod.Scan -> stringResource(R.string.cw_step_2_3_scan)
|
||||
PairMethod.EnterCode -> stringResource(R.string.cw_step_2_3_enter_code)
|
||||
PairMethod.ShowCode -> stringResource(R.string.cw_step_2_3_show_code)
|
||||
@@ -1644,6 +1661,7 @@ private fun NearbyHermesStep(
|
||||
}
|
||||
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun NewNearbyHermesStep(
|
||||
busy: Boolean,
|
||||
@@ -1754,10 +1772,9 @@ private fun NewNearbyHermesStep(
|
||||
)
|
||||
}
|
||||
|
||||
Row(
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = { openExternalUrl(context, SetupGuideUrl) }) {
|
||||
Icon(
|
||||
@@ -1886,6 +1903,8 @@ private fun DashboardManualStep(
|
||||
intent: DashboardEntryIntent,
|
||||
address: String,
|
||||
onAddressChange: (String) -> Unit,
|
||||
httpConsentOrigin: String?,
|
||||
onHttpConsentChange: (String?) -> Unit,
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onBack: () -> Unit,
|
||||
@@ -1904,6 +1923,9 @@ private fun DashboardManualStep(
|
||||
optionalHttpUrlError(address, context)
|
||||
}
|
||||
val resolvedAddress = if (cloudSlugMode) resolveNousCloudDashboardAddress(address) else address.trim()
|
||||
val normalizedAddress = Connection.normalizeDashboardUrlInput(resolvedAddress)
|
||||
val httpAccepted = !com.hermesandroid.relay.data.dashboardHttpConsentRequired(normalizedAddress) ||
|
||||
httpConsentOrigin == com.hermesandroid.relay.data.dashboardHttpOrigin(normalizedAddress)
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
@@ -1959,7 +1981,7 @@ private fun DashboardManualStep(
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Go, autoCorrectEnabled = false),
|
||||
keyboardActions = KeyboardActions(onGo = {
|
||||
if (address.isNotBlank() && fieldError == null && !busy) onSubmit(resolvedAddress)
|
||||
if (address.isNotBlank() && fieldError == null && !busy && httpAccepted) onSubmit(resolvedAddress)
|
||||
}),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
@@ -1983,13 +2005,17 @@ private fun DashboardManualStep(
|
||||
error?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
DashboardHttpConsentControl(normalizedAddress, httpConsentOrigin, onHttpConsentChange, enabled = !busy)
|
||||
TextButton(onClick = { openExternalUrl(context, SetupGuideUrl) }) {
|
||||
Text(stringResource(R.string.cw_setup_guide))
|
||||
}
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = onBack, enabled = !busy, modifier = Modifier.weight(1f).heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.cw_back))
|
||||
}
|
||||
Button(
|
||||
onClick = { onSubmit(resolvedAddress) },
|
||||
enabled = address.isNotBlank() && fieldError == null && !busy,
|
||||
enabled = address.isNotBlank() && fieldError == null && !busy && httpAccepted,
|
||||
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
|
||||
) {
|
||||
if (busy) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
@@ -2039,12 +2065,12 @@ private fun DashboardFoundStep(
|
||||
}
|
||||
FoundCapabilityLine(
|
||||
label = stringResource(R.string.cw_chat),
|
||||
value = if (result.signInRequired) stringResource(R.string.cw_available_after_signin) else stringResource(R.string.cw_ready),
|
||||
ready = !result.signInRequired,
|
||||
value = if (result.signInRequired) stringResource(R.string.cw_available_after_signin) else stringResource(R.string.cw_chat_checked_on_open),
|
||||
ready = false,
|
||||
)
|
||||
FoundCapabilityLine(
|
||||
label = stringResource(R.string.cw_manage),
|
||||
value = if (result.signInRequired) stringResource(R.string.cw_available_after_signin) else stringResource(R.string.cw_ready),
|
||||
value = if (result.signInRequired) stringResource(R.string.cw_available_after_signin) else stringResource(R.string.cw_auth_verified),
|
||||
ready = !result.signInRequired,
|
||||
)
|
||||
FoundCapabilityLine(
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.dashboardHttpConsentRequired
|
||||
import com.hermesandroid.relay.data.dashboardHttpOrigin
|
||||
|
||||
@Composable
|
||||
fun DashboardHttpConsentControl(
|
||||
address: String,
|
||||
confirmedOrigin: String?,
|
||||
onConfirmationChange: (String?) -> Unit,
|
||||
enabled: Boolean = true,
|
||||
required: Boolean = dashboardHttpConsentRequired(address),
|
||||
) {
|
||||
if (!required) return
|
||||
val origin = dashboardHttpOrigin(address) ?: return
|
||||
val checked = confirmedOrigin == origin
|
||||
Column {
|
||||
Text(
|
||||
stringResource(R.string.dashboard_http_risk, origin),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable(
|
||||
value = checked,
|
||||
enabled = enabled,
|
||||
role = Role.Checkbox,
|
||||
onValueChange = { onConfirmationChange(if (it) origin else null) },
|
||||
).padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = checked, onCheckedChange = null, enabled = enabled)
|
||||
Text(stringResource(R.string.dashboard_http_allow), modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package com.hermesandroid.relay.ui.components
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -69,6 +71,7 @@ import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.network.shared.EndpointSurface
|
||||
import com.hermesandroid.relay.network.shared.RouteProbeOutcome
|
||||
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.net.URI
|
||||
@@ -427,11 +430,6 @@ private fun EndpointRow(
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = stringResource(R.string.secure_link_auth_note),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -580,10 +578,10 @@ private fun RouteSurfaceMap(
|
||||
outcomeFor: (EndpointSurface) -> RouteProbeOutcome? = { null },
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val dashboardUrl = candidate.dashboard?.url
|
||||
?: candidate.api?.url?.let(Connection::deriveDefaultDashboardUrl)
|
||||
val apiUrl = candidate.api?.url
|
||||
val relayUrl = candidate.relay?.url
|
||||
val proxy = candidate.pluginProxyRoutesOrNull()
|
||||
val dashboardUrl = candidate.gatewayRouteUrl()
|
||||
val apiUrl = candidate.api?.url ?: proxy?.apiBaseUrl
|
||||
val relayUrl = candidate.relay?.url ?: proxy?.relayWebSocketUrl
|
||||
val dashboardOutcome = outcomeFor(EndpointSurface.Dashboard)
|
||||
val apiOutcome = outcomeFor(EndpointSurface.Api)
|
||||
val relayOutcome = outcomeFor(EndpointSurface.Relay)
|
||||
@@ -925,10 +923,11 @@ internal fun EndpointCandidate.hasPlainRelayTransport(): Boolean {
|
||||
@Composable
|
||||
fun DashboardAddressEditorDialog(
|
||||
initialUrl: String,
|
||||
onSave: (dashboardUrl: String, onResult: (String?) -> Unit) -> Unit,
|
||||
onSave: (dashboardUrl: String, httpConsentOrigin: String?, onResult: (String?) -> Unit) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var url by remember(initialUrl) { mutableStateOf(initialUrl) }
|
||||
var httpConsentOrigin by remember(url) { mutableStateOf<String?>(null) }
|
||||
var errorText by remember { mutableStateOf<String?>(null) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
val normalized = remember(url) {
|
||||
@@ -940,7 +939,7 @@ fun DashboardAddressEditorDialog(
|
||||
onDismissRequest = { if (!saving) onDismiss() },
|
||||
title = { Text(stringResource(R.string.dashboard_address_editor_title)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_address_editor_body),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -973,14 +972,17 @@ fun DashboardAddressEditorDialog(
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
DashboardHttpConsentControl(normalized, httpConsentOrigin, { httpConsentOrigin = it }, enabled = !saving)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
enabled = valid && !saving && normalized != initialUrl.trim().trimEnd('/'),
|
||||
enabled = valid && !saving && normalized != initialUrl.trim().trimEnd('/') &&
|
||||
(!com.hermesandroid.relay.data.dashboardHttpConsentRequired(normalized) ||
|
||||
httpConsentOrigin == com.hermesandroid.relay.data.dashboardHttpOrigin(normalized)),
|
||||
onClick = {
|
||||
saving = true
|
||||
onSave(normalized) { error ->
|
||||
onSave(normalized, httpConsentOrigin) { error ->
|
||||
saving = false
|
||||
if (error == null) onDismiss() else errorText = error
|
||||
}
|
||||
@@ -1029,7 +1031,7 @@ private fun isValidDashboardEditorAddress(address: String): Boolean {
|
||||
fun RouteEditorDialog(
|
||||
original: EndpointCandidate?,
|
||||
relayEnabled: Boolean = false,
|
||||
onSave: (role: String, dashboardUrl: String, onResult: (String?) -> Unit) -> Unit,
|
||||
onSave: (role: String, dashboardUrl: String, httpConsentOrigin: String?, onResult: (String?) -> Unit) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val uriHandler = LocalUriHandler.current
|
||||
@@ -1049,12 +1051,17 @@ fun RouteEditorDialog(
|
||||
)
|
||||
}
|
||||
var url by remember(original) { mutableStateOf(routeEditorInitialGatewayUrl(original)) }
|
||||
var httpConsentOrigin by remember(url, selectedRole) { mutableStateOf<String?>(null) }
|
||||
var errorText by remember { mutableStateOf<String?>(null) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
|
||||
val effectiveRole = if (selectedRole == CUSTOM_ROLE) customRole else selectedRole
|
||||
val normalizedAddress = Connection.normalizeDashboardUrlInput(url)
|
||||
val needsHttpConsent = com.hermesandroid.relay.data.dashboardHttpConsentRequired(normalizedAddress) ||
|
||||
(effectiveRole == "public" && com.hermesandroid.relay.data.dashboardHttpOrigin(normalizedAddress) != null)
|
||||
val saveEnabled = !saving &&
|
||||
url.isNotBlank() &&
|
||||
(!needsHttpConsent || httpConsentOrigin == com.hermesandroid.relay.data.dashboardHttpOrigin(normalizedAddress)) &&
|
||||
(selectedRole != CUSTOM_ROLE || customRole.isNotBlank())
|
||||
|
||||
AlertDialog(
|
||||
@@ -1066,7 +1073,7 @@ fun RouteEditorDialog(
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.endpoints_route_editor_desc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -1154,6 +1161,10 @@ fun RouteEditorDialog(
|
||||
previewCandidate?.let { candidate ->
|
||||
RouteSurfaceMap(candidate = candidate)
|
||||
}
|
||||
DashboardHttpConsentControl(
|
||||
normalizedAddress, httpConsentOrigin, { httpConsentOrigin = it },
|
||||
enabled = !saving, required = needsHttpConsent,
|
||||
)
|
||||
if (selectedRole == "tailscale") {
|
||||
Text(
|
||||
text = stringResource(R.string.endpoints_tailscale_setup_hint),
|
||||
@@ -1173,7 +1184,7 @@ fun RouteEditorDialog(
|
||||
enabled = saveEnabled,
|
||||
onClick = {
|
||||
saving = true
|
||||
onSave(effectiveRole, url) { error ->
|
||||
onSave(effectiveRole, url, httpConsentOrigin) { error ->
|
||||
saving = false
|
||||
if (error == null) {
|
||||
onDismiss()
|
||||
|
||||
@@ -60,7 +60,9 @@ import com.hermesandroid.relay.ui.theme.appearanceTopRoundedCornerShape
|
||||
@Composable
|
||||
fun ModelPickerSheet(
|
||||
options: List<ChatInputPickerOption>,
|
||||
loading: Boolean = false,
|
||||
refreshing: Boolean = false,
|
||||
error: String? = null,
|
||||
onRefresh: (() -> Unit)? = null,
|
||||
onSelect: (ChatInputPickerOption) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
@@ -210,11 +212,28 @@ fun ModelPickerSheet(
|
||||
.padding(32.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.model_picker_empty),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
when {
|
||||
modelOptions.isEmpty() && loading -> Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(stringResource(R.string.dashboard_loading_provider_catalog))
|
||||
}
|
||||
modelOptions.isEmpty() && error != null -> Text(
|
||||
text = stringResource(R.string.dashboard_model_options_load_failed),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
else -> Text(
|
||||
text = stringResource(
|
||||
if (modelOptions.isEmpty()) R.string.model_picker_no_models
|
||||
else R.string.model_picker_empty,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,9 +46,8 @@ fun RelayStatusStrip(
|
||||
/** Optional security marker rendered just before the route label. */
|
||||
securityGlyph: (@Composable () -> Unit)? = null,
|
||||
/**
|
||||
* 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.
|
||||
* When true, the strip shows the active chat connection's pending state
|
||||
* instead of its route label. Optional Relay availability is independent.
|
||||
*/
|
||||
reconnecting: Boolean = false,
|
||||
maxContentWidth: Dp? = null,
|
||||
@@ -120,7 +119,7 @@ fun RelayStatusStrip(
|
||||
}
|
||||
|
||||
/**
|
||||
* Amber "Relay reconnecting" cue with a softly pulsing dot. This is the *only*
|
||||
* Amber connection-progress 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
|
||||
@@ -144,7 +143,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
|
||||
.background(RelayRefresh.Amber),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.settings_relay_reconnecting),
|
||||
text = stringResource(R.string.session_path_connecting),
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Amber,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -30,6 +30,7 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -63,7 +64,7 @@ fun OnboardingPage(
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(210.dp),
|
||||
.height(if (LocalConfiguration.current.screenHeightDp < 620 || LocalConfiguration.current.fontScale > 1.2f) 96.dp else 150.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
heroContent()
|
||||
@@ -129,7 +130,7 @@ private fun FeatureHero(
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = title,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(46.dp),
|
||||
tint = Color(0xFF7B55F6),
|
||||
)
|
||||
|
||||
@@ -15,9 +15,11 @@ 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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
@@ -207,7 +209,7 @@ fun OnboardingScreen(
|
||||
)
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Column(modifier = Modifier.fillMaxSize().safeDrawingPadding()) {
|
||||
val currentPage = pagerState.currentPage
|
||||
val currentPageType = pages[currentPage]
|
||||
|
||||
@@ -221,7 +223,6 @@ fun OnboardingScreen(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.statusBarsPadding()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -363,7 +364,6 @@ private fun GradientOnboardingButton(
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.clickable(onClick = onClick),
|
||||
color = Color.Transparent,
|
||||
@@ -371,13 +371,14 @@ private fun GradientOnboardingButton(
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 52.dp)
|
||||
.background(
|
||||
Brush.horizontalGradient(
|
||||
listOf(Color(0xFF7047F5), Color(0xFF6446F0)),
|
||||
),
|
||||
)
|
||||
.padding(horizontal = 22.dp),
|
||||
.padding(horizontal = 22.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
@@ -431,6 +432,9 @@ private fun SegmentedOnboardingProgress(
|
||||
|
||||
@Composable
|
||||
private fun WelcomePage() {
|
||||
val configuration = LocalConfiguration.current
|
||||
val heroHeight = (configuration.screenHeightDp * if (configuration.fontScale > 1.2f) 0.18f else 0.27f)
|
||||
.coerceIn(80f, 240f).dp
|
||||
val titleParts = stringResource(R.string.onboarding_welcome_title).split("\n", limit = 2)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -442,15 +446,15 @@ private fun WelcomePage() {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(380.dp),
|
||||
.height(heroHeight),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.onboarding_hero_option1),
|
||||
contentDescription = stringResource(R.string.onboarding_hermes_logo),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = BiasAlignment(horizontalBias = 0f, verticalBias = -0.5f),
|
||||
contentScale = ContentScale.Fit,
|
||||
alignment = Alignment.Center,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1119,7 +1119,9 @@ fun ChatScreen(
|
||||
val serverModelName by chatViewModel.serverModelName.collectAsState()
|
||||
val apiModelOptions by chatViewModel.apiModelOptions.collectAsState()
|
||||
val modelProviders by chatViewModel.modelProviders.collectAsState()
|
||||
val modelOptionsLoading by chatViewModel.modelOptionsLoading.collectAsState()
|
||||
val modelOptionsRefreshing by chatViewModel.modelOptionsRefreshing.collectAsState()
|
||||
val modelOptionsError by chatViewModel.modelOptionsError.collectAsState()
|
||||
val modelSelectionConfirmation by chatViewModel.modelSelectionConfirmation.collectAsState()
|
||||
val reasoningCapabilityRevision by chatViewModel.reasoningCapabilityRevision.collectAsState()
|
||||
val selectedModelOverride by chatViewModel.selectedModelOverride.collectAsState()
|
||||
@@ -1220,6 +1222,7 @@ fun ChatScreen(
|
||||
chatGatewayAvailability == GatewayAvailability.SignInRequired && !apiReachable
|
||||
val isGatewayTransport = remember(
|
||||
streamingEndpointPref, chatServerCapabilities, chatGatewayAvailability,
|
||||
activeConnection,
|
||||
) {
|
||||
connectionViewModel.resolveStreamingEndpoint(streamingEndpointPref) == "gateway"
|
||||
}
|
||||
@@ -1453,6 +1456,11 @@ fun ChatScreen(
|
||||
composerDraftKey.sessionId,
|
||||
) { mutableStateOf<Int?>(null) }
|
||||
var showModelSheet by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(showModelSheet, isGatewayTransport, currentSessionId, selectedProfile?.name, activeConnection?.id) {
|
||||
if (showModelSheet && isGatewayTransport) {
|
||||
chatViewModel.refreshModelOptions(catalogOnly = true)
|
||||
}
|
||||
}
|
||||
var showEffortSheet by remember { mutableStateOf(false) }
|
||||
var showAgentInfo by remember { mutableStateOf(false) }
|
||||
var showProfileShelf by remember { mutableStateOf(false) }
|
||||
@@ -3331,6 +3339,9 @@ fun ChatScreen(
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier
|
||||
.then(if (targetConnectState == ChatConnectState.NeedsConnection) {
|
||||
Modifier.verticalScroll(rememberScrollState())
|
||||
} else Modifier)
|
||||
.padding(horizontal = 32.dp)
|
||||
.then(
|
||||
responsiveLayout.introMaxWidth?.let {
|
||||
@@ -3345,7 +3356,9 @@ fun ChatScreen(
|
||||
LocalBackgroundVisualizationEnabled.current &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||
) {
|
||||
val avatarModifier = responsiveLayout.avatarSize?.let { size ->
|
||||
val avatarModifier = if (targetConnectState == ChatConnectState.NeedsConnection) {
|
||||
Modifier.size(80.dp).clipToBounds()
|
||||
} else responsiveLayout.avatarSize?.let { size ->
|
||||
Modifier
|
||||
.size(size)
|
||||
.clipToBounds()
|
||||
@@ -4332,8 +4345,9 @@ fun ChatScreen(
|
||||
fallbackModelDetail,
|
||||
serverDefaultModelDetail,
|
||||
hasModelChoices,
|
||||
isGatewayTransport,
|
||||
) {
|
||||
if (!hasModelChoices && fallbackModelDetail.isNullOrBlank()) {
|
||||
if (!isGatewayTransport && !hasModelChoices && fallbackModelDetail.isNullOrBlank()) {
|
||||
emptyList()
|
||||
} else {
|
||||
buildList {
|
||||
@@ -4406,7 +4420,7 @@ fun ChatScreen(
|
||||
value = compactModelChipLabel(currentModelForInput, modelDefaultLabel),
|
||||
contentDescription = stringResource(R.string.cd_select_model),
|
||||
options = it,
|
||||
enabled = chatReady && !isStreaming && it.size > 1,
|
||||
enabled = chatReady && !isStreaming && (isGatewayTransport || it.size > 1),
|
||||
)
|
||||
}
|
||||
val normalizedEffort = normalizeReasoningEffortForInput(selectedReasoningEffort)
|
||||
@@ -4772,7 +4786,9 @@ fun ChatScreen(
|
||||
if (showModelSheet) {
|
||||
ModelPickerSheet(
|
||||
options = modelPickerOptions,
|
||||
loading = modelOptionsLoading,
|
||||
refreshing = modelOptionsRefreshing,
|
||||
error = modelOptionsError,
|
||||
onRefresh = {
|
||||
chatViewModel.refreshModelOptions(refresh = true, catalogOnly = true)
|
||||
},
|
||||
|
||||
@@ -41,7 +41,7 @@ import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.TabRow
|
||||
import androidx.compose.material3.ScrollableTabRow
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
@@ -265,7 +265,7 @@ fun ConnectionDetailScreen(
|
||||
.padding(innerPadding),
|
||||
) {
|
||||
if (tabs.size > 1) {
|
||||
TabRow(selectedTabIndex = safeIndex) {
|
||||
ScrollableTabRow(selectedTabIndex = safeIndex, edgePadding = 0.dp) {
|
||||
tabs.forEachIndexed { index, tab ->
|
||||
Tab(
|
||||
selected = safeIndex == index,
|
||||
@@ -276,7 +276,7 @@ fun ConnectionDetailScreen(
|
||||
DetailTab.Routes -> stringResource(R.string.detail_tab_routes)
|
||||
DetailTab.Access -> stringResource(R.string.detail_tab_access)
|
||||
DetailTab.Advanced -> stringResource(R.string.detail_tab_advanced)
|
||||
})
|
||||
}, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -380,8 +380,8 @@ fun ConnectionDetailScreen(
|
||||
if (showDashboardEditor) {
|
||||
DashboardAddressEditorDialog(
|
||||
initialUrl = connection.resolvedDashboardUrl,
|
||||
onSave = { dashboardUrl, onResult ->
|
||||
connectionViewModel.updateDashboardAddress(dashboardUrl, onResult)
|
||||
onSave = { dashboardUrl, httpConsentOrigin, onResult ->
|
||||
connectionViewModel.updateDashboardAddress(dashboardUrl, httpConsentOrigin, onResult)
|
||||
},
|
||||
onDismiss = { showDashboardEditor = false },
|
||||
)
|
||||
|
||||
+28
-18
@@ -53,6 +53,7 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
@@ -419,6 +420,29 @@ private fun ConnectionListCard(
|
||||
label = "connectionCardBorder",
|
||||
)
|
||||
|
||||
val configuration = LocalConfiguration.current
|
||||
val stackActions = configuration.screenWidthDp < 360 || configuration.fontScale > 1.2f
|
||||
val showSwitch = onSwitch != null || isSwitching || justSwitched
|
||||
val switchAction: @Composable (Modifier) -> Unit = { actionModifier ->
|
||||
OutlinedButton(
|
||||
modifier = actionModifier,
|
||||
onClick = { onSwitch?.invoke() },
|
||||
enabled = !isSwitching && !justSwitched,
|
||||
) {
|
||||
when {
|
||||
isSwitching -> {
|
||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Text(stringResource(R.string.conn_switching), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
justSwitched -> {
|
||||
Icon(Icons.Filled.CheckCircle, contentDescription = null, modifier = Modifier.size(16.dp))
|
||||
Text(stringResource(R.string.conn_switched), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
else -> Text(stringResource(R.string.conn_switch))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -500,30 +524,16 @@ private fun ConnectionListCard(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onSwitch != null || isSwitching || justSwitched) {
|
||||
OutlinedButton(
|
||||
onClick = { onSwitch?.invoke() },
|
||||
enabled = !isSwitching && !justSwitched,
|
||||
) {
|
||||
when {
|
||||
isSwitching -> {
|
||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Text(stringResource(R.string.conn_switching), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
justSwitched -> {
|
||||
Icon(Icons.Filled.CheckCircle, contentDescription = null, modifier = Modifier.size(16.dp))
|
||||
Text(stringResource(R.string.conn_switched), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
else -> Text(stringResource(R.string.conn_switch))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (showSwitch && !stackActions) switchAction(Modifier)
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (showSwitch && stackActions) {
|
||||
switchAction(Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -317,7 +317,7 @@ fun DashboardSignInScreen(
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
?: status.authProviderDetails
|
||||
authFlows = status.authFlows
|
||||
var session = if (status.authRequired) client.currentSession().getOrNull() else null
|
||||
var session = client.currentSession().getOrNull()
|
||||
var ticketAvailable = if (session?.authenticated == true) {
|
||||
client.requestWsTicket().isSuccess
|
||||
} else {
|
||||
@@ -359,10 +359,12 @@ fun DashboardSignInScreen(
|
||||
gatewayTicketAvailable = ticketAvailable,
|
||||
)
|
||||
if (
|
||||
!status.authRequired ||
|
||||
session?.let { dashboardAuthenticationReady(it, ticketAvailable) } == true
|
||||
) {
|
||||
finishAuthentication()
|
||||
} else if (!status.authRequired) {
|
||||
actionMessage = resources.getString(R.string.dashboard_local_auth_help)
|
||||
actionIsError = true
|
||||
}
|
||||
} finally {
|
||||
loading = false
|
||||
@@ -435,11 +437,6 @@ fun DashboardSignInScreen(
|
||||
oauthProvider = provider
|
||||
return
|
||||
}
|
||||
if (!isNativeDashboardTransportEligible(dashboardUrl)) {
|
||||
embeddedFallbackFromNative = true
|
||||
oauthProvider = provider
|
||||
return
|
||||
}
|
||||
val authClient = connectionViewModel.nativeDashboardAuthClientForActive(dashboardUrl)
|
||||
if (authClient == null) {
|
||||
embeddedFallbackFromNative = true
|
||||
|
||||
@@ -642,6 +642,7 @@ private fun ProviderUsageDisplaySettings(
|
||||
"openai-codex" to "Codex",
|
||||
"nous" to "Nous",
|
||||
"opencode-go" to "OpenCode Go",
|
||||
"supergrok" to "SuperGrok",
|
||||
)
|
||||
} else {
|
||||
providers.map { it.id to it.displayName }
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.hermesandroid.relay.ui.theme
|
||||
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import com.hermesandroid.relay.data.AppearancePreferences
|
||||
import com.hermesandroid.relay.data.CustomThemePreset
|
||||
import com.hermesandroid.relay.data.PersistedAppearance
|
||||
|
||||
/**
|
||||
* Maps the persisted appearance preference onto AppCompat's night mode.
|
||||
*
|
||||
* Compose paints its own palette, while the activity and platform surfaces use
|
||||
* Theme.AppCompat.DayNight. Both resolve from the same saved appearance.
|
||||
*/
|
||||
internal object AppearanceNightMode {
|
||||
private val VALID_PREFERENCES = setOf("auto", "light", "dark")
|
||||
|
||||
fun normalizePreference(raw: String?): String =
|
||||
raw?.takeIf { it in VALID_PREFERENCES } ?: "auto"
|
||||
|
||||
fun nightModeFor(
|
||||
themePreference: String,
|
||||
themeMode: ThemeMode,
|
||||
customTheme: CustomThemePreset? = null,
|
||||
): Int {
|
||||
customTheme?.let { preset ->
|
||||
return if (preset.isDark) {
|
||||
AppCompatDelegate.MODE_NIGHT_YES
|
||||
} else {
|
||||
AppCompatDelegate.MODE_NIGHT_NO
|
||||
}
|
||||
}
|
||||
return when (themeMode) {
|
||||
ThemeMode.DARK_ONLY -> AppCompatDelegate.MODE_NIGHT_YES
|
||||
ThemeMode.LIGHT_ONLY -> AppCompatDelegate.MODE_NIGHT_NO
|
||||
ThemeMode.BOTH -> when (normalizePreference(themePreference)) {
|
||||
"light" -> AppCompatDelegate.MODE_NIGHT_NO
|
||||
"dark" -> AppCompatDelegate.MODE_NIGHT_YES
|
||||
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun nightModeFor(appearance: PersistedAppearance): Int {
|
||||
val appTheme = appearance.customTheme?.toAppTheme() ?: AppThemes.byId(appearance.appThemeId)
|
||||
return nightModeFor(
|
||||
themePreference = appearance.customTheme?.mode ?: appearance.themePreference,
|
||||
themeMode = appTheme.mode,
|
||||
customTheme = appearance.customTheme,
|
||||
)
|
||||
}
|
||||
|
||||
fun nightModeFor(preferences: Preferences): Int =
|
||||
nightModeFor(AppearancePreferences.decode(preferences))
|
||||
|
||||
/** Apply only when the mode actually changes — avoids redundant uiMode churn. */
|
||||
fun apply(nightMode: Int) {
|
||||
try {
|
||||
if (AppCompatDelegate.getDefaultNightMode() != nightMode) {
|
||||
AppCompatDelegate.setDefaultNightMode(nightMode)
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// Robolectric / headless hosts may not support night-mode switches.
|
||||
}
|
||||
}
|
||||
|
||||
fun applyFromPreferences(preferences: Preferences) {
|
||||
apply(nightModeFor(preferences))
|
||||
}
|
||||
|
||||
fun applyFromAppearance(appearance: PersistedAppearance) {
|
||||
apply(nightModeFor(appearance))
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.ui.theme
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -10,7 +11,9 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.core.view.WindowCompat
|
||||
import com.hermesandroid.relay.data.AppearancePreferences
|
||||
import com.hermesandroid.relay.data.CustomThemePreset
|
||||
import com.hermesandroid.relay.data.PersistedAppearance
|
||||
@@ -63,9 +66,22 @@ fun HermesRelayTheme(
|
||||
// call sites observe the active palette. SideEffect runs post-composition,
|
||||
// avoiding a state-write-during-composition; the default theme matches the
|
||||
// façade's initial value, so the common path has no first-frame flash.
|
||||
//
|
||||
// Match system-bar icon contrast to the palette in this window. AppCompat
|
||||
// night mode follows persisted Appearance independently of composable
|
||||
// previews and temporary supervised/loading palettes.
|
||||
val view = LocalView.current
|
||||
SideEffect {
|
||||
RelayRefresh.activePalette = palette
|
||||
RelayRefresh.activeShapeScale = shapeScale
|
||||
if (!view.isInEditMode) {
|
||||
val activity = view.context as? Activity
|
||||
if (activity != null) {
|
||||
val controller = WindowCompat.getInsetsController(activity.window, view)
|
||||
controller.isAppearanceLightStatusBars = !useDarkTheme
|
||||
controller.isAppearanceLightNavigationBars = !useDarkTheme
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(
|
||||
|
||||
@@ -780,6 +780,9 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
/** Callback to persist session ID — set by RelayApp */
|
||||
var onSessionChanged: ((String?) -> Unit)? = null
|
||||
|
||||
/** Capture a voice-session receipt at live admission, never during history replay. */
|
||||
internal var gatewayInboundSpeechReceiver: (() -> ((String) -> Unit)?)? = null
|
||||
var onFreshDraftSelected: ((String?, SessionTransport) -> Unit)? = null
|
||||
|
||||
/**
|
||||
@@ -1124,6 +1127,9 @@ class ChatViewModel : ViewModel() {
|
||||
modelSelectionRevision.incrementAndGet()
|
||||
_modelSelectionConfirmation.value = null
|
||||
modelOptionsGeneration.incrementAndGet()
|
||||
_modelOptionsLoading.value = false
|
||||
_modelOptionsRefreshing.value = false
|
||||
_modelOptionsError.value = null
|
||||
val cached = modelOptionsByProfile[profileKey]
|
||||
_modelProviders.value = cached?.providers.orEmpty()
|
||||
relayCapabilityGeneration.incrementAndGet()
|
||||
@@ -1141,6 +1147,10 @@ class ChatViewModel : ViewModel() {
|
||||
/** True only during an explicit user-requested dynamic model catalog refresh. */
|
||||
private val _modelOptionsRefreshing = MutableStateFlow(false)
|
||||
val modelOptionsRefreshing: StateFlow<Boolean> = _modelOptionsRefreshing.asStateFlow()
|
||||
private val _modelOptionsLoading = MutableStateFlow(false)
|
||||
val modelOptionsLoading: StateFlow<Boolean> = _modelOptionsLoading.asStateFlow()
|
||||
private val _modelOptionsError = MutableStateFlow<String?>(null)
|
||||
val modelOptionsError: StateFlow<String?> = _modelOptionsError.asStateFlow()
|
||||
|
||||
/** Current gateway model from `model.options`, used when no Android override is active. */
|
||||
private val _gatewayCurrentModel = MutableStateFlow("")
|
||||
@@ -1228,16 +1238,20 @@ class ChatViewModel : ViewModel() {
|
||||
val gateway = gatewayClient ?: run {
|
||||
android.util.Log.i("ChatViewModel", "refreshModelOptions: no gateway client")
|
||||
if (refresh) _modelOptionsRefreshing.value = false
|
||||
_modelOptionsLoading.value = false
|
||||
_modelOptionsError.value = "Gateway unavailable."
|
||||
return
|
||||
}
|
||||
if (refresh && _modelOptionsRefreshing.value) return
|
||||
if (_modelOptionsRefreshing.value) return
|
||||
if (refresh) _modelOptionsRefreshing.value = true
|
||||
_modelOptionsLoading.value = true
|
||||
_modelOptionsError.value = null
|
||||
val generation = modelOptionsGeneration.incrementAndGet()
|
||||
val profileKey = modelOptionsProfileKey()
|
||||
viewModelScope.launch {
|
||||
gateway.modelOptions(refresh = refresh).fold(
|
||||
onSuccess = {
|
||||
if (!isCurrentModelOptionsResponse(
|
||||
if (gatewayClient !== gateway || !isCurrentModelOptionsResponse(
|
||||
generation,
|
||||
modelOptionsGeneration.get(),
|
||||
profileKey,
|
||||
@@ -1270,12 +1284,22 @@ class ChatViewModel : ViewModel() {
|
||||
},
|
||||
onFailure = {
|
||||
android.util.Log.w("ChatViewModel", "model.options failed: ${it.message}")
|
||||
if (refresh) {
|
||||
_transientNotice.tryEmit("Couldn't refresh models: ${it.message ?: "unknown error"}")
|
||||
if (gatewayClient === gateway && isCurrentModelOptionsResponse(
|
||||
generation, modelOptionsGeneration.get(),
|
||||
profileKey, modelOptionsProfileKey(),
|
||||
)
|
||||
) {
|
||||
_modelOptionsError.value = it.message ?: "Model catalog unavailable."
|
||||
if (refresh) {
|
||||
_transientNotice.tryEmit("Couldn't refresh models: ${it.message ?: "unknown error"}")
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
if (refresh) _modelOptionsRefreshing.value = false
|
||||
if (gatewayClient === gateway && generation == modelOptionsGeneration.get()) {
|
||||
_modelOptionsLoading.value = false
|
||||
if (refresh) _modelOptionsRefreshing.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1510,6 +1534,9 @@ class ChatViewModel : ViewModel() {
|
||||
) {
|
||||
val client = apiClient ?: return
|
||||
val generation = modelOptionsGeneration.incrementAndGet()
|
||||
_modelOptionsLoading.value = false
|
||||
_modelOptionsRefreshing.value = false
|
||||
_modelOptionsError.value = null
|
||||
val profileKey = modelOptionsProfileKey()
|
||||
viewModelScope.launch {
|
||||
val providerResult = client.getProviderModelOptions()
|
||||
@@ -2119,6 +2146,9 @@ class ChatViewModel : ViewModel() {
|
||||
// what the agent actually runs. The next session.create then binds the
|
||||
// profile's own model.
|
||||
modelOptionsGeneration.incrementAndGet()
|
||||
_modelOptionsLoading.value = false
|
||||
_modelOptionsRefreshing.value = false
|
||||
_modelOptionsError.value = null
|
||||
_modelProviders.value = emptyList()
|
||||
_apiModelOptions.value = emptyList()
|
||||
_availableModels.value = emptyList()
|
||||
@@ -2729,6 +2759,10 @@ class ChatViewModel : ViewModel() {
|
||||
val previousClient = gatewayClient
|
||||
val changed = previousClient !== client
|
||||
if (changed) {
|
||||
modelOptionsGeneration.incrementAndGet()
|
||||
_modelOptionsLoading.value = false
|
||||
_modelOptionsRefreshing.value = false
|
||||
_modelOptionsError.value = null
|
||||
clearProjectedBackgroundProcesses()
|
||||
sessionActivityPollJob?.cancel()
|
||||
sessionActivityPollJob = null
|
||||
@@ -3070,6 +3104,7 @@ class ChatViewModel : ViewModel() {
|
||||
var boundHandle: ActiveTurnHandle? = null
|
||||
var inputTokens: Int? = null
|
||||
var outputTokens: Int? = null
|
||||
var speechReceiver: ((String) -> Unit)? = null
|
||||
|
||||
fun ownsTranscriptSession(): Boolean =
|
||||
chatHandler === handler && handler.currentSessionId.value == storedSessionId
|
||||
@@ -3148,9 +3183,9 @@ class ChatViewModel : ViewModel() {
|
||||
onTurnComplete = {
|
||||
if (acceptsEvent()) handler.onTurnComplete(messageId)
|
||||
},
|
||||
// Server-initiated turns already take the bounded durable-history
|
||||
// reconcile below on every completion.
|
||||
onReconcileRequired = { },
|
||||
// Recovery can settle a partial live bubble before durable history
|
||||
// arrives. That history repairs Chat, but is not a speech receipt.
|
||||
onReconcileRequired = { speechReceiver = null },
|
||||
onComplete = {
|
||||
val canWriteTranscript = acceptsEvent()
|
||||
val expectedText = handler.messages.value
|
||||
@@ -3168,7 +3203,9 @@ class ChatViewModel : ViewModel() {
|
||||
} else {
|
||||
finalizeTurnSideEffects(handler, messageId)
|
||||
AppAnalytics.onStreamComplete(inputTokens, outputTokens)
|
||||
speechReceiver?.invoke(expectedText.orEmpty())
|
||||
}
|
||||
speechReceiver = null
|
||||
scheduleGatewayHistoryReconcile(
|
||||
storedSessionId = storedSessionId,
|
||||
expectedAssistantText = expectedText,
|
||||
@@ -3271,6 +3308,9 @@ class ChatViewModel : ViewModel() {
|
||||
baselineAssistantCount = handler.messages.value.count {
|
||||
it.role == MessageRole.ASSISTANT && !it.clientOnly
|
||||
}
|
||||
if (queuedRecovery == null) {
|
||||
speechReceiver = gatewayInboundSpeechReceiver?.invoke()
|
||||
}
|
||||
boundHandle = handle
|
||||
accepted = true
|
||||
activeStream = handle
|
||||
@@ -5411,6 +5451,9 @@ class ChatViewModel : ViewModel() {
|
||||
/** Clear server-owned catalogs before a different connection starts loading. */
|
||||
fun resetConnectionCatalogs() {
|
||||
modelOptionsGeneration.incrementAndGet()
|
||||
_modelOptionsLoading.value = false
|
||||
_modelOptionsRefreshing.value = false
|
||||
_modelOptionsError.value = null
|
||||
modelOptionsByProfile.clear()
|
||||
apiSessionModelLocks.clear()
|
||||
_availableSkills.value = emptyList()
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.hermesandroid.relay.auth.AuthManager
|
||||
import com.hermesandroid.relay.auth.AuthState
|
||||
import com.hermesandroid.relay.ui.theme.AppFont
|
||||
import com.hermesandroid.relay.ui.theme.AppThemes
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceNightMode
|
||||
import com.hermesandroid.relay.ui.theme.normalizeAccentHex
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceShape
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetImporter
|
||||
@@ -31,6 +32,7 @@ import com.hermesandroid.relay.auth.PairedDeviceInfo
|
||||
import com.hermesandroid.relay.auth.PairedSession
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.AppearancePreferences
|
||||
import com.hermesandroid.relay.data.PersistedAppearance
|
||||
import com.hermesandroid.relay.data.CustomThemePreset
|
||||
import com.hermesandroid.relay.data.DataManager
|
||||
import com.hermesandroid.relay.data.DemoContent
|
||||
@@ -64,6 +66,10 @@ import com.hermesandroid.relay.data.LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE
|
||||
import com.hermesandroid.relay.data.ConnectionValidation
|
||||
import com.hermesandroid.relay.data.computeConnectionSecurity
|
||||
import com.hermesandroid.relay.data.normalizeCredentialFreeAuthenticatedDashboardOrigin
|
||||
import com.hermesandroid.relay.data.dashboardHttpConsentMatches
|
||||
import com.hermesandroid.relay.data.dashboardHttpOrigin
|
||||
import com.hermesandroid.relay.data.updatedDashboardHttpConsents
|
||||
import com.hermesandroid.relay.network.upstream.verifySetup
|
||||
import com.hermesandroid.relay.data.BuildFlavor
|
||||
import com.hermesandroid.relay.data.BotChatTarget
|
||||
import com.hermesandroid.relay.data.BotModeState
|
||||
@@ -515,7 +521,7 @@ internal fun resolveEffectiveDashboardUrl(
|
||||
): String {
|
||||
if (connection == null) return ""
|
||||
connection.authenticatedDashboardOrigin
|
||||
?.let(::normalizeCredentialFreeAuthenticatedDashboardOrigin)
|
||||
?.let { normalizeCredentialFreeAuthenticatedDashboardOrigin(it, connection.dashboardHttpConsentOrigins) }
|
||||
?.let { return it }
|
||||
// The resolver publishes independently of the active connection. During a
|
||||
// switch its last winner can still belong to the outgoing installation.
|
||||
@@ -571,12 +577,14 @@ internal fun normalizeDashboardAddressForEdit(raw: String): String? {
|
||||
internal fun publicDashboardAddressRequiresHttps(
|
||||
role: String?,
|
||||
normalizedAddress: String,
|
||||
httpConsentOrigins: Set<String> = emptySet(),
|
||||
): Boolean {
|
||||
val uri = runCatching { URI(normalizedAddress) }.getOrNull() ?: return false
|
||||
val explicitRole = role?.trim()?.lowercase()?.takeIf { it.isNotBlank() }
|
||||
val inferredRole = Connection.inferRouteRole(normalizedAddress)
|
||||
return uri.scheme.equals("http", ignoreCase = true) &&
|
||||
(explicitRole == "public" || inferredRole == "public")
|
||||
(explicitRole == "public" || inferredRole == "public") &&
|
||||
!dashboardHttpConsentMatches(normalizedAddress, httpConsentOrigins)
|
||||
}
|
||||
|
||||
internal fun standardApiDashboardSecurityError(
|
||||
@@ -596,6 +604,7 @@ internal data class PendingConnectionDraft(
|
||||
val previousConnectionId: String?,
|
||||
var pairingPayload: com.hermesandroid.relay.ui.components.HermesPairingPayload? = null,
|
||||
var label: String? = null,
|
||||
val dashboardHttpConsentOrigins: Set<String> = emptySet(),
|
||||
)
|
||||
|
||||
/** Hide user-confirmed removals immediately while serialized cleanup finishes. */
|
||||
@@ -1178,9 +1187,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private val endpointResolver = EndpointResolver(
|
||||
httpClient = endpointProbeClient,
|
||||
clientForCandidate = { candidate ->
|
||||
candidate.pluginProxyRoutesOrNull()?.let { proxy ->
|
||||
val tokenProvider = { (authManager.authState.value as? AuthState.Paired)?.token }
|
||||
clientForCandidate = { candidate, probeRequestUrl ->
|
||||
val tokenProvider = { (authManager.authState.value as? AuthState.Paired)?.token }
|
||||
candidate.pluginProxyRoutesOrNull()?.takeIf { proxy ->
|
||||
proxy.authority.equals(
|
||||
probeRequestUrl?.let(com.hermesandroid.relay.auth.CertPinStore::hostPortFromUrl),
|
||||
ignoreCase = true,
|
||||
)
|
||||
}?.let { proxy ->
|
||||
if (candidate.hermesReachRouteOrNull() != null) {
|
||||
buildHermesReachClient(
|
||||
baseBuilder = endpointProbeClient.newBuilder(),
|
||||
@@ -1195,6 +1209,28 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
sessionTokenProvider = tokenProvider,
|
||||
)
|
||||
}
|
||||
} ?: run {
|
||||
// LAN sometimes stores Secure Link relay URL (wss://…:9443/…).
|
||||
// Pin ONLY when this probe actually hits that authority —
|
||||
// not for plain dashboard :9119 / API :8642 on the same
|
||||
// candidate (pin client's authority guard → IOException).
|
||||
val requestUrl = probeRequestUrl?.trim().orEmpty()
|
||||
if (requestUrl.isBlank()) return@run null
|
||||
val targetAuthority = com.hermesandroid.relay.auth.CertPinStore
|
||||
.hostPortFromUrl(requestUrl)
|
||||
?: return@run null
|
||||
activeConnection.value?.routeCandidates.orEmpty()
|
||||
.mapNotNull { it.pluginProxyRoutesOrNull() }
|
||||
.firstOrNull { routes ->
|
||||
routes.authority.equals(targetAuthority, ignoreCase = true)
|
||||
}
|
||||
?.let { routes ->
|
||||
buildPluginProxyClient(
|
||||
baseBuilder = endpointProbeClient.newBuilder(),
|
||||
routes = routes,
|
||||
sessionTokenProvider = tokenProvider,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
context = application,
|
||||
@@ -1285,6 +1321,15 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
(authManager.authState.value as? AuthState.Paired)?.token
|
||||
},
|
||||
dashboardHttpClientProvider = ::dashboardHttpClientForRelayIngress,
|
||||
// Secure Link relay HTTP must use the same pin TrustManager as WSS;
|
||||
// default OkHttp only has the system CA store and rejects the leaf.
|
||||
pluginProxyHttpClientProvider = { url ->
|
||||
pluginProxyClientForUrl(
|
||||
url = url,
|
||||
baseClient = relayOkHttp,
|
||||
includeRelaySessionHeader = false,
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
// Pairing-management collaborator — owns the paired-devices list
|
||||
@@ -1331,6 +1376,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
?: connection?.dashboardAuthProviders.orEmpty(),
|
||||
)
|
||||
},
|
||||
dashboardHttpConsentOriginsProvider = { cid -> dashboardHttpConsentsFor(cid) },
|
||||
pinnedClientProvider = { url, base ->
|
||||
pluginProxyClientForUrl(url, base, includeRelaySessionHeader = false)
|
||||
},
|
||||
@@ -1553,7 +1599,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
?: connectionManager.activeRelayEndpoint.value?.relay?.url
|
||||
?: autoRelayUrlSnapshot()
|
||||
|
||||
private fun pluginProxyClientForUrl(
|
||||
internal fun pluginProxyClientForUrl(
|
||||
url: String,
|
||||
baseClient: OkHttpClient? = null,
|
||||
includeRelaySessionHeader: Boolean = true,
|
||||
@@ -1788,8 +1834,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
origin: String,
|
||||
allowMissingInstallIdentity: Boolean = false,
|
||||
): Boolean {
|
||||
val normalized = normalizeAuthenticatedDashboardOrigin(origin) ?: return false
|
||||
val activeId = connectionStore.activeConnectionId.value ?: return false
|
||||
val normalized = normalizeCredentialFreeAuthenticatedDashboardOrigin(
|
||||
origin, dashboardHttpConsentsFor(activeId),
|
||||
) ?: return false
|
||||
val previous = connectionStore.connections.value
|
||||
.firstOrNull { it.id == activeId }
|
||||
?: return false
|
||||
@@ -1808,7 +1856,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
withTimeoutOrNull(8_000L) {
|
||||
val status = verificationClient.getStatus().getOrNull() ?: return@withTimeoutOrNull false
|
||||
candidateInstallId = status.installId
|
||||
!status.authRequired || verificationClient.currentSession().getOrNull()?.authenticated == true
|
||||
verificationClient.currentSession().getOrNull()?.authenticated == true &&
|
||||
verificationClient.requestWsTicket().isSuccess
|
||||
} == true
|
||||
} finally {
|
||||
verificationClient.shutdown()
|
||||
@@ -1868,6 +1917,11 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
fun retireNativeDashboardAuthentication(connectionId: String) =
|
||||
upstreamTransport.retireNativeDashboardAuthentication(connectionId)
|
||||
|
||||
private fun dashboardHttpConsentsFor(connectionId: String): Set<String> =
|
||||
pendingConnectionDraft?.takeIf { it.id == connectionId }?.dashboardHttpConsentOrigins
|
||||
?: connectionStore.connections.value.firstOrNull { it.id == connectionId }
|
||||
?.dashboardHttpConsentOrigins.orEmpty()
|
||||
|
||||
fun nativeDashboardAuthClientForActive(dashboardUrl: String): NativeDashboardAuthClient? =
|
||||
upstreamTransport.nativeDashboardAuthClientForActive(dashboardUrl)
|
||||
|
||||
@@ -2148,10 +2202,16 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
@Deprecated("Use relayConnectionState", replaceWith = ReplaceWith("relayConnectionState"))
|
||||
val connectionState: StateFlow<ConnectionState> = relayConnectionState
|
||||
|
||||
// One snapshot from the DataStore emission that also releases splash
|
||||
// readiness. The app root must not compose a first frame from separately
|
||||
// hydrated theme, preset, font, and shape StateFlows.
|
||||
private val _appearance = MutableStateFlow(PersistedAppearance())
|
||||
internal val appearance: StateFlow<PersistedAppearance> = _appearance.asStateFlow()
|
||||
|
||||
// Theme preference — light/dark/auto mode axis.
|
||||
val theme: StateFlow<String> = application.relayDataStore.data
|
||||
.map { preferences ->
|
||||
preferences[AppearancePreferences.themeKey] ?: "auto"
|
||||
AppearanceNightMode.normalizePreference(preferences[AppearancePreferences.themeKey])
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
|
||||
@@ -2870,12 +2930,16 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
// this Home-Assistant-class persistent-connection use case). Mirrors
|
||||
// BridgeViewModel's masterToggle → BridgeForegroundService driver.
|
||||
viewModelScope.launch {
|
||||
combine(gatewayKeepAlive, ActiveTurnKeepAliveRegistry.snapshot) { persistent, turns ->
|
||||
persistent to turns
|
||||
}.distinctUntilChanged().collect { (persistent, turns) ->
|
||||
combine(
|
||||
gatewayKeepAlive,
|
||||
ActiveTurnKeepAliveRegistry.snapshot,
|
||||
AppForegroundTracker.isForeground,
|
||||
) { persistent, turns, foreground ->
|
||||
Triple(persistent, turns, foreground)
|
||||
}.distinctUntilChanged().collect { (persistent, turns, foreground) ->
|
||||
upstreamTransport.applyGatewayKeepAlive(persistent || turns.required)
|
||||
val ctx = getApplication<Application>()
|
||||
runCatching { GatewayKeepAliveService.update(ctx, persistent, turns) }
|
||||
GatewayKeepAliveService.update(ctx, persistent, turns, foreground)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5098,6 +5162,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
var prevApiKey: String? = null
|
||||
|
||||
application.relayDataStore.data.collect { preferences ->
|
||||
val persistedAppearance = AppearancePreferences.decode(preferences)
|
||||
_appearance.value = persistedAppearance
|
||||
AppearanceNightMode.applyFromAppearance(persistedAppearance)
|
||||
|
||||
// Restore insecure mode
|
||||
val insecure = preferences[KEY_INSECURE_MODE] ?: false
|
||||
connectionManager.setInsecureMode(insecure)
|
||||
@@ -6459,6 +6527,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
val signInRequired: Boolean = false,
|
||||
val authenticated: Boolean = false,
|
||||
val voiceAvailability: StandardVoiceAvailability = StandardVoiceAvailability.Unknown,
|
||||
val httpConsentOrigin: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -6468,9 +6537,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
*/
|
||||
fun probeHermesDashboard(
|
||||
address: String,
|
||||
httpConsentOrigin: String? = null,
|
||||
onResult: (DashboardSetupResult) -> Unit,
|
||||
) {
|
||||
val dashboardUrl = Connection.normalizeApiUrlInput(
|
||||
val dashboardUrl = Connection.normalizeDashboardUrlInput(
|
||||
address,
|
||||
defaultPort = Connection.DEFAULT_DASHBOARD_PORT,
|
||||
)
|
||||
@@ -6484,7 +6554,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
)
|
||||
return
|
||||
}
|
||||
if (publicDashboardAddressRequiresHttps(role = null, normalizedAddress = dashboardUrl)) {
|
||||
if (publicDashboardAddressRequiresHttps(null, dashboardUrl, setOfNotNull(httpConsentOrigin))) {
|
||||
onResult(
|
||||
DashboardSetupResult(
|
||||
ok = false,
|
||||
@@ -6495,27 +6565,11 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val client = upstreamTransport.dashboardClientForActive(dashboardUrl)
|
||||
val client = upstreamTransport.dashboardClientForActive(dashboardUrl, setupProbe = true)
|
||||
try {
|
||||
val statusResult = client.getStatus()
|
||||
val status = statusResult.getOrNull()
|
||||
if (status == null) {
|
||||
onResult(
|
||||
DashboardSetupResult(
|
||||
ok = false,
|
||||
dashboardUrl = dashboardUrl,
|
||||
message = statusResult.exceptionOrNull()?.message
|
||||
?: "Hermes was not found at this address",
|
||||
),
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
val session = if (status.authRequired) {
|
||||
client.currentSession().getOrNull()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val authenticated = !status.authRequired || session?.authenticated == true
|
||||
val verification = client.verifySetup()
|
||||
val status = verification.status
|
||||
val authenticated = verification.authenticated
|
||||
val voice = when {
|
||||
!authenticated -> StandardVoiceAvailability.SignInRequired
|
||||
client.audioRoutesPresent() -> StandardVoiceAvailability.Ready
|
||||
@@ -6526,9 +6580,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
ok = true,
|
||||
dashboardUrl = dashboardUrl,
|
||||
message = status.message ?: "Hermes is ready",
|
||||
signInRequired = status.authRequired && !authenticated,
|
||||
signInRequired = !authenticated,
|
||||
authenticated = authenticated,
|
||||
voiceAvailability = voice,
|
||||
httpConsentOrigin = httpConsentOrigin?.takeIf { it == dashboardHttpOrigin(dashboardUrl) },
|
||||
),
|
||||
)
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
@@ -6538,7 +6593,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
DashboardSetupResult(
|
||||
ok = false,
|
||||
dashboardUrl = dashboardUrl,
|
||||
message = e.message ?: "Hermes was not found at this address",
|
||||
message = if (e is com.hermesandroid.relay.network.upstream.DashboardLocalAuthenticationRequiredException) {
|
||||
getApplication<Application>().getString(R.string.dashboard_local_auth_help)
|
||||
} else e.message ?: "Hermes was not found at this address",
|
||||
),
|
||||
)
|
||||
} finally {
|
||||
@@ -6551,6 +6608,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
fun saveDashboardConnection(
|
||||
dashboardUrl: String,
|
||||
discoveredHostname: String? = null,
|
||||
httpConsentOrigin: String? = null,
|
||||
onComplete: (Result<Unit>) -> Unit,
|
||||
) {
|
||||
val normalized = Connection.normalizeDashboardUrlInput(
|
||||
@@ -6561,7 +6619,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
onComplete(Result.failure(IllegalArgumentException("Hermes address is required")))
|
||||
return
|
||||
}
|
||||
if (publicDashboardAddressRequiresHttps(role = null, normalizedAddress = normalized)) {
|
||||
if (publicDashboardAddressRequiresHttps(null, normalized, setOfNotNull(httpConsentOrigin))) {
|
||||
onComplete(Result.failure(IllegalArgumentException("Public Gateway addresses require HTTPS")))
|
||||
return
|
||||
}
|
||||
@@ -6573,7 +6631,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
draft = draft,
|
||||
dashboardUrl = normalized,
|
||||
discoveredHostname = discoveredHostname,
|
||||
)
|
||||
).copy(dashboardHttpConsentOrigins = updatedDashboardHttpConsents(
|
||||
draft.dashboardHttpConsentOrigins, null, normalized, httpConsentOrigin,
|
||||
))
|
||||
true
|
||||
}
|
||||
if (stagedDraft) return@runCatching
|
||||
@@ -6597,6 +6657,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
val next = current.copy(
|
||||
label = nextLabel,
|
||||
dashboardUrl = normalized,
|
||||
dashboardHttpConsentOrigins = updatedDashboardHttpConsents(
|
||||
current.dashboardHttpConsentOrigins, current.configuredDashboardUrl, normalized, httpConsentOrigin,
|
||||
),
|
||||
authenticatedDashboardOrigin = current.authenticatedDashboardOrigin
|
||||
?.takeIf {
|
||||
it.trimEnd('/').equals(normalized.trimEnd('/'), ignoreCase = true)
|
||||
@@ -6635,6 +6698,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
*/
|
||||
fun updateDashboardAddress(
|
||||
url: String,
|
||||
httpConsentOrigin: String? = null,
|
||||
onResult: (String?) -> Unit,
|
||||
) {
|
||||
val normalized = normalizeDashboardAddressForEdit(url)
|
||||
@@ -6642,7 +6706,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
onResult("Enter an http:// or https:// Hermes Dashboard address")
|
||||
return
|
||||
}
|
||||
if (publicDashboardAddressRequiresHttps(role = null, normalizedAddress = normalized)) {
|
||||
if (publicDashboardAddressRequiresHttps(null, normalized, setOfNotNull(httpConsentOrigin))) {
|
||||
onResult("Public Gateway addresses require HTTPS")
|
||||
return
|
||||
}
|
||||
@@ -6660,7 +6724,11 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
return@launch
|
||||
}
|
||||
val originChanged = !sameDashboardBase(current.resolvedDashboardUrl, normalized)
|
||||
val next = withExplicitDashboardAddress(current, normalized)
|
||||
val next = withExplicitDashboardAddress(current, normalized).copy(
|
||||
dashboardHttpConsentOrigins = updatedDashboardHttpConsents(
|
||||
current.dashboardHttpConsentOrigins, current.configuredDashboardUrl, normalized, httpConsentOrigin,
|
||||
),
|
||||
)
|
||||
connectionStore.updateConnection(next)
|
||||
if (originChanged) {
|
||||
withContext(Dispatchers.IO) {
|
||||
@@ -6747,6 +6815,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
tokenStoreKey = Connection.buildTokenStoreKey(connectionId),
|
||||
dashboardUrl = dashboardUrl,
|
||||
routeCandidates = routes,
|
||||
dashboardHttpConsentOrigins = draft.dashboardHttpConsentOrigins,
|
||||
pairedAt = paired?.let { System.currentTimeMillis() },
|
||||
transportHint = pairedSession?.transportHint,
|
||||
expiresAt = pairedSession?.expiresAt?.let { it * 1000L },
|
||||
@@ -6787,16 +6856,11 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
private suspend fun probeDashboardAddress(
|
||||
dashboardUrl: String,
|
||||
): Result<Pair<DashboardStatus, DashboardAuthSession?>> {
|
||||
val client = upstreamTransport.dashboardClientForActive(dashboardUrl)
|
||||
val client = upstreamTransport.dashboardClientForActive(dashboardUrl, setupProbe = true)
|
||||
return try {
|
||||
withTimeoutOrNull(8_000L) {
|
||||
val status = client.getStatus().getOrElse { throw it }
|
||||
val session = if (status.authRequired) {
|
||||
client.currentSession().getOrNull()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
Result.success(status to session)
|
||||
val verification = client.verifySetup()
|
||||
Result.success(verification.status to verification.session)
|
||||
} ?: Result.failure(java.net.SocketTimeoutException("Dashboard check timed out"))
|
||||
} catch (cancelled: kotlinx.coroutines.CancellationException) {
|
||||
throw cancelled
|
||||
@@ -6819,7 +6883,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
reachable = true,
|
||||
authRequired = status.authRequired,
|
||||
authProviders = status.authProviders,
|
||||
authenticated = if (status.authRequired) session?.authenticated else true,
|
||||
authenticated = session?.authenticated == true,
|
||||
authProvider = session?.provider,
|
||||
message = status.message,
|
||||
gatewayMode = status.gatewayMode,
|
||||
@@ -7300,6 +7364,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
},
|
||||
apiBearerTokenProvider = { authManager.getApiKey() },
|
||||
dashboardHttpClientProvider = ::dashboardHttpClientForRelayIngress,
|
||||
pluginProxyHttpClientProvider = { url ->
|
||||
pluginProxyClientForUrl(
|
||||
url = url,
|
||||
baseClient = relayOkHttp,
|
||||
includeRelaySessionHeader = false,
|
||||
)
|
||||
},
|
||||
dashboardIngressWebSocketRequestProvider = ::dashboardRelayRequestForIngress,
|
||||
).getVoiceConfig()
|
||||
} else {
|
||||
@@ -7740,6 +7811,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
role: String,
|
||||
dashboardUrl: String,
|
||||
original: EndpointCandidate? = null,
|
||||
httpConsentOrigin: String? = null,
|
||||
onResult: (String?) -> Unit,
|
||||
) {
|
||||
if (original?.priority == 0) {
|
||||
@@ -7755,7 +7827,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
// Accept bare hosts/IPs — http:// is assumed and the standard
|
||||
// Dashboard/Gateway port defaults to 9119.
|
||||
val trimmedUrl = Connection.normalizeDashboardUrlInput(dashboardUrl)
|
||||
if (publicDashboardAddressRequiresHttps(role, trimmedUrl)) {
|
||||
if (publicDashboardAddressRequiresHttps(role, trimmedUrl, setOfNotNull(httpConsentOrigin))) {
|
||||
onResult("Public Gateway routes require HTTPS")
|
||||
return@launch
|
||||
}
|
||||
@@ -7808,7 +7880,12 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
val next = (withoutOriginal + candidate)
|
||||
.sortedWith(compareBy<EndpointCandidate> { it.priority }.thenBy { it.role })
|
||||
connectionStore.updateConnection(current.copy(routeCandidates = next))
|
||||
connectionStore.updateConnection(current.copy(
|
||||
routeCandidates = next,
|
||||
dashboardHttpConsentOrigins = updatedDashboardHttpConsents(
|
||||
current.dashboardHttpConsentOrigins, original?.dashboard?.url, trimmedUrl, httpConsentOrigin,
|
||||
),
|
||||
))
|
||||
// Full probe cycle (not a bare refresh) so the just-saved route
|
||||
// immediately shows a reachability verdict in the Routes card.
|
||||
probeNow()
|
||||
@@ -8375,9 +8452,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
// --- Shared methods ---
|
||||
|
||||
fun setTheme(theme: String) {
|
||||
val normalized = AppearanceNightMode.normalizePreference(theme)
|
||||
viewModelScope.launch {
|
||||
getApplication<Application>().relayDataStore.edit { preferences ->
|
||||
preferences[AppearancePreferences.themeKey] = theme
|
||||
preferences[AppearancePreferences.themeKey] = normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -900,6 +900,11 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
* we don't re-process older turns when the history list updates. */
|
||||
private var assistantSpeechCursor: AssistantSpeechCursor? = null
|
||||
private var voiceTurnSessionFence: VoiceTurnSessionFence? = null
|
||||
private var inboundSpeechGeneration = 0L
|
||||
private var inboundSpeechOwner: Pair<ConversationBinding, String?>? = null
|
||||
private var inboundSpeechObserver: Job? = null
|
||||
private val pendingInboundSpeech = ArrayDeque<Pair<() -> Boolean, String>>()
|
||||
private var inboundSpeechPlaying = false
|
||||
private var sentenceBuffer: StringBuilder = StringBuilder()
|
||||
private val realtimeSpeechCoalescer = BalancedRealtimeTtsCoalescer()
|
||||
private val brokeredToolSpeechKeys = mutableSetOf<String>()
|
||||
@@ -1199,9 +1204,12 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
voiceHandoffReporter: ((VoiceHandoffEvent) -> Unit)? = null,
|
||||
) {
|
||||
cancelStandardSpeechStream("voice dependencies rewired")
|
||||
retireInboundSpeech()
|
||||
this.chatViewModel?.gatewayInboundSpeechReceiver = null
|
||||
this.voiceClient = voiceClient
|
||||
this.voiceAudioClient = voiceAudioClient ?: RelayVoiceAudioClientAdapter(voiceClient)
|
||||
this.chatViewModel = chatViewModel
|
||||
chatViewModel.gatewayInboundSpeechReceiver = ::captureInboundSpeechReceiver
|
||||
this.recorder = recorder
|
||||
this.player = player
|
||||
this.realtimePcmPlayer = realtimePcmPlayer
|
||||
@@ -1537,6 +1545,10 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
*/
|
||||
private fun applyVoiceSettingsSnapshot(settings: com.hermesandroid.relay.data.VoiceSettings) {
|
||||
val nextEngineMode = VoiceEngineMode.fromStorage(settings.engineMode)
|
||||
if (voiceEngineMode != nextEngineMode) {
|
||||
if (inboundSpeechPlaying) interruptSpeaking(cancelActiveTurn = false)
|
||||
else retireInboundSpeech()
|
||||
}
|
||||
val finalAnswerPolicyChanged = finalAnswerOnly != settings.finalAnswerOnly
|
||||
val realtimeSelectionChanged =
|
||||
realtimeModel != settings.realtimeModel || realtimeVoice != settings.realtimeVoice
|
||||
@@ -1675,6 +1687,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
backgroundRun = if (orphanedRun != null) null else it.backgroundRun,
|
||||
)
|
||||
}
|
||||
if (freshEntry) bindInboundSpeechOwner()
|
||||
prewarmRealtimeSession()
|
||||
}
|
||||
|
||||
@@ -1885,6 +1898,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
fun exitVoiceMode() {
|
||||
retireInboundSpeech()
|
||||
cancelPendingListeningStart()
|
||||
// Idempotence guard — added 2026-04-21 after logcat showed the voice-
|
||||
// exit chime playing on every Add-connection tap.
|
||||
@@ -2291,6 +2305,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
* listening turn; until then, idle queue-drain callbacks are ignored.
|
||||
*/
|
||||
fun pauseContinuousMode() {
|
||||
retireInboundSpeech()
|
||||
cancelPendingListeningStart()
|
||||
continuousLoopArmed = false
|
||||
continuousListeningPaused = _uiState.value.interactionMode == InteractionMode.Continuous
|
||||
@@ -2427,6 +2442,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
* new turn on the next mic tap).
|
||||
*/
|
||||
fun interruptSpeaking(cancelActiveTurn: Boolean = true): Job? {
|
||||
retireInboundSpeech()
|
||||
cancelPendingListeningStart()
|
||||
Log.i(
|
||||
TAG,
|
||||
@@ -3584,6 +3600,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
voiceTurnSessionFence?.bindSubmittedUser(submittedUserUiKey)
|
||||
if (inboundSpeechOwner == null) bindInboundSpeechOwner()
|
||||
beginBargeInTurnIfEnabled()
|
||||
startStreamObserver(chatVm)
|
||||
}
|
||||
@@ -4738,6 +4755,99 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
standardSpeechStreamBargeInStarted.set(false)
|
||||
}
|
||||
|
||||
/** The voice overlay owns live completions only for the conversation it entered. */
|
||||
private fun bindInboundSpeechOwner() {
|
||||
val chat = chatViewModel ?: return
|
||||
retireInboundSpeech()
|
||||
inboundSpeechOwner = chat.conversationBinding.value to chat.currentSessionId.value
|
||||
inboundSpeechObserver = viewModelScope.launch {
|
||||
combine(chat.conversationBinding, chat.currentSessionId, _uiState) { binding, id, state ->
|
||||
Triple(binding, id, state)
|
||||
}.collect { (binding, id, _) ->
|
||||
val owner = inboundSpeechOwner ?: return@collect
|
||||
if (owner != (binding to id)) {
|
||||
// The first voice submission may create/adopt a durable session.
|
||||
if (owner.second == null && owner.first.contextKey == binding.contextKey &&
|
||||
voiceTurnSessionFence?.accepts(id, chat.messages.value) == true
|
||||
) {
|
||||
inboundSpeechOwner = binding to id
|
||||
} else {
|
||||
val wasPlaying = inboundSpeechPlaying
|
||||
retireInboundSpeech()
|
||||
if (wasPlaying) interruptSpeaking(cancelActiveTurn = false)
|
||||
return@collect
|
||||
}
|
||||
}
|
||||
drainInboundSpeech()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun retireInboundSpeech() {
|
||||
inboundSpeechGeneration++
|
||||
inboundSpeechOwner = null
|
||||
inboundSpeechObserver?.cancel()
|
||||
inboundSpeechObserver = null
|
||||
pendingInboundSpeech.clear()
|
||||
inboundSpeechPlaying = false
|
||||
}
|
||||
|
||||
/** Called on Main before Chat installs the new live assistant placeholder. */
|
||||
private fun captureInboundSpeechReceiver(): ((String) -> Unit)? {
|
||||
val chat = chatViewModel ?: return null
|
||||
val owner = inboundSpeechOwner ?: return null
|
||||
val generation = inboundSpeechGeneration
|
||||
fun current(): Boolean =
|
||||
generation == inboundSpeechGeneration && _uiState.value.voiceMode &&
|
||||
voiceEngineMode == VoiceEngineMode.HermesVoiceOutput &&
|
||||
inboundSpeechOwner == owner &&
|
||||
owner == (chat.conversationBinding.value to chat.currentSessionId.value)
|
||||
if (owner.second == null || !current()) return null
|
||||
|
||||
// A fast unsolicited start can overtake combine's final local-turn snapshot.
|
||||
// Consume that final snapshot before the new placeholder exists so the two
|
||||
// speech paths cannot narrate the same assistant bubble.
|
||||
if (streamObserverJob?.isActive == true && !chat.isStreaming.value) {
|
||||
assistantSpeechCursor?.let { cursor ->
|
||||
consumeAssistantSpeech(cursor.poll(chat.messages.value), runActive = false)
|
||||
}
|
||||
streamObserverJob?.cancel()
|
||||
}
|
||||
var consumed = false
|
||||
return { text ->
|
||||
if (!consumed) {
|
||||
consumed = true
|
||||
if (current() && sanitizeForTts(text).isNotBlank()) {
|
||||
pendingInboundSpeech.addLast(::current to text)
|
||||
drainInboundSpeech()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for a capture/earlier reply to settle; use the configured output renderer. */
|
||||
private fun drainInboundSpeech(): Boolean {
|
||||
if (pendingInboundSpeech.isEmpty()) return false
|
||||
if (_uiState.value.state != VoiceState.Idle || isMicCaptureActive() ||
|
||||
streamObserverJob?.isActive == true ||
|
||||
chatViewModel?.isStreaming?.value == true ||
|
||||
!agentAudioCompletionDecision().finishNow
|
||||
) return false
|
||||
while (pendingInboundSpeech.isNotEmpty()) {
|
||||
val (current, text) = pendingInboundSpeech.removeAt(0)
|
||||
if (!current()) continue
|
||||
cancelPendingListeningStart()
|
||||
streamComplete = true
|
||||
inboundSpeechPlaying = true
|
||||
resetTtsTurnStats()
|
||||
clearSpokenChunksState()
|
||||
speakSettledFinalAnswer(text)
|
||||
scheduleAgentAudioCompletionCheck()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe every assistant bubble created by the active Hermes run. A tool
|
||||
* turn can finalize one bubble while the run is still active and later
|
||||
@@ -4770,40 +4880,43 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
return@collect
|
||||
}
|
||||
|
||||
val batch = cursor.poll(messages)
|
||||
if (finalAnswerOnly) {
|
||||
if (batch.deltas.isNotEmpty()) {
|
||||
onVisualStreamDelta(batch.aggregateText)
|
||||
}
|
||||
} else {
|
||||
batch.deltas.forEach { update ->
|
||||
if (update.startsNewBubble) {
|
||||
beginAssistantSpeechBubble()
|
||||
}
|
||||
onStreamDelta(update.text, batch.aggregateText)
|
||||
}
|
||||
}
|
||||
// Tool state can change without text growth.
|
||||
if (!finalAnswerOnly) {
|
||||
batch.assistantMessages.forEach(::observeHermesToolLoopForSpeech)
|
||||
}
|
||||
|
||||
if (!runActive && batch.hasTurnAssistant) {
|
||||
streamComplete = true
|
||||
idleFlushJob?.cancel()
|
||||
idleFlushJob = null
|
||||
if (finalAnswerOnly) {
|
||||
speakSettledFinalAnswer(batch.finalAnswerText)
|
||||
} else if (!finishStandardSpeechStream()) {
|
||||
flushRemainingBuffer()
|
||||
}
|
||||
streamObserverJob?.cancel()
|
||||
scheduleAgentAudioCompletionCheck()
|
||||
}
|
||||
consumeAssistantSpeech(cursor.poll(messages), runActive)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun consumeAssistantSpeech(batch: AssistantSpeechBatch, runActive: Boolean) {
|
||||
if (finalAnswerOnly) {
|
||||
if (batch.deltas.isNotEmpty()) {
|
||||
onVisualStreamDelta(batch.aggregateText)
|
||||
}
|
||||
} else {
|
||||
batch.deltas.forEach { update ->
|
||||
if (update.startsNewBubble) {
|
||||
beginAssistantSpeechBubble()
|
||||
}
|
||||
onStreamDelta(update.text, batch.aggregateText)
|
||||
}
|
||||
}
|
||||
// Tool state can change without text growth.
|
||||
if (!finalAnswerOnly) {
|
||||
batch.assistantMessages.forEach(::observeHermesToolLoopForSpeech)
|
||||
}
|
||||
|
||||
if (!runActive && batch.hasTurnAssistant) {
|
||||
streamComplete = true
|
||||
idleFlushJob?.cancel()
|
||||
idleFlushJob = null
|
||||
if (finalAnswerOnly) {
|
||||
speakSettledFinalAnswer(batch.finalAnswerText)
|
||||
} else if (!finishStandardSpeechStream()) {
|
||||
flushRemainingBuffer()
|
||||
}
|
||||
streamObserverJob?.cancel()
|
||||
scheduleAgentAudioCompletionCheck()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onVisualStreamDelta(fullContent: String) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
@@ -5800,6 +5913,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
private fun finishAgentAudioOutput() {
|
||||
inboundSpeechPlaying = false
|
||||
continuousResumeJob = null
|
||||
_responseSpeechActive.value = false
|
||||
stopBargeInListener()
|
||||
@@ -5825,6 +5939,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
_uiState.update { it.copy(amplitude = 0f, outputAudioActive = false) }
|
||||
}
|
||||
|
||||
if (drainInboundSpeech()) return
|
||||
if (_uiState.value.interactionMode == InteractionMode.Continuous &&
|
||||
continuousLoopArmed &&
|
||||
_uiState.value.state == VoiceState.Idle
|
||||
@@ -6686,6 +6801,8 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
retireInboundSpeech()
|
||||
chatViewModel?.gatewayInboundSpeechReceiver = null
|
||||
super.onCleared()
|
||||
voicePreviewJob?.cancel()
|
||||
voicePreviewJob = null
|
||||
|
||||
+46
-10
@@ -104,6 +104,7 @@ class UpstreamTransportController(
|
||||
private val trustedDashboardUrlProvider: (String) -> String? = { null },
|
||||
/** False when the host's advertised auth topology requires cookie compatibility mode. */
|
||||
private val nativeDashboardBearerEligibleProvider: (String) -> Boolean = { true },
|
||||
private val dashboardHttpConsentOriginsProvider: (String) -> Set<String> = { emptySet() },
|
||||
/** Applies pairing-bound TLS to a standard authenticated client when needed. */
|
||||
private val pinnedClientProvider: (String, okhttp3.OkHttpClient) -> okhttp3.OkHttpClient? =
|
||||
{ _, _ -> null },
|
||||
@@ -190,18 +191,29 @@ class UpstreamTransportController(
|
||||
}
|
||||
}
|
||||
|
||||
private fun dashboardClientTransport(
|
||||
connectionId: String?,
|
||||
url: String,
|
||||
base: okhttp3.OkHttpClient,
|
||||
): okhttp3.OkHttpClient = com.hermesandroid.relay.network.upstream.dashboardClientWithHttpConsent(
|
||||
pinnedClientProvider(url, base) ?: base,
|
||||
url,
|
||||
connectionId?.let(dashboardHttpConsentOriginsProvider).orEmpty(),
|
||||
)
|
||||
|
||||
private fun bearerAuthForTrustedDashboard(
|
||||
connectionId: String,
|
||||
dashboardUrl: String,
|
||||
): DashboardBearerAuth? {
|
||||
if (!nativeDashboardBearerEligibleProvider(connectionId)) return null
|
||||
if (!isNativeDashboardTransportEligible(dashboardUrl)) return null
|
||||
if (!isNativeDashboardTransportEligible(dashboardUrl, dashboardHttpConsentOriginsProvider(connectionId))) return null
|
||||
val trustedDashboardUrl = trustedDashboardUrlProvider(connectionId)
|
||||
?: (if (activeConnectionIdProvider() == connectionId) dashboardUrlProvider() else null)
|
||||
?: return null
|
||||
return trustedDashboardBearerAuthOrNull(
|
||||
candidate = dashboardUrl,
|
||||
trusted = trustedDashboardUrl,
|
||||
httpConsentOrigins = dashboardHttpConsentOriginsProvider(connectionId),
|
||||
tokenStoreProvider = { dashboardTokenStoreFor(connectionId) },
|
||||
)
|
||||
}
|
||||
@@ -223,7 +235,7 @@ class UpstreamTransportController(
|
||||
dashboardCookieStoreFor(connectionId),
|
||||
bearerAuthForTrustedDashboard(connectionId, normalizedUrl),
|
||||
)
|
||||
pinnedClientProvider(normalizedUrl, base) ?: base
|
||||
dashboardClientTransport(connectionId, normalizedUrl, base)
|
||||
}
|
||||
return DashboardApiClient(
|
||||
baseUrl = normalizedUrl,
|
||||
@@ -257,16 +269,27 @@ class UpstreamTransportController(
|
||||
* [dashboardUrl], falling back to an in-memory cookie store when there is
|
||||
* no active connection (the standard-voice probe path).
|
||||
*/
|
||||
fun dashboardClientForActive(dashboardUrl: String): DashboardApiClient {
|
||||
fun dashboardClientForActive(dashboardUrl: String, setupProbe: Boolean = false): DashboardApiClient {
|
||||
val ownerId = activeConnectionIdProvider()
|
||||
val trustedBase = ownerId?.let(trustedDashboardUrlProvider) ?: dashboardUrlProvider()
|
||||
val cookies = if (!setupProbe || (trustedBase != null &&
|
||||
com.hermesandroid.relay.network.upstream.sameDashboardBase(dashboardUrl, trustedBase))) {
|
||||
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore()
|
||||
} else InMemoryDashboardCookieStore()
|
||||
val base = dashboardHttpClientFactory(
|
||||
activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
|
||||
cookies,
|
||||
activeConnectionIdProvider()?.let {
|
||||
bearerAuthForTrustedDashboard(it, dashboardUrl)
|
||||
},
|
||||
)
|
||||
val boundedBase = if (setupProbe) base.newBuilder()
|
||||
.callTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.followRedirects(false)
|
||||
.followSslRedirects(false)
|
||||
.build() else base
|
||||
return DashboardApiClient(
|
||||
baseUrl = dashboardUrl,
|
||||
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
|
||||
okHttpClient = dashboardClientTransport(ownerId, dashboardUrl, boundedBase),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -281,7 +304,7 @@ class UpstreamTransportController(
|
||||
)
|
||||
return DashboardApiClient(
|
||||
baseUrl = dashboardUrl,
|
||||
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
|
||||
okHttpClient = dashboardClientTransport(activeConnectionIdProvider(), dashboardUrl, base),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -293,7 +316,7 @@ class UpstreamTransportController(
|
||||
fun nativeDashboardAuthClientForActive(dashboardUrl: String): NativeDashboardAuthClient? {
|
||||
val connectionId = activeConnectionIdProvider() ?: return null
|
||||
val trustedDashboardUrl = dashboardUrlProvider() ?: return null
|
||||
if (!isNativeDashboardTransportEligible(dashboardUrl)) {
|
||||
if (!isNativeDashboardTransportEligible(dashboardUrl, dashboardHttpConsentOriginsProvider(connectionId))) {
|
||||
return null
|
||||
}
|
||||
if (!com.hermesandroid.relay.network.upstream.sameDashboardBase(
|
||||
@@ -312,7 +335,7 @@ class UpstreamTransportController(
|
||||
return NativeDashboardAuthClient(
|
||||
baseUrl = dashboardUrl,
|
||||
tokenStore = dashboardTokenStoreFor(connectionId),
|
||||
client = pinnedClientProvider(dashboardUrl, base) ?: base,
|
||||
client = dashboardClientTransport(activeConnectionIdProvider(), dashboardUrl, base),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -331,7 +354,7 @@ class UpstreamTransportController(
|
||||
bearerAuthForTrustedDashboard(activeId, dashboardUrl)
|
||||
},
|
||||
)
|
||||
return (pinnedClientProvider(dashboardUrl, base) ?: base)
|
||||
return (dashboardClientTransport(activeConnectionIdProvider(), dashboardUrl, base))
|
||||
.also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
|
||||
}
|
||||
|
||||
@@ -458,8 +481,17 @@ class UpstreamTransportController(
|
||||
}
|
||||
gatewayClientCache?.third?.shutdown()
|
||||
lateinit var client: GatewayChatClient
|
||||
// Dashboard REST already carries the pairing SPKI pin for Secure Link.
|
||||
// The gateway WS upgrade must use the SAME client — a bare OkHttpClient
|
||||
// rejects the self-signed Secure Link cert ("Trust anchor … not found")
|
||||
// and leaves Chat stuck on "Checking gateway…".
|
||||
val dashboardClient = dashboardClientFor(connectionId, dashboardUrl)
|
||||
val gatewayHttpClient = dashboardRestHttpClients[
|
||||
connectionId to dashboardUrl.trim().trimEnd('/'),
|
||||
]
|
||||
client = GatewayChatClient(
|
||||
initialDashboardClient = dashboardClientFor(connectionId, dashboardUrl),
|
||||
initialDashboardClient = dashboardClient,
|
||||
okHttpClient = gatewayHttpClient,
|
||||
onGatewayUnsupported = {
|
||||
updateGatewayAvailabilityIfCurrent(
|
||||
connectionId,
|
||||
@@ -531,12 +563,16 @@ class UpstreamTransportController(
|
||||
if (cached.activeRequests == 0 && cached.retained == 0) shutdownRouteEntry(cached)
|
||||
}
|
||||
val dashboardClient = dashboardClientFor(connectionId, dashboardUrl)
|
||||
val gatewayHttpClient = dashboardRestHttpClients[
|
||||
connectionId to dashboardUrl.trim().trimEnd('/'),
|
||||
]
|
||||
entry = RouteGatewayEntry(
|
||||
dashboardUrl = dashboardUrl,
|
||||
dashboardClient = dashboardClient,
|
||||
client = GatewayChatClient(
|
||||
initialDashboardClient = dashboardClient,
|
||||
fixedSessionProfile = profile,
|
||||
okHttpClient = gatewayHttpClient,
|
||||
).also { it.setKeepAliveInBackground(gatewayKeepAliveProvider()) },
|
||||
)
|
||||
if (retain) entry.retained = 1 else entry.activeRequests = 1
|
||||
|
||||
@@ -294,7 +294,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 API direta são opcionais.</string>
|
||||
<string name="cw_relay_optional_note">HTTPS é recomendado. Outros endereços HTTP exigem aceitação explícita do risco. O aplicativo não impõe proteção VPN. Relay e Direct API são opcionais.</string>
|
||||
<string name="cw_cloud_entry_title">Conectar ao Hermes hospedado pela Nous</string>
|
||||
<string name="cw_cloud_entry_description">Insira o endereço do agente mostrado no Nous Portal. Você entrará com segurança depois que o Hermes for encontrado.</string>
|
||||
<string name="cw_cloud_agent_name">Endereço do agente</string>
|
||||
@@ -302,7 +302,7 @@
|
||||
<string name="cw_cloud_slug_hint">Conectaremos a seu-agente.agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_slug_error">Insira exatamente as letras, os números e os hifens antes de .agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_address_placeholder">https://seu-agente.example.com</string>
|
||||
<string name="cw_cloud_address_hint">Use o endereço HTTPS completo exibido para seu agente hospedado.</string>
|
||||
<string name="cw_cloud_address_hint">Use o endereço HTTPS completo exibido para seu agente hospedado, incluindo :porta se ela for fornecida.</string>
|
||||
<string name="cw_cloud_use_custom_address">Usar URL personalizada</string>
|
||||
<string name="cw_cloud_use_nous_address">Usar endereço hospedado pela Nous</string>
|
||||
<string name="cw_before_connecting">Antes de conectar</string>
|
||||
@@ -322,10 +322,10 @@
|
||||
<string name="cw_nearby_enter_address">Informar endereço</string>
|
||||
<string name="cw_other_connection_methods">Outros métodos de conexão</string>
|
||||
<string name="cw_manual_hermes_title">Informe o endereço do gateway</string>
|
||||
<string name="cw_manual_hermes_description">Informe o endereço do Painel usado no navegador. Se ele não abrir neste celular, inicie hermes dashboard e verifique o Wi-Fi ou o Tailscale.</string>
|
||||
<string name="cw_manual_hermes_description">Digite o endereço do Dashboard que pode abrir neste telefone. Para LAN ou VPN, o host precisa de um Dashboard acessível e autenticação. Consulte o guia de configuração se o navegador não conectar.</string>
|
||||
<string name="cw_hermes_address">Endereço do Hermes</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 ou hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">Nenhuma chave de API é necessária. A porta 9119 é usada quando nenhuma porta é informada.</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">Exemplos: 192.168.1.10:9119 ou https://hermes.example.com:10443. Se omitida, hosts privados usam a porta 9119 e HTTPS usa a 443. Nenhuma chave API é necessária.</string>
|
||||
<string name="cw_find_hermes">Procurar Hermes</string>
|
||||
<string name="cw_hermes_found">Hermes encontrado</string>
|
||||
<string name="cw_ready_to_connect">Pronto para conectar</string>
|
||||
@@ -348,12 +348,12 @@
|
||||
<string name="cw_skip_for_now">Pular por enquanto — configure depois em Configurações</string>
|
||||
<string name="cw_back">Voltar</string>
|
||||
<string name="cw_connect_button">Conectar</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">Use isto para Chat e Gerenciar. Pareie o Relay depois somente quando ativar Terminal, Bridge, sessões do Relay ou permissões. O login no painel é o caminho de autenticação upstream preferencial; a chave da API continua sendo a alternativa para o Chat do Android.</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API é uma conexão de compatibilidade escolhida explicitamente para o chat do servidor API. Manage, sessões do Dashboard e voz padrão exigem login separado no Dashboard. Ela não assume uma conversa existente do Gateway.</string>
|
||||
<string name="cw_api_url_label">URL ou host do servidor API</string>
|
||||
<string name="cw_api_key_label">Chave da API</string>
|
||||
<string name="cw_api_key_placeholder">Valor de API_SERVER_KEY</string>
|
||||
<string name="cw_api_key_hint">Necessária para o Chat do Android até que o transporte do Gateway pelo painel seja ativado.</string>
|
||||
<string name="cw_api_key_hint">Chave bearer apenas para este servidor API. Ela não faz login no Dashboard.</string>
|
||||
<string name="cw_tailscale_label">Acesso remoto — URL do Tailscale (opcional)</string>
|
||||
<string name="cw_dashboard">Painel</string>
|
||||
<string name="cw_dashboard_routes_hint">Rotas: primeiro a padrão, depois o Tailscale quando estiver acessível.</string>
|
||||
@@ -368,7 +368,7 @@
|
||||
<string name="cw_cancel">Cancelar</string>
|
||||
<!-- Method tiles -->
|
||||
<string name="cw_method_hermes_title">Hermes</string>
|
||||
<string name="cw_method_hermes_subtitle">Configuração de API/painel para Chat, Gerenciar, Habilidades, Cron, MCP, Perfis, Modelos e Configurações</string>
|
||||
<string name="cw_method_hermes_subtitle">Chat explícito do servidor API para configurações sem interface ou de compatibilidade</string>
|
||||
<string name="cw_method_scan_title">Ler QR de configuração</string>
|
||||
<string name="cw_method_scan_subtitle">Leia um QR com a URL/chave da API do Hermes; os detalhes do QR do Relay exigem o plugin do Relay</string>
|
||||
<string name="cw_method_pair_code_title">Parear o Relay por código</string>
|
||||
@@ -377,7 +377,7 @@
|
||||
<string name="cw_method_show_code_subtitle">Sem câmera ou QR? Registre o código deste celular no host</string>
|
||||
<!-- Standard connect form -->
|
||||
<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_api_url_supporting">Endereço do servidor para chat Direct API. Hosts sem esquema usam HTTP e a porta 8642.</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 em conexões explícitas pela API direta.</string>
|
||||
<string name="cw_pair_relay_section">Parear o Relay (opcional)</string>
|
||||
@@ -467,7 +467,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">O host ainda não aceitou este código de pareamento. Execute o comando de pareamento no host do Hermes (ou confira o código) e toque em Tentar novamente.</string>
|
||||
<string name="cw_timeout_scan">O tempo se esgotou antes de o relay confirmar o pareamento. Verifique se o relay está em execução e acessível nesta rede e tente novamente. Se o pareamento parecer concluído, mas o Hermes ainda estiver inacessível, talvez o servidor API esteja atrás de um Gateway de login.</string>
|
||||
<string name="cw_timeout_other">O tempo de espera pelo relay se esgotou. Verifique se o relay está em execução e se a URL está correta.</string>
|
||||
<string name="cw_camera_denied">Permissão da câmera negada. Faça o pareamento manual — escolha \"Parear o Relay por código\" ou insira a URL do servidor.</string>
|
||||
<string name="cw_camera_denied">Permissão de câmera negada. Escolha Gateway remoto e digite o endereço do Dashboard. Os códigos de pareamento Relay estão em Avançado.</string>
|
||||
<!-- EndpointsCard -->
|
||||
<string name="endpoints_no_routes_stored">Nenhuma rota armazenada para esta conexão.</string>
|
||||
<string name="endpoints_add_route">Adicionar rota</string>
|
||||
@@ -2671,6 +2671,7 @@
|
||||
<string name="model_picker_title">Modelo</string>
|
||||
<string name="model_picker_search">Pesquisar modelos ou provedores…</string>
|
||||
<string name="model_picker_empty">Nenhum modelo corresponde à pesquisa</string>
|
||||
<string name="model_picker_no_models">Nenhum modelo disponível. Tente atualizar.</string>
|
||||
<!-- InjectedContextSheet -->
|
||||
<string name="context_sheet_agent_sees">O que o agente vê</string>
|
||||
<string name="context_sheet_transparency">O contexto adicional exato adicionado ao início do próximo turno, para transparência.</string>
|
||||
@@ -3179,7 +3180,7 @@
|
||||
<string name="endpoints_pin_title">Endpoints fixados</string>
|
||||
<string name="endpoints_route_editor_desc">Adicione o endereço do Dashboard/Gateway que este celular deve usar nessa rede.</string>
|
||||
<string name="endpoints_route_name_placeholder">Nome da rota</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z ou host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 ou https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">Insira o endereço do Dashboard do servidor</string>
|
||||
<string name="endpoints_url_supporting_enter">Use um endereço de Dashboard http:// ou https://</string>
|
||||
<string name="endpoints_url_supporting_preview">Será testado: %1$s</string>
|
||||
@@ -3365,16 +3366,16 @@
|
||||
<string name="cw_relay_pair_qr">Emparelhar Hermes Relay</string>
|
||||
<string name="cw_relay_pair_qr_desc">Escaneie um QR de configuração do Relay</string>
|
||||
<string name="cw_relay_enter_code">Inserir código de emparelhamento</string>
|
||||
<string name="cw_dashboard_connected_title">Hermes está conectado</string>
|
||||
<string name="cw_dashboard_connected_body">Dashboard e Gateway estão prontos. Você pode começar a conversar ou abrir Manage.</string>
|
||||
<string name="cw_dashboard_connected_title">Acesso ao Dashboard verificado</string>
|
||||
<string name="cw_dashboard_connected_body">Continue para o Chat. A conexão Gateway e a disponibilidade de voz são verificadas separadamente.</string>
|
||||
<string name="cw_continue">Continuar</string>
|
||||
<string name="cw_timeline_discovered">Hermes encontrado</string>
|
||||
<string name="cw_timeline_discovered_detail">Identidade do Dashboard e endpoint de status verificados</string>
|
||||
<string name="cw_timeline_discovered_detail">Estado do Dashboard obtido</string>
|
||||
<string name="cw_timeline_access">Acesso ao Dashboard</string>
|
||||
<string name="cw_timeline_access_ready">Nenhum login adicional necessário</string>
|
||||
<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="cw_timeline_ready">Pronto para continuar</string>
|
||||
<string name="cw_timeline_ready_detail">Chat conecta ao abrir; a voz é verificada separadamente</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>
|
||||
@@ -4391,11 +4392,11 @@
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</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_body">Defina o endereço do Dashboard e Gateway desta conexão. Inclua :porta quando necessário, por exemplo 192.168.1.10:9119 ou https://hermes.example.com:10443. HTTPS é recomendado. Outros endereços HTTP exigem aceitação explícita do risco.</string>
|
||||
<string name="dashboard_address_editor_title">Endereço do gateway</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_oidc_hint">Alterar o endereço preserva este gateway e as referências ao histórico, mas uma origem diferente exige novo login. Os retornos OIDC são configurados no Hermes.</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Informe o endereço do Gateway Hermes</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
@@ -4453,4 +4454,9 @@
|
||||
<string name="voice_overlay_settings_hint">Opcional nas duas versões. Abra o foco de voz no Chat e escolha Sobreposição. As permissões sozinhas nunca iniciam a escuta.</string>
|
||||
<string name="voice_overlay_reset_position">Redefinir posição</string>
|
||||
<string name="injected_context_gateway_unsupported">Não é enviado no chat do Gateway. Esta conexão não oferece suporte a contexto adicional por turno.</string>
|
||||
<string name="dashboard_http_risk">HTTP não criptografa solicitações a %1$s. Senhas, tokens de sessão e conversas podem ficar expostos. Se depender de uma VPN, você é responsável por manter o tráfego dentro dela, inclusive se ela cair. O aplicativo não detecta nem impõe proteção VPN.</string>
|
||||
<string name="dashboard_http_allow">Aceito o risco e permito HTTP para este endereço</string>
|
||||
<string name="cw_auth_verified">Login verificado</string>
|
||||
<string name="cw_chat_checked_on_open">Verificado ao abrir o Chat</string>
|
||||
<string name="dashboard_local_auth_help">Hermes está acessível, mas as solicitações protegidas não estão autorizadas. Se o Dashboard for encaminhado do loopback, confira o endereço de escuta, o provedor de autenticação e dashboard.public_url no host. Um 401 sozinho não identifica a causa.</string>
|
||||
</resources>
|
||||
|
||||
@@ -315,7 +315,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">建议使用 HTTPS。其他 HTTP 地址需要明确接受风险。应用不会强制执行 VPN 保护。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>
|
||||
@@ -323,7 +323,7 @@
|
||||
<string name="cw_cloud_slug_hint">我们将连接到 your-agent.agents.nousresearch.com。</string>
|
||||
<string name="cw_cloud_slug_error">请准确输入 .agents.nousresearch.com 前的字母、数字和连字符。</string>
|
||||
<string name="cw_cloud_address_placeholder">https://your-agent.example.com</string>
|
||||
<string name="cw_cloud_address_hint">请使用为托管智能体显示的完整 HTTPS 地址。</string>
|
||||
<string name="cw_cloud_address_hint">请使用为托管智能体显示的完整 HTTPS 地址;如有提供,也请包含 :端口。</string>
|
||||
<string name="cw_cloud_use_custom_address">使用自定义网址</string>
|
||||
<string name="cw_cloud_use_nous_address">使用 Nous 托管地址</string>
|
||||
<string name="cw_before_connecting">连接之前</string>
|
||||
@@ -343,10 +343,10 @@
|
||||
<string name="cw_nearby_enter_address">改为输入地址</string>
|
||||
<string name="cw_other_connection_methods">其他连接方式</string>
|
||||
<string name="cw_manual_hermes_title">输入网关地址</string>
|
||||
<string name="cw_manual_hermes_description">请输入你在浏览器中打开的仪表板地址。如果此手机无法打开,请启动 hermes dashboard 并检查 Wi-Fi 或 Tailscale。</string>
|
||||
<string name="cw_manual_hermes_description">输入可在此手机浏览器中打开的 Dashboard 地址。通过 LAN 或 VPN 访问时,主机需要可达的 Dashboard 和身份验证。若浏览器无法连接,请参阅设置指南。</string>
|
||||
<string name="cw_hermes_address">Hermes 地址</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 或 hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">无需 API 密钥。未指定端口时使用仪表板端口 9119。</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">示例:192.168.1.10:9119 或 https://hermes.example.com:10443。省略时,私有主机使用端口 9119,HTTPS 使用端口 443。无需 API 密钥。</string>
|
||||
<string name="cw_find_hermes">查找 Hermes</string>
|
||||
<string name="cw_hermes_found">已找到 Hermes</string>
|
||||
<string name="cw_ready_to_connect">可以连接</string>
|
||||
@@ -369,12 +369,12 @@
|
||||
<string name="cw_skip_for_now">暂时跳过——稍后在设置中配置</string>
|
||||
<string name="cw_back">上一步</string>
|
||||
<string name="cw_connect_button">连接</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">用于聊天和管理。等启用终端、Bridge、Relay 会话或授权时再配对 Relay。仪表盘登录是首选的上游认证方式;API 密钥仍是 Android 聊天的备用方式。</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API 是为 API 服务器聊天明确选择的兼容连接。Manage、Dashboard 会话和标准语音需要单独登录 Dashboard。它不会接管现有 Gateway 对话。</string>
|
||||
<string name="cw_api_url_label">API 服务器地址或主机名</string>
|
||||
<string name="cw_api_key_label">API 密钥</string>
|
||||
<string name="cw_api_key_placeholder">API_SERVER_KEY 的值</string>
|
||||
<string name="cw_api_key_hint">在仪表盘网关传输启用前,Android 聊天需要此密钥。</string>
|
||||
<string name="cw_api_key_hint">仅用于此 API 服务器的 Bearer 密钥,不能用于登录 Dashboard。</string>
|
||||
<string name="cw_tailscale_label">远程访问——Tailscale 地址(可选)</string>
|
||||
<string name="cw_dashboard">仪表盘</string>
|
||||
<string name="cw_dashboard_routes_hint">路由:默认优先,Tailscale 在可达时作为备用。</string>
|
||||
@@ -390,7 +390,7 @@
|
||||
|
||||
<!-- 方法卡片 -->
|
||||
<string name="cw_method_hermes_title">Hermes</string>
|
||||
<string name="cw_method_hermes_subtitle">API/仪表盘设置,用于聊天、管理、技能、定时任务、MCP、配置文件、模型和设置</string>
|
||||
<string name="cw_method_hermes_subtitle">为无界面或兼容配置明确选择的 API 服务器聊天</string>
|
||||
<string name="cw_method_scan_title">扫描设置二维码</string>
|
||||
<string name="cw_method_scan_subtitle">扫描包含 API 地址/密钥的二维码;Relay 二维码详情需要 Relay 插件</string>
|
||||
<string name="cw_method_pair_code_title">用配对码配对 Relay</string>
|
||||
@@ -400,7 +400,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_api_url_supporting">Direct API 聊天使用的 API 服务器地址。仅输入主机时使用 HTTP 和端口 8642。</string>
|
||||
<string name="cw_scan_message">正在扫描本局域网寻找 Hermes 仪表盘/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于明确配置的 Direct API 连接。</string>
|
||||
<string name="cw_pair_relay_section">配对 Relay(可选)</string>
|
||||
@@ -495,7 +495,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">主机尚未接受此配对码。请在 Hermes 主机上运行配对命令(或重新检查配对码),然后点击重试。</string>
|
||||
<string name="cw_timeout_scan">在 Relay 确认配对之前超时。请检查 Relay 是否在运行且在此网络上可达,然后重试。如果配对似乎成功但仍无法访问 Hermes,则 API 服务器可能位于登录网关之后。</string>
|
||||
<string name="cw_timeout_other">等待 Relay 超时。请检查 Relay 是否正在运行以及地址是否正确。</string>
|
||||
<string name="cw_camera_denied">摄像头权限被拒绝。请改为手动配对——选择"用配对码配对 Relay"或输入您的服务器地址。</string>
|
||||
<string name="cw_camera_denied">相机权限被拒绝。请选择远程 Gateway 并输入 Dashboard 地址。Relay 配对码位于高级选项中。</string>
|
||||
|
||||
<!-- EndpointsCard -->
|
||||
<string name="endpoints_no_routes_stored">此连接尚未存储任何路由。</string>
|
||||
@@ -2782,6 +2782,7 @@
|
||||
<string name="model_picker_title">模型</string>
|
||||
<string name="model_picker_search">搜索模型或提供商…</string>
|
||||
<string name="model_picker_empty">没有匹配您搜索的模型</string>
|
||||
<string name="model_picker_no_models">没有可用的模型。请尝试刷新。</string>
|
||||
|
||||
<!-- InjectedContextSheet -->
|
||||
<string name="context_sheet_agent_sees">代理看到的内容</string>
|
||||
@@ -3278,7 +3279,7 @@
|
||||
<string name="endpoints_pin_title">固定端点</string>
|
||||
<string name="endpoints_route_editor_desc">添加此手机在该网络上应使用的 Dashboard/Gateway 地址。</string>
|
||||
<string name="endpoints_route_name_placeholder">路由名称</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z 或 host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 或 https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">输入服务器的 Dashboard 地址</string>
|
||||
<string name="endpoints_url_supporting_enter">使用 http:// 或 https:// Dashboard 地址</string>
|
||||
<string name="endpoints_url_supporting_preview">将测试:%1$s</string>
|
||||
@@ -3517,16 +3518,16 @@
|
||||
<string name="cw_relay_pair_qr">配对 Hermes Relay</string>
|
||||
<string name="cw_relay_pair_qr_desc">扫描 Relay 设置二维码</string>
|
||||
<string name="cw_relay_enter_code">输入配对码</string>
|
||||
<string name="cw_dashboard_connected_title">Hermes 已连接</string>
|
||||
<string name="cw_dashboard_connected_body">Dashboard 和 Gateway 已就绪。你可以开始聊天或打开 Manage。</string>
|
||||
<string name="cw_dashboard_connected_title">Dashboard 访问已验证</string>
|
||||
<string name="cw_dashboard_connected_body">继续进入 Chat。Gateway 连接和语音可用性会分别检查。</string>
|
||||
<string name="cw_continue">继续</string>
|
||||
<string name="cw_timeline_discovered">已发现 Hermes</string>
|
||||
<string name="cw_timeline_discovered_detail">已验证 Dashboard 标识和状态端点</string>
|
||||
<string name="cw_timeline_discovered_detail">已获取 Dashboard 状态</string>
|
||||
<string name="cw_timeline_access">Dashboard 访问</string>
|
||||
<string name="cw_timeline_access_ready">无需额外登录</string>
|
||||
<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="cw_timeline_ready">可以继续</string>
|
||||
<string name="cw_timeline_ready_detail">打开 Chat 时连接,语音可用性单独检查</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>
|
||||
@@ -4472,11 +4473,11 @@
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</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_body">设置此连接的 Dashboard 和 Gateway 地址。需要时请包含 :端口,例如 192.168.1.10:9119 或 https://hermes.example.com:10443。建议使用 HTTPS。其他 HTTP 地址需要明确接受风险。</string>
|
||||
<string name="dashboard_address_editor_title">网关地址</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_oidc_hint">更改地址会保留此 Gateway 和历史记录引用,但更换源后需要重新登录。OIDC 回调在 Hermes 上配置。</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">输入 Hermes Gateway 地址</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
@@ -4534,4 +4535,9 @@
|
||||
<string name="voice_overlay_settings_hint">两个版本均可选择使用。在聊天的语音专注模式中选择悬浮窗。仅授予权限不会开始监听。</string>
|
||||
<string name="voice_overlay_reset_position">重置位置</string>
|
||||
<string name="injected_context_gateway_unsupported">Gateway 聊天不会发送此内容。此连接不支持每轮附加上下文。</string>
|
||||
<string name="dashboard_http_risk">HTTP 不会加密发送到 %1$s 的请求。密码、会话令牌和对话可能泄露。如果依赖 VPN,您有责任确保流量始终处于 VPN 内,包括 VPN 断开时。应用不会检测或强制执行 VPN 保护。</string>
|
||||
<string name="dashboard_http_allow">我接受风险并允许此地址使用 HTTP</string>
|
||||
<string name="cw_auth_verified">登录已验证</string>
|
||||
<string name="cw_chat_checked_on_open">打开 Chat 时验证</string>
|
||||
<string name="dashboard_local_auth_help">Hermes 可达,但受保护的请求未获授权。如果 Dashboard 从回环地址转发,请检查主机的监听地址、身份验证提供方和 dashboard.public_url。仅凭 401 无法确定原因。</string>
|
||||
</resources>
|
||||
|
||||
@@ -315,7 +315,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 Direct API sind optional.</string>
|
||||
<string name="cw_relay_optional_note">HTTPS wird empfohlen. Andere HTTP-Adressen erfordern eine ausdrückliche Risikoannahme. Die App erzwingt keinen VPN-Schutz. 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>
|
||||
@@ -323,7 +323,7 @@
|
||||
<string name="cw_cloud_slug_hint">Wir verbinden dich mit dein-agent.agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_slug_error">Gib exakt die Buchstaben, Zahlen und Bindestriche vor .agents.nousresearch.com ein.</string>
|
||||
<string name="cw_cloud_address_placeholder">https://dein-agent.example.com</string>
|
||||
<string name="cw_cloud_address_hint">Verwende die vollständige HTTPS-Adresse, die für deinen gehosteten Agenten angezeigt wird.</string>
|
||||
<string name="cw_cloud_address_hint">Verwende die vollständige HTTPS-Adresse, die für deinen gehosteten Agenten angezeigt wird, einschließlich :Port, falls angegeben.</string>
|
||||
<string name="cw_cloud_use_custom_address">Benutzerdefinierte URL verwenden</string>
|
||||
<string name="cw_cloud_use_nous_address">Von Nous gehostete Adresse verwenden</string>
|
||||
<string name="cw_before_connecting">Vor dem Verbinden</string>
|
||||
@@ -343,10 +343,10 @@
|
||||
<string name="cw_nearby_enter_address">Stattdessen Adresse eingeben</string>
|
||||
<string name="cw_other_connection_methods">Andere Verbindungsmethoden</string>
|
||||
<string name="cw_manual_hermes_title">Gateway-Adresse eingeben</string>
|
||||
<string name="cw_manual_hermes_description">Gib die Dashboard-Adresse ein, die du im Browser öffnest. Wenn sie auf diesem Smartphone nicht geöffnet wird, starte hermes dashboard und prüfe WLAN oder Tailscale.</string>
|
||||
<string name="cw_manual_hermes_description">Gib die Dashboard-Adresse ein, die sich auf diesem Telefon öffnen lässt. Für LAN oder VPN benötigt der Host ein erreichbares Dashboard mit Authentifizierung. Wenn der Browser keine Verbindung herstellt, lies die Einrichtungsanleitung.</string>
|
||||
<string name="cw_hermes_address">Hermes-Adresse</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 oder hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">Kein API-Schlüssel erforderlich. Ohne Port wird Dashboard-Port 9119 verwendet.</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">Beispiele: 192.168.1.10:9119 oder https://hermes.example.com:10443. Ohne Angabe verwenden private Hosts Port 9119 und HTTPS Port 443. Kein API-Schlüssel nötig.</string>
|
||||
<string name="cw_find_hermes">Hermes suchen</string>
|
||||
<string name="cw_hermes_found">Hermes gefunden</string>
|
||||
<string name="cw_ready_to_connect">Verbindungsbereit</string>
|
||||
@@ -369,12 +369,12 @@
|
||||
<string name="cw_skip_for_now">Vorerst überspringen — später in den Einstellungen einrichten</string>
|
||||
<string name="cw_back">Zurück</string>
|
||||
<string name="cw_connect_button">Verbinden</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">Verwende dies für Chat und Verwaltung. Kopple Relay später nur, wenn du Terminal, Bridge, Relay-Sitzungen oder Berechtigungen aktivierst. Die Dashboard-Anmeldung ist der bevorzugte vorgelagerte Authentifizierungsweg; der API-Schlüssel bleibt die Ausweichlösung für Android-Chat.</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API ist eine ausdrücklich gewählte Kompatibilitätsverbindung für API-Server-Chats. Manage, Dashboard-Sitzungen und Standard-Sprachfunktionen erfordern eine separate Dashboard-Anmeldung. Bestehende Gateway-Unterhaltungen wechseln nicht zu Direct API.</string>
|
||||
<string name="cw_api_url_label">API-Server-URL oder Host</string>
|
||||
<string name="cw_api_key_label">API-Schlüssel</string>
|
||||
<string name="cw_api_key_placeholder">Wert aus API_SERVER_KEY</string>
|
||||
<string name="cw_api_key_hint">Für Android-Chat erforderlich, bis der Dashboard-Gateway-Transport aktiviert ist.</string>
|
||||
<string name="cw_api_key_hint">Bearer-Schlüssel nur für diesen API-Server. Er meldet dich nicht am Dashboard an.</string>
|
||||
<string name="cw_tailscale_label">Fernzugriff — Tailscale-URL (optional)</string>
|
||||
<string name="cw_dashboard">Dashboard</string>
|
||||
<string name="cw_dashboard_routes_hint">Routen: zuerst Standard, bei Erreichbarkeit Tailscale als Ausweichroute.</string>
|
||||
@@ -390,7 +390,7 @@
|
||||
|
||||
<!-- Method tiles -->
|
||||
<string name="cw_method_hermes_title">Hermes</string>
|
||||
<string name="cw_method_hermes_subtitle">API-/Dashboard-Einrichtung für Chat, Verwaltung, Skills, Cron, MCP, Profile, Modelle und Einstellungen</string>
|
||||
<string name="cw_method_hermes_subtitle">Ausdrücklich gewählter API-Server-Chat für Headless- oder Kompatibilitätskonfigurationen</string>
|
||||
<string name="cw_method_scan_title">Einrichtungs-QR-Code scannen</string>
|
||||
<string name="cw_method_scan_subtitle">Scanne einen QR-Code mit API-URL/-Schlüssel für Hermes; Relay-QR-Daten erfordern das Relay-Plugin</string>
|
||||
<string name="cw_method_pair_code_title">Relay per Code koppeln</string>
|
||||
@@ -400,7 +400,7 @@
|
||||
|
||||
<!-- Standard connect form -->
|
||||
<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_api_url_supporting">API-Server-Adresse für Direct-API-Chat. Reine Hostnamen verwenden HTTP und Port 8642.</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 eine explizite Direct-API-Verbindung.</string>
|
||||
<string name="cw_pair_relay_section">Relay koppeln (optional)</string>
|
||||
@@ -495,7 +495,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">Der Host hat diesen Kopplungscode noch nicht angenommen. Führe den Kopplungsbefehl auf deinem Hermes-Host aus (oder prüfe den Code erneut) und tippe dann auf Erneut versuchen.</string>
|
||||
<string name="cw_timeout_scan">Zeitüberschreitung, bevor das Relay die Kopplung bestätigt hat. Prüfe, ob das Relay läuft und in diesem Netzwerk erreichbar ist, und versuche es erneut. Falls die Kopplung erfolgreich scheint, Hermes aber weiterhin nicht erreichbar ist, befindet sich der API-Server möglicherweise hinter einem Anmelde-Gateway.</string>
|
||||
<string name="cw_timeout_other">Zeitüberschreitung beim Warten auf das Relay. Prüfe, ob das Relay läuft und die URL stimmt.</string>
|
||||
<string name="cw_camera_denied">Kameraberechtigung abgelehnt. Kopple stattdessen manuell — wähle \"Relay per Code koppeln\" oder gib deine Server-URL ein.</string>
|
||||
<string name="cw_camera_denied">Kamerazugriff verweigert. Wähle Remote-Gateway und gib die Dashboard-Adresse ein. Relay-Kopplungscodes findest du unter Erweitert.</string>
|
||||
|
||||
<!-- EndpointsCard -->
|
||||
<string name="endpoints_no_routes_stored">Für diese Verbindung sind keine Routen gespeichert.</string>
|
||||
@@ -2788,6 +2788,7 @@
|
||||
<string name="model_picker_title">Modell</string>
|
||||
<string name="model_picker_search">Modelle oder Anbieter suchen…</string>
|
||||
<string name="model_picker_empty">Keine Modelle entsprechen deiner Suche</string>
|
||||
<string name="model_picker_no_models">Keine Modelle verfügbar. Versuche es mit Aktualisieren.</string>
|
||||
|
||||
<!-- InjectedContextSheet -->
|
||||
<string name="context_sheet_agent_sees">Was der Agent sieht</string>
|
||||
@@ -3347,7 +3348,7 @@
|
||||
<string name="endpoints_pin_title">Angeheftete Endpunkte</string>
|
||||
<string name="endpoints_route_editor_desc">Füge die Dashboard-/Gateway-Adresse hinzu, die dieses Telefon in diesem Netzwerk verwenden soll.</string>
|
||||
<string name="endpoints_route_name_placeholder">Routenname</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z oder host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 oder https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">Dashboard-Adresse des Servers eingeben</string>
|
||||
<string name="endpoints_url_supporting_enter">Eine http://- oder https://-Dashboard-Adresse verwenden</string>
|
||||
<string name="endpoints_url_supporting_preview">Wird getestet: %1$s</string>
|
||||
@@ -3585,16 +3586,16 @@
|
||||
<string name="cw_relay_pair_qr">Hermes Relay koppeln</string>
|
||||
<string name="cw_relay_pair_qr_desc">Einen Relay-Einrichtungs-QR-Code scannen</string>
|
||||
<string name="cw_relay_enter_code">Pairing-Code eingeben</string>
|
||||
<string name="cw_dashboard_connected_title">Hermes ist verbunden</string>
|
||||
<string name="cw_dashboard_connected_body">Dashboard und Gateway sind bereit. Du kannst chatten oder Manage öffnen.</string>
|
||||
<string name="cw_dashboard_connected_title">Dashboard-Zugriff bestätigt</string>
|
||||
<string name="cw_dashboard_connected_body">Weiter zu Chat. Gateway-Verbindung und Sprachverfügbarkeit werden getrennt geprüft.</string>
|
||||
<string name="cw_continue">Weiter</string>
|
||||
<string name="cw_timeline_discovered">Hermes gefunden</string>
|
||||
<string name="cw_timeline_discovered_detail">Dashboard-Identität und Status-Endpunkt bestätigt</string>
|
||||
<string name="cw_timeline_discovered_detail">Dashboard-Status abgerufen</string>
|
||||
<string name="cw_timeline_access">Dashboard-Zugriff</string>
|
||||
<string name="cw_timeline_access_ready">Keine weitere Anmeldung erforderlich</string>
|
||||
<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="cw_timeline_ready">Bereit zum Fortfahren</string>
|
||||
<string name="cw_timeline_ready_detail">Chat verbindet sich beim Öffnen; Sprachverfügbarkeit wird getrennt geprüft</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>
|
||||
@@ -4548,11 +4549,11 @@
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</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_body">Lege die Dashboard- und Gateway-Adresse dieser Verbindung fest. Gib bei Bedarf :port an, zum Beispiel 192.168.1.10:9119 oder https://hermes.example.com:10443. HTTPS wird empfohlen. Andere HTTP-Adressen erfordern deine ausdrückliche Risikoannahme.</string>
|
||||
<string name="dashboard_address_editor_title">Gateway-Adresse</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_oidc_hint">Eine neue Adresse erhält dieses Gateway und seine Verlaufsverweise. Bei einem anderen Ursprung musst du dich erneut anmelden. OIDC-Rückrufe werden auf Hermes konfiguriert.</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Gib die Hermes-Gateway-Adresse ein</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
@@ -4610,4 +4611,9 @@
|
||||
<string name="voice_overlay_settings_hint">In beiden Versionen optional. Öffne den Sprachfokus im Chat und wähle Overlay. Berechtigungen allein starten kein Zuhören.</string>
|
||||
<string name="voice_overlay_reset_position">Position zurücksetzen</string>
|
||||
<string name="injected_context_gateway_unsupported">Wird im Gateway-Chat nicht gesendet. Diese Verbindung unterstützt keinen zusätzlichen Kontext pro Nachricht.</string>
|
||||
<string name="dashboard_http_risk">HTTP verschlüsselt Anfragen an %1$s nicht. Passwörter, Sitzungstoken und Unterhaltungen können offengelegt werden. Wenn du ein VPN nutzt, bist du dafür verantwortlich, dass der Verkehr darin bleibt, auch bei VPN-Ausfall. Die App erkennt oder erzwingt keinen VPN-Schutz.</string>
|
||||
<string name="dashboard_http_allow">Ich akzeptiere das Risiko und erlaube HTTP für diese Adresse</string>
|
||||
<string name="cw_auth_verified">Anmeldung bestätigt</string>
|
||||
<string name="cw_chat_checked_on_open">Wird beim Öffnen von Chat geprüft</string>
|
||||
<string name="dashboard_local_auth_help">Hermes ist erreichbar, aber geschützte Anfragen sind nicht autorisiert. Wird das Dashboard von Loopback weitergeleitet, prüfe Bind-Adresse, Authentifizierungsanbieter und dashboard.public_url auf dem Host. Ein 401 allein bestimmt die Ursache nicht.</string>
|
||||
</resources>
|
||||
|
||||
@@ -277,7 +277,7 @@
|
||||
<string name="cw_cloud_subtitle">Conéctate a tu agente alojado</string>
|
||||
<string name="cw_server_vps_title">Gateway remoto</string>
|
||||
<string name="cw_server_vps_subtitle">Introduce la dirección del Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Las direcciones privadas LAN y Tailscale pueden usar HTTP o HTTPS. Las direcciones públicas requieren HTTPS. Relay y la alternativa API son opcionales.</string>
|
||||
<string name="cw_relay_optional_note">Se recomienda HTTPS. Otras direcciones HTTP requieren aceptar el riesgo. La aplicación no impone protección VPN. Relay y Direct API son opcionales.</string>
|
||||
<string name="cw_cloud_entry_title">Conectarse a Hermes alojado por Nous</string>
|
||||
<string name="cw_cloud_entry_description">Introduce la dirección del agente que aparece en Nous Portal. Iniciarás sesión de forma segura después de encontrar Hermes.</string>
|
||||
<string name="cw_cloud_agent_name">Dirección del agente</string>
|
||||
@@ -285,7 +285,7 @@
|
||||
<string name="cw_cloud_slug_hint">Nos conectaremos a tu-agente.agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_slug_error">Introduce exactamente las letras, números y guiones anteriores a .agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_address_placeholder">https://tu-agente.example.com</string>
|
||||
<string name="cw_cloud_address_hint">Usa la dirección HTTPS completa que aparece para tu agente alojado.</string>
|
||||
<string name="cw_cloud_address_hint">Usa la dirección HTTPS completa que aparece para tu agente alojado, incluido :puerto si se proporciona.</string>
|
||||
<string name="cw_cloud_use_custom_address">Usar URL personalizada</string>
|
||||
<string name="cw_cloud_use_nous_address">Usar dirección alojada por Nous</string>
|
||||
<string name="cw_before_connecting">Antes de conectar</string>
|
||||
@@ -305,10 +305,10 @@
|
||||
<string name="cw_nearby_enter_address">Introducir la dirección</string>
|
||||
<string name="cw_other_connection_methods">Otros métodos de conexión</string>
|
||||
<string name="cw_manual_hermes_title">Introduce la dirección del gateway</string>
|
||||
<string name="cw_manual_hermes_description">Introduce la dirección del panel que abres en el navegador. Si no abre en este teléfono, inicia hermes dashboard y comprueba Wi-Fi o Tailscale.</string>
|
||||
<string name="cw_manual_hermes_description">Introduce la dirección del Dashboard que puedes abrir en este teléfono. Para LAN o VPN, el host necesita un Dashboard accesible y autenticación. Consulta la guía de configuración si el navegador no conecta.</string>
|
||||
<string name="cw_hermes_address">Dirección de Hermes</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 o hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">No se necesita una clave de API. Se usa el puerto 9119 si no incluyes uno.</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">Ejemplos: 192.168.1.10:9119 o https://hermes.example.com:10443. Si se omite, los hosts privados usan el puerto 9119 y HTTPS usa el 443. No se necesita clave API.</string>
|
||||
<string name="cw_find_hermes">Buscar Hermes</string>
|
||||
<string name="cw_hermes_found">Hermes encontrado</string>
|
||||
<string name="cw_ready_to_connect">Listo para conectar</string>
|
||||
@@ -331,12 +331,12 @@
|
||||
<string name="cw_skip_for_now">Saltar por ahora: configurar más tarde en Configuración</string>
|
||||
<string name="cw_back">Atrás</string>
|
||||
<string name="cw_connect_button">Conectar</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">Utilice esto para chatear y administrar. Empareje Relay más tarde solo cuando habilite Terminal, sesiones Bridge, Relay o concesiones. El inicio de sesión en el panel es la ruta de autenticación ascendente preferida; la clave API sigue siendo la alternativa del chat Android.</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API es una conexión de compatibilidad elegida explícitamente para el chat del servidor API. Manage, las sesiones del Dashboard y la voz estándar requieren iniciar sesión por separado en el Dashboard. No sustituye una conversación existente del Gateway.</string>
|
||||
<string name="cw_api_url_label">URL o host del servidor API</string>
|
||||
<string name="cw_api_key_label">Clave API</string>
|
||||
<string name="cw_api_key_placeholder">Valor de API_SERVER_KEY</string>
|
||||
<string name="cw_api_key_hint">Necesario para el chat Android hasta que se habilite el transporte gateway del panel.</string>
|
||||
<string name="cw_api_key_hint">Clave bearer solo para este servidor API. No inicia sesión en el Dashboard.</string>
|
||||
<string name="cw_tailscale_label">Acceso remoto: URL Tailscale (opcional)</string>
|
||||
<string name="cw_dashboard">Panel</string>
|
||||
<string name="cw_dashboard_routes_hint">Rutas: predeterminada primero, Tailscale alternativa cuando sea accesible.</string>
|
||||
@@ -350,7 +350,7 @@
|
||||
<string name="cw_update_button">Actualizar</string>
|
||||
<string name="cw_cancel">Cancelar</string>
|
||||
<string name="cw_method_hermes_title">Hermes</string>
|
||||
<string name="cw_method_hermes_subtitle">Configuración de API/dashboard para chat, administración, habilidades, cron, MCP, perfiles, modelos y configuraciones</string>
|
||||
<string name="cw_method_hermes_subtitle">Chat explícito del servidor API para instalaciones sin interfaz o de compatibilidad</string>
|
||||
<string name="cw_method_scan_title">Configuración de escaneo QR</string>
|
||||
<string name="cw_method_scan_subtitle">Escanee un QR con API URL/key para Hermes; Los detalles de Relay QR requieren el complemento Relay</string>
|
||||
<string name="cw_method_pair_code_title">Emparejar Relay por código</string>
|
||||
@@ -358,7 +358,7 @@
|
||||
<string name="cw_method_show_code_title">Mostrar código Relay</string>
|
||||
<string name="cw_method_show_code_subtitle">¿Sin cámara o QR? Registra el código de este teléfono en el anfitrión</string>
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 o http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">Hermes API utilizado por Chat y sesiones — API puerto 8642 y http:// asumido para hosts desnudos (el 9119 del tablero se deriva por separado)</string>
|
||||
<string name="cw_api_url_supporting">Dirección del servidor para el chat Direct API. Los hosts sin esquema usan HTTP y el puerto 8642.</string>
|
||||
<string name="cw_scan_message">Escaneando esta LAN en busca de Hermes dashboard/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">Inicie sesión a través del panel para desbloquear Administrar y voz: la clave API solo se usa para la alternativa directa opcional mediante API.</string>
|
||||
<string name="cw_pair_relay_section">Emparejar Relay (opcional)</string>
|
||||
@@ -448,7 +448,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">El anfitrión aún no ha aceptado este código de vinculación. Ejecuta el comando de emparejamiento en tu host Hermes (o vuelve a comprobar el código) y, a continuación, toca Reintentar.</string>
|
||||
<string name="cw_timeout_scan">Se agotó el tiempo antes de que el relay confirmara el emparejamiento. Compruebe que el relay se esté ejecutando y sea accesible en esta red y, a continuación, vuelva a intentarlo. Si el emparejamiento parece tener éxito pero aún no se puede acceder a Hermes, el servidor API puede estar detrás de un inicio de sesión gateway.</string>
|
||||
<string name="cw_timeout_other">Se agotó el tiempo de espera para el relay. Verifique que relay se esté ejecutando y que la URL sea correcta.</string>
|
||||
<string name="cw_camera_denied">Permiso de cámara denegado. En su lugar, empareje manualmente: elija \"Empareje Relay mediante el código\" o ingrese la URL de su servidor.</string>
|
||||
<string name="cw_camera_denied">Permiso de cámara denegado. Elige Gateway remoto e introduce la dirección del Dashboard. Los códigos de emparejamiento Relay están en Avanzado.</string>
|
||||
<string name="endpoints_no_routes_stored">No hay rutas almacenadas para esta conexión.</string>
|
||||
<string name="endpoints_add_route">Agregar ruta</string>
|
||||
<string name="endpoints_resolving">Resolviendo…</string>
|
||||
@@ -2551,6 +2551,7 @@
|
||||
<string name="model_picker_title">Modelo</string>
|
||||
<string name="model_picker_search">Buscar modelos o proveedores…</string>
|
||||
<string name="model_picker_empty">Ningún modelo coincide con tu búsqueda</string>
|
||||
<string name="model_picker_no_models">No hay modelos disponibles. Prueba a actualizar.</string>
|
||||
<string name="context_sheet_agent_sees">Lo que ve el agente</string>
|
||||
<string name="context_sheet_transparency">El contexto adicional exacto antepuesto a tu próximo turno, para mayor transparencia.</string>
|
||||
<string name="context_sheet_persona">Persona/perfil</string>
|
||||
@@ -3011,7 +3012,7 @@
|
||||
<string name="endpoints_pin_title">Puntos finales fijados</string>
|
||||
<string name="endpoints_route_editor_desc">Añada la dirección de Dashboard/Gateway que debe usar este teléfono en esa red.</string>
|
||||
<string name="endpoints_route_name_placeholder">Nombre de la ruta</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z o host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 o https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">Introduzca la dirección de Dashboard del servidor</string>
|
||||
<string name="endpoints_url_supporting_enter">Use una dirección de Dashboard http:// o https://</string>
|
||||
<string name="endpoints_url_supporting_preview">Se probará: %1$s</string>
|
||||
@@ -3274,16 +3275,16 @@
|
||||
<string name="cw_relay_pair_qr">Vincular Hermes Relay</string>
|
||||
<string name="cw_relay_pair_qr_desc">Escanea un QR de configuración de Relay</string>
|
||||
<string name="cw_relay_enter_code">Introducir código de vinculación</string>
|
||||
<string name="cw_dashboard_connected_title">Hermes está conectado</string>
|
||||
<string name="cw_dashboard_connected_body">Dashboard y Gateway están listos. Puedes empezar a chatear o abrir Manage.</string>
|
||||
<string name="cw_dashboard_connected_title">Acceso al Dashboard verificado</string>
|
||||
<string name="cw_dashboard_connected_body">Continúa a Chat. La conexión Gateway y la disponibilidad de voz se comprueban por separado.</string>
|
||||
<string name="cw_continue">Continuar</string>
|
||||
<string name="cw_timeline_discovered">Hermes encontrado</string>
|
||||
<string name="cw_timeline_discovered_detail">Identidad del Dashboard y endpoint de estado verificados</string>
|
||||
<string name="cw_timeline_discovered_detail">Estado del Dashboard obtenido</string>
|
||||
<string name="cw_timeline_access">Acceso al Dashboard</string>
|
||||
<string name="cw_timeline_access_ready">No se requiere otro inicio de sesión</string>
|
||||
<string name="cw_timeline_authenticated">Autenticación verificada</string>
|
||||
<string name="cw_timeline_ready">Conexión lista</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage y Voice pueden usar este Dashboard</string>
|
||||
<string name="cw_timeline_ready">Listo para continuar</string>
|
||||
<string name="cw_timeline_ready_detail">Chat conecta al abrirse; la voz se comprueba por separado</string>
|
||||
<string name="active_section_optional_api_fallback">Alternativa directa opcional mediante API</string>
|
||||
<string name="active_section_api_not_required">No es necesaria cuando esta conexión usa Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">¿Dónde obtengo esta clave?</string>
|
||||
@@ -4239,11 +4240,11 @@
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</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_body">Configura la dirección del Dashboard y Gateway de esta conexión. Incluye :puerto cuando sea necesario, por ejemplo 192.168.1.10:9119 o https://hermes.example.com:10443. Se recomienda HTTPS. Otras direcciones HTTP requieren aceptar expresamente el riesgo.</string>
|
||||
<string name="dashboard_address_editor_title">Dirección del gateway</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_oidc_hint">Cambiar la dirección conserva este gateway y sus referencias al historial, pero un origen distinto requiere volver a iniciar sesión. Las devoluciones OIDC se configuran en Hermes.</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Introduce la dirección del Gateway Hermes</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
@@ -4301,4 +4302,9 @@
|
||||
<string name="voice_overlay_settings_hint">Opcional en ambas versiones. Abre el enfoque de voz en Chat y elige Superposición. Los permisos por sí solos nunca inician la escucha.</string>
|
||||
<string name="voice_overlay_reset_position">Restablecer posición</string>
|
||||
<string name="injected_context_gateway_unsupported">No se envía en el chat de Gateway. Esta conexión no admite contexto adicional por turno.</string>
|
||||
<string name="dashboard_http_risk">HTTP no cifra las solicitudes a %1$s. Las contraseñas, los tokens de sesión y las conversaciones podrían quedar expuestos. Si dependes de una VPN, eres responsable de mantener el tráfico dentro de ella, incluso si falla. La aplicación no detecta ni impone protección VPN.</string>
|
||||
<string name="dashboard_http_allow">Acepto el riesgo y permito HTTP para esta dirección</string>
|
||||
<string name="cw_auth_verified">Inicio de sesión verificado</string>
|
||||
<string name="cw_chat_checked_on_open">Se verifica al abrir Chat</string>
|
||||
<string name="dashboard_local_auth_help">Hermes es accesible, pero las solicitudes protegidas no están autorizadas. Si el Dashboard se reenvía desde loopback, comprueba la dirección de escucha, el proveedor de autenticación y dashboard.public_url en el host. Un 401 por sí solo no identifica la causa.</string>
|
||||
</resources>
|
||||
|
||||
@@ -315,7 +315,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 と Direct API は任意です。</string>
|
||||
<string name="cw_relay_optional_note">HTTPS を推奨します。それ以外の HTTP アドレスには明示的なリスク同意が必要です。アプリは VPN 保護を強制しません。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>
|
||||
@@ -323,7 +323,7 @@
|
||||
<string name="cw_cloud_slug_hint">your-agent.agents.nousresearch.com に接続します。</string>
|
||||
<string name="cw_cloud_slug_error">.agents.nousresearch.com の前にある英字、数字、ハイフンを正確に入力してください。</string>
|
||||
<string name="cw_cloud_address_placeholder">https://your-agent.example.com</string>
|
||||
<string name="cw_cloud_address_hint">ホスト済みエージェントに表示される完全な HTTPS アドレスを使用してください。</string>
|
||||
<string name="cw_cloud_address_hint">ホスト済みエージェントに表示される完全な HTTPS アドレスを使用し、指定されている場合は :ポートも含めてください。</string>
|
||||
<string name="cw_cloud_use_custom_address">カスタム URL を使用</string>
|
||||
<string name="cw_cloud_use_nous_address">Nous ホスト版アドレスを使用</string>
|
||||
<string name="cw_before_connecting">接続する前に</string>
|
||||
@@ -343,10 +343,10 @@
|
||||
<string name="cw_nearby_enter_address">アドレスを入力</string>
|
||||
<string name="cw_other_connection_methods">その他の接続方法</string>
|
||||
<string name="cw_manual_hermes_title">ゲートウェイのアドレスを入力</string>
|
||||
<string name="cw_manual_hermes_description">ブラウザで開くダッシュボードアドレスを入力します。このスマートフォンで開けない場合は hermes dashboard を起動し、Wi-Fi または Tailscale を確認してください。</string>
|
||||
<string name="cw_manual_hermes_description">この端末のブラウザーで開ける Dashboard アドレスを入力してください。LAN や VPN では、ホストの Dashboard が到達可能で認証を設定済みである必要があります。接続できない場合はセットアップガイドを確認してください。</string>
|
||||
<string name="cw_hermes_address">Hermes アドレス</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 または hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">API キーは不要です。ポートを省略するとダッシュボードの 9119 番ポートを使用します。</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">例: 192.168.1.10:9119 または https://hermes.example.com:10443。省略した場合、プライベートホストはポート 9119、HTTPS はポート 443 を使用します。API キーは不要です。</string>
|
||||
<string name="cw_find_hermes">Hermes を検索</string>
|
||||
<string name="cw_hermes_found">Hermes が見つかりました</string>
|
||||
<string name="cw_ready_to_connect">接続できます</string>
|
||||
@@ -369,12 +369,12 @@
|
||||
<string name="cw_skip_for_now">今はスキップします — 後で [設定] で設定します</string>
|
||||
<string name="cw_back">戻る</string>
|
||||
<string name="cw_connect_button">接続する</string>
|
||||
<string name="cw_hermes_label">Hermes</string>
|
||||
<string name="cw_hermes_label_desc">チャットと管理に使用します。後でターミナル、Bridge、Relay セッション、または許可を有効にする場合にのみ、Relay をペアリングします。ダッシュボード サインインは、優先されるアップストリーム認証パスです。 API キーは Android チャット フォールバックのままです。</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API は、API サーバーのチャット用に明示的に選ぶ互換接続です。Manage、Dashboard のセッション、標準音声には別途 Dashboard へのサインインが必要です。既存の Gateway の会話を引き継ぐものではありません。</string>
|
||||
<string name="cw_api_url_label">API サーバー URL またはホスト</string>
|
||||
<string name="cw_api_key_label">API キー</string>
|
||||
<string name="cw_api_key_placeholder">API_SERVER_KEY の値</string>
|
||||
<string name="cw_api_key_hint">ダッシュボード Gateway トランスポートが有効になるまで、Android チャットに必要です。</string>
|
||||
<string name="cw_api_key_hint">この API サーバー専用の Bearer キーです。Dashboard へのサインインには使えません。</string>
|
||||
<string name="cw_tailscale_label">リモート アクセス — Tailscale URL (オプション)</string>
|
||||
<string name="cw_dashboard">ダッシュボード</string>
|
||||
<string name="cw_dashboard_routes_hint">ルート: 最初はデフォルト、到達可能な場合は Tailscale フォールバック。</string>
|
||||
@@ -390,7 +390,7 @@
|
||||
|
||||
<!-- Method tiles -->
|
||||
<string name="cw_method_hermes_title">Hermes</string>
|
||||
<string name="cw_method_hermes_subtitle">API/チャット、管理、スキル、Cron、MCP、プロファイル、モデル、設定のダッシュボード設定</string>
|
||||
<string name="cw_method_hermes_subtitle">ヘッドレス構成や互換用途で明示的に使う API サーバーチャット</string>
|
||||
<string name="cw_method_scan_title">スキャン設定 QR</string>
|
||||
<string name="cw_method_scan_subtitle">QR を API URL/キーで Hermes にスキャンします。 Relay QR の詳細には Relay プラグインが必要です</string>
|
||||
<string name="cw_method_pair_code_title">Relay をコードでペアリングする</string>
|
||||
@@ -400,7 +400,7 @@
|
||||
|
||||
<!-- Standard connect form -->
|
||||
<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_api_url_supporting">Direct API チャット用の API サーバーアドレス。ホスト名だけの場合は HTTP とポート 8642 を使います。</string>
|
||||
<string name="cw_scan_message">この LAN をスキャンして Hermes ダッシュボード/API を探しています…</string>
|
||||
<string name="cw_dashboard_signin_hint">ダッシュボード経由でサインインして、管理と音声のロックを解除します。API キーは明示的な Direct API 接続でのみ使います。</string>
|
||||
<string name="cw_pair_relay_section">Relay のペア (オプション)</string>
|
||||
@@ -495,7 +495,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">ホストはまだこのペアリング コードを受け入れていません。 Hermes ホストでペアリング コマンドを実行し (またはコードを再確認し)、[再試行] をタップします。</string>
|
||||
<string name="cw_timeout_scan">Relayがペアリングを確認する前にタイムアウトしました。Relayが実行中であり、このネットワーク上で到達可能であることを確認してから、再試行してください。ペアリングが成功したように見えても、Hermes にまだ到達できない場合は、API サーバーがログイン Gatewayの背後にある可能性があります。</string>
|
||||
<string name="cw_timeout_other">Relay待ちでタイムアウト。Relayが動作していること、URL が正しいことを確認してください。</string>
|
||||
<string name="cw_camera_denied">カメラの許可が拒否されました。代わりに手動でペアリングします。「コードで Relay をペアリング」を選択するか、サーバー URL を入力します。</string>
|
||||
<string name="cw_camera_denied">カメラの権限が拒否されました。リモート Gateway を選び、Dashboard アドレスを入力してください。Relay のペアリングコードは詳細設定にあります。</string>
|
||||
|
||||
<!-- EndpointsCard -->
|
||||
<string name="endpoints_no_routes_stored">この接続にはルートが保存されていません。</string>
|
||||
@@ -2796,6 +2796,7 @@
|
||||
<string name="model_picker_title">モデル</string>
|
||||
<string name="model_picker_search">モデルまたはプロバイダーを検索…</string>
|
||||
<string name="model_picker_empty">検索に一致するモデルはありません</string>
|
||||
<string name="model_picker_no_models">利用可能なモデルがありません。更新してください。</string>
|
||||
|
||||
<!-- InjectedContextSheet -->
|
||||
<string name="context_sheet_agent_sees">エージェントが見ているもの</string>
|
||||
@@ -3354,7 +3355,7 @@
|
||||
<string name="endpoints_pin_title">固定されたエンドポイント</string>
|
||||
<string name="endpoints_route_editor_desc">このネットワークで電話が使用する Dashboard/Gateway アドレスを追加します。</string>
|
||||
<string name="endpoints_route_name_placeholder">路線名</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z または host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 または https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">サーバーの Dashboard アドレスを入力します</string>
|
||||
<string name="endpoints_url_supporting_enter">http:// または https:// の Dashboard アドレスを使用します</string>
|
||||
<string name="endpoints_url_supporting_preview">テスト対象: %1$s</string>
|
||||
@@ -3581,16 +3582,16 @@
|
||||
<string name="cw_relay_pair_qr">Hermes Relay をペアリング</string>
|
||||
<string name="cw_relay_pair_qr_desc">Relay セットアップ QR をスキャン</string>
|
||||
<string name="cw_relay_enter_code">ペアリングコードを入力</string>
|
||||
<string name="cw_dashboard_connected_title">Hermes に接続しました</string>
|
||||
<string name="cw_dashboard_connected_body">Dashboard と Gateway の準備ができました。チャットを開始するか Manage を開けます。</string>
|
||||
<string name="cw_dashboard_connected_title">Dashboard アクセス確認済み</string>
|
||||
<string name="cw_dashboard_connected_body">Chat に進みます。Gateway 接続と音声の利用可否は別途確認します。</string>
|
||||
<string name="cw_continue">続行</string>
|
||||
<string name="cw_timeline_discovered">Hermes を検出</string>
|
||||
<string name="cw_timeline_discovered_detail">Dashboard の識別情報とステータスエンドポイントを確認済み</string>
|
||||
<string name="cw_timeline_discovered_detail">Dashboard の状態を取得しました</string>
|
||||
<string name="cw_timeline_access">Dashboard アクセス</string>
|
||||
<string name="cw_timeline_access_ready">追加のサインインは不要です</string>
|
||||
<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="cw_timeline_ready">続行できます</string>
|
||||
<string name="cw_timeline_ready_detail">Chat は開く際に接続し、音声の利用可否は別途確認します</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>
|
||||
@@ -4543,11 +4544,11 @@
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</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_body">この接続の Dashboard と Gateway のアドレスを設定します。必要に応じて :ポートを指定してください(例: 192.168.1.10:9119 または https://hermes.example.com:10443)。HTTPS を推奨します。それ以外の HTTP アドレスにはリスクへの明示的な同意が必要です。</string>
|
||||
<string name="dashboard_address_editor_title">ゲートウェイのアドレス</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_oidc_hint">アドレスを変更しても Gateway と履歴への参照は保持されますが、接続元が変わる場合は再サインインが必要です。OIDC コールバックは Hermes 側で設定します。</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Hermes Gateway のアドレスを入力してください</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
@@ -4605,4 +4606,9 @@
|
||||
<string name="voice_overlay_settings_hint">両方のビルドで任意に利用できます。チャットの音声フォーカスでオーバーレイを選択します。権限の付与だけで録音は始まりません。</string>
|
||||
<string name="voice_overlay_reset_position">位置をリセット</string>
|
||||
<string name="injected_context_gateway_unsupported">Gateway チャットでは送信されません。この接続はターンごとの追加コンテキストに対応していません。</string>
|
||||
<string name="dashboard_http_risk">HTTP は %1$s へのリクエストを暗号化しません。パスワード、セッショントークン、会話が露出する可能性があります。VPN に依存する場合、VPN 切断時も含め、通信を VPN 内に保つ責任は利用者にあります。アプリは VPN の保護を検出も強制もしません。</string>
|
||||
<string name="dashboard_http_allow">リスクを理解し、このアドレスで HTTP を許可します</string>
|
||||
<string name="cw_auth_verified">サインイン確認済み</string>
|
||||
<string name="cw_chat_checked_on_open">Chat を開く際に確認します</string>
|
||||
<string name="dashboard_local_auth_help">Hermes には到達できますが、保護されたリクエストが認可されていません。Dashboard をループバックから転送している場合は、ホストのバインドアドレス、認証プロバイダー、dashboard.public_url を確認してください。401 だけでは原因を特定できません。</string>
|
||||
</resources>
|
||||
|
||||
@@ -298,7 +298,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 и Direct API необязательны.</string>
|
||||
<string name="cw_relay_optional_note">Рекомендуется HTTPS. Для других HTTP-адресов нужно явно принять риск. Приложение не обеспечивает защиту VPN. 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>
|
||||
@@ -306,7 +306,7 @@
|
||||
<string name="cw_cloud_slug_hint">Будет выполнено подключение к ваш-агент.agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_slug_error">Точно введите буквы, цифры и дефисы перед .agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_address_placeholder">https://your-agent.example.com</string>
|
||||
<string name="cw_cloud_address_hint">Используйте полный HTTPS-адрес, указанный для вашего размещённого агента.</string>
|
||||
<string name="cw_cloud_address_hint">Используйте полный HTTPS-адрес, указанный для вашего размещённого агента, включая :порт, если он указан.</string>
|
||||
<string name="cw_cloud_use_custom_address">Использовать собственный URL</string>
|
||||
<string name="cw_cloud_use_nous_address">Использовать адрес хостинга Nous</string>
|
||||
<string name="cw_before_connecting">Перед подключением</string>
|
||||
@@ -333,10 +333,10 @@
|
||||
<string name="cw_relay_pair_qr_desc">Просканируйте QR-код настройки Relay</string>
|
||||
<string name="cw_relay_enter_code">Введите код сопоставления Relay</string>
|
||||
<string name="cw_manual_hermes_title">Введите адрес шлюза</string>
|
||||
<string name="cw_manual_hermes_description">Введите адрес панели управления, который вы открываете в браузере. Если он не открывается на этом телефоне, запустите панель управления Гермесом и проверьте Wi-Fi или Tailscale.</string>
|
||||
<string name="cw_manual_hermes_description">Введите адрес Dashboard, который открывается на этом телефоне. Для LAN или VPN на хосте нужен доступный Dashboard с аутентификацией. Если браузер не подключается, откройте руководство по настройке.</string>
|
||||
<string name="cw_hermes_address">Адрес Гермеса</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 или hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">API-ключ не требуется. Порт панели управления 9119 используется, если порт не указан.</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">Примеры: 192.168.1.10:9119 или https://hermes.example.com:10443. Если порт не указан, частные хосты используют 9119, а HTTPS — 443. Ключ API не нужен.</string>
|
||||
<string name="cw_find_hermes">Найти Гермеса</string>
|
||||
<string name="cw_hermes_found">Гермес найден</string>
|
||||
<string name="cw_ready_to_connect">Готов к подключению</string>
|
||||
@@ -346,16 +346,16 @@
|
||||
<string name="cw_could_not_verify">Не удалось проверить</string>
|
||||
<string name="cw_choose_another">Выбрать другой</string>
|
||||
<string name="cw_sign_in_to_hermes">Войти в Гермес</string>
|
||||
<string name="cw_dashboard_connected_title">Гермес подключен</string>
|
||||
<string name="cw_dashboard_connected_body">Панель управления и шлюз готовы. Вы можете начать чат или открыть управление.</string>
|
||||
<string name="cw_dashboard_connected_title">Доступ к Dashboard подтверждён</string>
|
||||
<string name="cw_dashboard_connected_body">Перейдите в чат. Подключение Gateway и доступность голоса проверяются отдельно.</string>
|
||||
<string name="cw_continue">Продолжить</string>
|
||||
<string name="cw_timeline_discovered">Обнаружен Гермес</string>
|
||||
<string name="cw_timeline_discovered_detail">Проверен идентификатор панели управления и endpoint состояния</string>
|
||||
<string name="cw_timeline_discovered_detail">Статус Dashboard получен</string>
|
||||
<string name="cw_timeline_access">Доступ к панели управления</string>
|
||||
<string name="cw_timeline_access_ready">Дополнительный вход не требуется</string>
|
||||
<string name="cw_timeline_authenticated">Аутентификация проверена</string>
|
||||
<string name="cw_timeline_ready">Подключение готово</string>
|
||||
<string name="cw_timeline_ready_detail">Чат, Управление и Голос могут использовать эту панель управления</string>
|
||||
<string name="cw_timeline_ready">Можно продолжить</string>
|
||||
<string name="cw_timeline_ready_detail">Чат подключается при открытии; голос проверяется отдельно</string>
|
||||
<string name="cw_semantics_hermes_available">Гермес доступен</string>
|
||||
<string name="cw_semantics_capability">%1$s: %2$s</string>
|
||||
<string name="cw_connect_description">Используйте эти параметры для совместимости только с API, настройки пользователя или альтернативного сопряжения Relay.</string>
|
||||
@@ -369,12 +369,12 @@
|
||||
<string name="cw_skip_for_now">Пропустить на данный момент — настроить позже в настройках</string>
|
||||
<string name="cw_back">Назад</string>
|
||||
<string name="cw_connect_button">Подключить</string>
|
||||
<string name="cw_hermes_label">Гермес</string>
|
||||
<string name="cw_hermes_label_desc">Используйте это для Чата и Управления. Сопрягайте плагин Relay позже только при включении Терминала, Моста, сессий Relay или разрешений. Вход на панели управления является предпочтительным способом аутентификации; ключ API остается резервным для Android Chat.</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API — явно выбранное совместимое подключение для чата API-сервера. Для Manage, сеансов Dashboard и стандартного голоса нужен отдельный вход в Dashboard. Существующий разговор Gateway не переносится в Direct API.</string>
|
||||
<string name="cw_api_url_label">URL или хост сервера API</string>
|
||||
<string name="cw_api_key_label">Ключ API</string>
|
||||
<string name="cw_api_key_placeholder">Значение из API_SERVER_KEY</string>
|
||||
<string name="cw_api_key_hint">Необходимо для Android Chat, пока не включен транспорт шлюза панели управления.</string>
|
||||
<string name="cw_api_key_hint">Bearer-ключ только для этого API-сервера. Он не выполняет вход в Dashboard.</string>
|
||||
<string name="cw_tailscale_label">Удалённый доступ — URL Tailscale (необязательно)</string>
|
||||
<string name="cw_dashboard">Панель управления</string>
|
||||
<string name="cw_dashboard_routes_hint">Маршруты: по умолчанию сначала, Tailscale при достижимости.</string>
|
||||
@@ -388,7 +388,7 @@
|
||||
<string name="cw_update_button">Обновить</string>
|
||||
<string name="cw_cancel">Отмена</string>
|
||||
<string name="cw_method_hermes_title">Подключение только через API</string>
|
||||
<string name="cw_method_hermes_subtitle">Совместимость и резервное копирование, когда Панель управления/Шлюз недоступны</string>
|
||||
<string name="cw_method_hermes_subtitle">Явно выбранный чат API-сервера для работы без интерфейса или совместимости</string>
|
||||
<string name="cw_method_scan_title">Сканирование QR-кода настройки</string>
|
||||
<string name="cw_method_scan_subtitle">Сканируйте QR-код с URL/ключом API для Гермеса; детали QR-кода Relay требуют плагина Relay</string>
|
||||
<string name="cw_method_pair_code_title">Сопряжение Relay по коду</string>
|
||||
@@ -396,7 +396,7 @@
|
||||
<string name="cw_method_show_code_title">Показать код Relay</string>
|
||||
<string name="cw_method_show_code_subtitle">Нет камеры или QR-кода? Зарегистрируйте код этого телефона на хосте</string>
|
||||
<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_api_url_supporting">Адрес API-сервера для чата Direct API. Для хоста без схемы используются HTTP и порт 8642.</string>
|
||||
<string name="cw_scan_message">Сканирование этой локальной сети на предмет панели управления/API Гермеса…</string>
|
||||
<string name="cw_dashboard_signin_hint">Войдите через панель управления, чтобы разблокировать Управление и голос — ключ API предназначен только для явно настроенного Direct API.</string>
|
||||
<string name="cw_pair_relay_section">Сопряжение Relay (необязательно)</string>
|
||||
@@ -491,7 +491,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">Хост ещё не принял этот код подключения. Запустите команду подключения на вашем хосте Гермеса (или проверьте код), затем нажмите Повторить.</string>
|
||||
<string name="cw_timeout_scan">Истекло время ожидания подтверждения подключения Relay. Проверьте, что Relay работает и доступно в этой сети, затем повторите. Если подключение кажется успешным, но Гермес всё ещё недоступен, сервер API может быть за брандмауэром.</string>
|
||||
<string name="cw_timeout_other">Истекло время ожидания ответа от Relay. Проверьте, что Relay работает и URL-адрес правильный.</string>
|
||||
<string name="cw_camera_denied">Доступ к камере запрещён. Подключитесь вручную — выберите "Подключить Relay по коду" или введите URL-адрес сервера.</string>
|
||||
<string name="cw_camera_denied">Доступ к камере запрещён. Выберите удалённый Gateway и введите адрес Dashboard. Коды сопряжения Relay доступны в дополнительных настройках.</string>
|
||||
<string name="endpoints_no_routes_stored">Нет сохранённых маршрутов для этого подключения.</string>
|
||||
<string name="endpoints_add_route">Добавить маршрут</string>
|
||||
<string name="endpoints_resolving">Разрешение…</string>
|
||||
@@ -2776,6 +2776,7 @@
|
||||
<string name="model_picker_title">Модель</string>
|
||||
<string name="model_picker_search">Поиск моделей или поставщиков\&#8230;</string>
|
||||
<string name="model_picker_empty">Нет моделей, соответствующих вашему запросу</string>
|
||||
<string name="model_picker_no_models">Нет доступных моделей. Попробуйте обновить список.</string>
|
||||
<string name="context_sheet_agent_sees">Что видит агент</string>
|
||||
<string name="context_sheet_transparency">Точный дополнительный контекст, добавляемый к вашему следующему ходу, для прозрачности.</string>
|
||||
<string name="context_sheet_persona">Персона / профиль</string>
|
||||
@@ -3215,7 +3216,7 @@
|
||||
<string name="endpoints_pin_title">Закрепленные конечные точки</string>
|
||||
<string name="endpoints_route_editor_desc">Добавьте адрес Dashboard/Gateway, который это устройство должно использовать в этой сети.</string>
|
||||
<string name="endpoints_route_name_placeholder">Название маршрута</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z или host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 или https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">Введите адрес Dashboard сервера</string>
|
||||
<string name="endpoints_url_supporting_enter">Используйте адрес Dashboard с http:// или https://</string>
|
||||
<string name="endpoints_url_supporting_preview">Будет протестировано: %1$s</string>
|
||||
@@ -4287,11 +4288,11 @@
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</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_body">Укажите адрес Dashboard и Gateway для этого подключения. При необходимости добавьте :порт, например 192.168.1.10:9119 или https://hermes.example.com:10443. Рекомендуется HTTPS. Для других HTTP-адресов необходимо явно принять риск.</string>
|
||||
<string name="dashboard_address_editor_title">Адрес шлюза</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_oidc_hint">Изменение адреса сохраняет шлюз и ссылки на историю, но другой источник требует повторного входа. Обратные вызовы OIDC настраиваются в Hermes.</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_required">Введите адрес Hermes Gateway</string>
|
||||
<string name="dashboard_gateway_configured">Configured address</string>
|
||||
@@ -4349,4 +4350,9 @@
|
||||
<string name="voice_overlay_settings_hint">Необязательно в обеих сборках. Откройте голосовой фокус в чате и выберите оверлей. Одни разрешения никогда не включают прослушивание.</string>
|
||||
<string name="voice_overlay_reset_position">Сбросить положение</string>
|
||||
<string name="injected_context_gateway_unsupported">Не отправляется в чате Gateway. Это подключение не поддерживает дополнительный контекст для каждого хода.</string>
|
||||
<string name="dashboard_http_risk">HTTP не шифрует запросы к %1$s. Пароли, токены сеансов и разговоры могут стать доступны посторонним. При использовании VPN вы отвечаете за то, чтобы трафик оставался в нём, в том числе при его отключении. Приложение не определяет и не обеспечивает защиту VPN.</string>
|
||||
<string name="dashboard_http_allow">Я принимаю риск и разрешаю HTTP для этого адреса</string>
|
||||
<string name="cw_auth_verified">Вход подтверждён</string>
|
||||
<string name="cw_chat_checked_on_open">Проверяется при открытии чата</string>
|
||||
<string name="dashboard_local_auth_help">Hermes доступен, но защищённые запросы не авторизованы. Если Dashboard перенаправляется с loopback, проверьте адрес прослушивания, провайдер аутентификации и dashboard.public_url на хосте. Сам по себе код 401 не определяет причину.</string>
|
||||
</resources>
|
||||
|
||||
@@ -349,7 +349,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 Direct API are optional.</string>
|
||||
<string name="cw_relay_optional_note">HTTPS is recommended. Other HTTP addresses need explicit risk acknowledgement. The app does not enforce VPN protection. 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>
|
||||
@@ -357,7 +357,7 @@
|
||||
<string name="cw_cloud_slug_hint">We’ll connect to your-agent.agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_slug_error">Enter the exact letters, numbers, and hyphens before .agents.nousresearch.com.</string>
|
||||
<string name="cw_cloud_address_placeholder">https://your-agent.example.com</string>
|
||||
<string name="cw_cloud_address_hint">Use the complete HTTPS address shown for your hosted agent.</string>
|
||||
<string name="cw_cloud_address_hint">Use the complete HTTPS address shown for your hosted agent, including :port if provided.</string>
|
||||
<string name="cw_cloud_use_custom_address">Use custom URL</string>
|
||||
<string name="cw_cloud_use_nous_address">Use Nous-hosted address</string>
|
||||
<string name="cw_before_connecting">Before you connect</string>
|
||||
@@ -384,10 +384,10 @@
|
||||
<string name="cw_relay_pair_qr_desc">Scan a Relay setup QR</string>
|
||||
<string name="cw_relay_enter_code">Enter a Relay pairing code</string>
|
||||
<string name="cw_manual_hermes_title">Enter gateway address</string>
|
||||
<string name="cw_manual_hermes_description">Enter the Dashboard address you open in a browser. If it does not open on this phone, start hermes dashboard and check Wi-Fi or Tailscale.</string>
|
||||
<string name="cw_manual_hermes_description">Enter the Dashboard address you can open on this phone. For LAN or VPN access, the host needs a reachable Dashboard and authentication. See the Setup Guide if the browser cannot connect.</string>
|
||||
<string name="cw_hermes_address">Hermes address</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10 or hermes.example.com</string>
|
||||
<string name="cw_hermes_address_hint">No API key is needed. Dashboard port 9119 is used when no port is included.</string>
|
||||
<string name="cw_hermes_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="cw_hermes_address_hint">Examples: 192.168.1.10:9119 or https://hermes.example.com:10443. If omitted, private hosts use port 9119 and HTTPS uses port 443. No API key is needed.</string>
|
||||
<string name="cw_find_hermes">Find Hermes</string>
|
||||
<string name="cw_hermes_found">Hermes found</string>
|
||||
<string name="cw_ready_to_connect">Ready to connect</string>
|
||||
@@ -397,16 +397,16 @@
|
||||
<string name="cw_could_not_verify">Couldn’t verify</string>
|
||||
<string name="cw_choose_another">Choose another</string>
|
||||
<string name="cw_sign_in_to_hermes">Sign in to Hermes</string>
|
||||
<string name="cw_dashboard_connected_title">Hermes is connected</string>
|
||||
<string name="cw_dashboard_connected_body">Dashboard and Gateway are ready. You can start chatting or open Manage.</string>
|
||||
<string name="cw_dashboard_connected_title">Dashboard access verified</string>
|
||||
<string name="cw_dashboard_connected_body">Continue to Chat. The Gateway connection and voice availability are checked separately.</string>
|
||||
<string name="cw_continue">Continue</string>
|
||||
<string name="cw_timeline_discovered">Hermes discovered</string>
|
||||
<string name="cw_timeline_discovered_detail">Dashboard identity and status endpoint verified</string>
|
||||
<string name="cw_timeline_discovered_detail">Dashboard status retrieved</string>
|
||||
<string name="cw_timeline_access">Dashboard access</string>
|
||||
<string name="cw_timeline_access_ready">No additional sign-in required</string>
|
||||
<string name="cw_timeline_authenticated">Authentication verified</string>
|
||||
<string name="cw_timeline_ready">Connection ready</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage, and Voice can use this Dashboard</string>
|
||||
<string name="cw_timeline_ready">Ready to continue</string>
|
||||
<string name="cw_timeline_ready_detail">Chat connects when opened; voice availability is checked separately</string>
|
||||
<string name="cw_semantics_hermes_available">Hermes available</string>
|
||||
<string name="cw_semantics_capability">%1$s: %2$s</string>
|
||||
<string name="cw_connect_description">Use these options for API-only compatibility, custom setup, or alternate Relay pairing.</string>
|
||||
@@ -420,12 +420,12 @@
|
||||
<string name="cw_skip_for_now">Skip for now — set up later in Settings</string>
|
||||
<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 standard upstream auth path; an API key is only for explicit Direct API connections.</string>
|
||||
<string name="cw_hermes_label">Direct API</string>
|
||||
<string name="cw_hermes_label_desc">Direct API is an explicit compatibility connection for API-server chat. Manage, Dashboard sessions, and standard voice require a separate Dashboard sign-in. It does not take over an existing Gateway conversation.</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>
|
||||
<string name="cw_api_key_hint">Needed for Android Chat until the dashboard gateway transport is enabled.</string>
|
||||
<string name="cw_api_key_hint">Bearer key for this API server only. It does not sign in to Dashboard.</string>
|
||||
<string name="cw_tailscale_label">Remote access — Tailscale URL (optional)</string>
|
||||
<string name="cw_dashboard">Dashboard</string>
|
||||
<string name="cw_dashboard_routes_hint">Routes: default first, Tailscale fallback when reachable.</string>
|
||||
@@ -441,7 +441,7 @@
|
||||
|
||||
<!-- Method tiles -->
|
||||
<string name="cw_method_hermes_title">API-only connection</string>
|
||||
<string name="cw_method_hermes_subtitle">Compatibility and fallback when Dashboard/Gateway is unavailable</string>
|
||||
<string name="cw_method_hermes_subtitle">Explicit API-server chat for headless or compatibility setups</string>
|
||||
<string name="cw_method_scan_title">Scan setup QR</string>
|
||||
<string name="cw_method_scan_subtitle">Scan a QR with API URL/key for Hermes; Relay QR details require the Relay plugin</string>
|
||||
<string name="cw_method_pair_code_title">Pair Relay by code</string>
|
||||
@@ -451,7 +451,7 @@
|
||||
|
||||
<!-- Standard connect form -->
|
||||
<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_api_url_supporting">API-server address for Direct API chat. Bare hosts use HTTP and port 8642.</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 optional Direct API compatibility.</string>
|
||||
<string name="cw_pair_relay_section">Pair Relay (optional)</string>
|
||||
@@ -561,7 +561,7 @@
|
||||
<string name="cw_timeout_entercode_showcode">The host hasn\'t accepted this pairing code yet. Run the pairing command on your Hermes host (or re-check the code), then tap Retry.</string>
|
||||
<string name="cw_timeout_scan">Timed out before the relay confirmed pairing. Check the relay is running and reachable on this network, then Retry. If pairing seems to succeed but Hermes still can\'t be reached, the API server may be behind a login gateway.</string>
|
||||
<string name="cw_timeout_other">Timed out waiting for the relay. Check that the relay is running and the URL is correct.</string>
|
||||
<string name="cw_camera_denied">Camera permission denied. Pair manually instead — choose \"Pair Relay by code\" or enter your server URL.</string>
|
||||
<string name="cw_camera_denied">Camera permission denied. Choose Remote gateway to enter the Dashboard address. Relay pairing codes are available under Advanced.</string>
|
||||
|
||||
<!-- EndpointsCard -->
|
||||
<string name="endpoints_no_routes_stored">No routes stored for this connection.</string>
|
||||
@@ -617,12 +617,12 @@
|
||||
<string name="endpoints_close">Close</string>
|
||||
<string name="endpoints_actions">Endpoint actions</string>
|
||||
<string name="dashboard_address_editor_title">Gateway address</string>
|
||||
<string name="dashboard_address_editor_body">Set the Dashboard and Gateway address this phone should use. Private LAN and Tailscale routes may use HTTP or HTTPS; public routes require HTTPS.</string>
|
||||
<string name="dashboard_address_editor_body">Set the Dashboard and Gateway address for this connection. Include :port when needed, for example 192.168.1.10:9119 or https://hermes.example.com:10443. HTTPS is recommended. Other HTTP addresses need your explicit risk acknowledgement.</string>
|
||||
<string name="dashboard_address_label">Dashboard & Gateway address</string>
|
||||
<string name="dashboard_address_placeholder">https://hermes.example.com</string>
|
||||
<string name="dashboard_address_placeholder">192.168.1.10:9119</string>
|
||||
<string name="dashboard_address_required">Enter your Hermes Gateway address</string>
|
||||
<string name="dashboard_address_preview">Will use: %1$s</string>
|
||||
<string name="dashboard_address_oidc_hint">Use any Dashboard address this phone can reach. OIDC callback settings are configured on Hermes; no second sign-in address is required here.</string>
|
||||
<string name="dashboard_address_oidc_hint">Changing the address preserves this gateway and its history references, but a different origin requires sign-in again. OIDC callbacks are configured on Hermes.</string>
|
||||
|
||||
<!-- BridgeMasterToggle -->
|
||||
<string name="bmt_agent_control">Agent Control</string>
|
||||
@@ -3180,6 +3180,7 @@
|
||||
<string name="model_picker_title">Model</string>
|
||||
<string name="model_picker_search">Search models or providers…</string>
|
||||
<string name="model_picker_empty">No models match your search</string>
|
||||
<string name="model_picker_no_models">No models available. Try Refresh.</string>
|
||||
|
||||
<!-- InjectedContextSheet -->
|
||||
<string name="context_sheet_agent_sees">What the agent sees</string>
|
||||
@@ -3745,7 +3746,7 @@
|
||||
<string name="endpoints_pin_title">Pinned endpoints</string>
|
||||
<string name="endpoints_route_editor_desc">Add the Dashboard/Gateway address this phone should use on that network.</string>
|
||||
<string name="endpoints_route_name_placeholder">Route name</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z or host.ts.net</string>
|
||||
<string name="endpoints_url_host_placeholder">100.x.y.z:9119 or https://host.ts.net:10443</string>
|
||||
<string name="endpoints_url_supporting_blank">Enter the server’s Dashboard address</string>
|
||||
<string name="endpoints_url_supporting_enter">Use an http:// or https:// Dashboard address</string>
|
||||
<string name="endpoints_url_supporting_preview">Will test: %1$s</string>
|
||||
@@ -4668,4 +4669,9 @@
|
||||
<string name="voice_overlay_settings_hint">Optional in both builds. Open Voice Focus in Chat and choose Overlay to start. Permissions alone never start listening.</string>
|
||||
<string name="voice_overlay_reset_position">Reset position</string>
|
||||
<string name="injected_context_gateway_unsupported">Not sent in Gateway chat. This connection does not support extra per-turn context.</string>
|
||||
<string name="dashboard_http_risk">HTTP does not encrypt requests to %1$s. Passwords, session tokens, and conversations may be exposed. If you rely on a VPN, you are responsible for keeping traffic inside it, including after VPN loss. The app does not detect or enforce VPN protection.</string>
|
||||
<string name="dashboard_http_allow">I accept the risk and allow HTTP for this address</string>
|
||||
<string name="cw_auth_verified">Sign-in verified</string>
|
||||
<string name="cw_chat_checked_on_open">Verified when Chat opens</string>
|
||||
<string name="dashboard_local_auth_help">Hermes is reachable, but protected requests are not authorized. If this Dashboard is forwarded from loopback, check its bind address, authentication provider, and dashboard.public_url on the host. A 401 alone does not identify the cause.</string>
|
||||
</resources>
|
||||
|
||||
@@ -6,6 +6,15 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ConnectionCapabilitiesTest {
|
||||
@Test
|
||||
fun emptySetupPlaceholderRetainsGatewayIntentBeforeAddressIsSaved() {
|
||||
val placeholder = connection(dashboardUrl = null, apiServerUrl = "", relayUrl = "")
|
||||
assertEquals(SessionTransport.GATEWAY, placeholder.automaticChatTransport)
|
||||
assertEquals(SessionTransport.GATEWAY, placeholder.chatTransportForPreference("auto"))
|
||||
assertEquals(SessionTransport.SSE, placeholder.chatTransportForPreference("completions"))
|
||||
assertEquals(SessionTransport.SSE, placeholder.copy(apiServerUrl = "http://127.0.0.1:8642").automaticChatTransport)
|
||||
assertEquals(SessionTransport.GATEWAY, placeholder.copy(dashboardUrl = "https://gateway.example.test").automaticChatTransport)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardOnlyConnection_exposesStandardHermesCapabilities() {
|
||||
|
||||
@@ -329,6 +329,22 @@ class ConnectionDashboardFieldsTest {
|
||||
assertEquals("http://100.75.1.2:9119", Connection.normalizeDashboardUrlInput("100.75.1.2"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeDashboardUrlInput_preservesExplicitPorts() {
|
||||
assertEquals(
|
||||
"http://homelab.lan:9443",
|
||||
Connection.normalizeDashboardUrlInput("homelab.lan:9443"),
|
||||
)
|
||||
assertEquals(
|
||||
"https://hermes.example.com:10443",
|
||||
Connection.normalizeDashboardUrlInput("hermes.example.com:10443"),
|
||||
)
|
||||
assertEquals(
|
||||
"https://hermes.example.com:10443",
|
||||
Connection.normalizeDashboardUrlInput("https://hermes.example.com:10443"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun discoveredLabel_prefersHostnameForAnUncustomizedIpLabel() {
|
||||
assertEquals(
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.isNativeDashboardTransportEligible
|
||||
import com.hermesandroid.relay.network.upstream.trustedDashboardBearerAuthOrNull
|
||||
import com.hermesandroid.relay.network.upstream.dashboardClientWithHttpConsent
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import com.hermesandroid.relay.viewmodel.publicDashboardAddressRequiresHttps
|
||||
import io.mockk.mockk
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class DashboardHttpConsentTest {
|
||||
private val address = "http://11.0.0.1:9119"
|
||||
private val consent = setOf(address)
|
||||
|
||||
@Test fun consentDoesNotFollowRedirectsToAnotherOrigin() {
|
||||
MockWebServer().use { first ->
|
||||
MockWebServer().use { second ->
|
||||
first.enqueue(MockResponse().setResponseCode(307).setHeader("Location", second.url("/capture")))
|
||||
val base = first.url("/").toString().trimEnd('/')
|
||||
val client = dashboardClientWithHttpConsent(OkHttpClient(), base, setOf(base))
|
||||
try {
|
||||
client.newCall(Request.Builder().url(first.url("/api/auth/me"))
|
||||
.header("Authorization", "Bearer synthetic-fixture").build()).execute().use {
|
||||
assertEquals(307, it.code)
|
||||
}
|
||||
assertEquals(0, second.requestCount)
|
||||
} finally {
|
||||
client.connectionPool.evictAll()
|
||||
client.dispatcher.executorService.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun publicHttpRequiresExplicitExactOriginConsent() {
|
||||
assertTrue(publicDashboardAddressRequiresHttps(null, address))
|
||||
assertFalse(publicDashboardAddressRequiresHttps(null, address, consent))
|
||||
assertTrue(publicDashboardAddressRequiresHttps("lan", "http://11.0.0.2:9119", consent))
|
||||
assertTrue(publicDashboardAddressRequiresHttps(null, "http://11.0.0.1:9120", consent))
|
||||
assertNull(dashboardHttpOrigin("http://user:password@11.0.0.1:9119"))
|
||||
assertNull(dashboardHttpOrigin("http://11.0.0.1:9119?token=untrusted"))
|
||||
assertFalse(dashboardHttpConsentRequired("https://11.0.0.1:9119"))
|
||||
assertFalse(dashboardHttpConsentRequired("http://192.168.1.5:9119"))
|
||||
}
|
||||
|
||||
@Test fun persistedConsentBelongsToOneConnectionAndDoesNotChangeSecurityClassification() {
|
||||
val connection = Connection("one", "Gateway", "", "", "one-key",
|
||||
dashboardUrl = address, dashboardHttpConsentOrigins = consent)
|
||||
val restored = Json.decodeFromString<Connection>(Json.encodeToString(connection)).withDashboardDefaults()
|
||||
assertEquals(consent, restored.dashboardHttpConsentOrigins)
|
||||
assertTrue(dashboardHttpConsentMatches(address, restored.dashboardHttpConsentOrigins))
|
||||
assertFalse(dashboardHttpConsentMatches(address, Connection("two", "Other", "", "", "two-key").dashboardHttpConsentOrigins))
|
||||
assertEquals("public", Connection.inferRouteRole(address))
|
||||
assertFalse(isTlsUrl(address))
|
||||
}
|
||||
|
||||
@Test fun changingAnOriginRequiresFreshConsentAndRetiresTheOldException() {
|
||||
val next = "http://11.0.0.2:9119"
|
||||
assertEquals(emptySet<String>(), updatedDashboardHttpConsents(consent, address, next, null))
|
||||
assertEquals(setOf(next), updatedDashboardHttpConsents(consent, address, next, next))
|
||||
assertEquals(emptySet<String>(), updatedDashboardHttpConsents(consent, address, "https://11.0.0.1:9119", null))
|
||||
assertEquals(consent, updatedDashboardHttpConsents(consent, address, "$address/prefix", null))
|
||||
}
|
||||
|
||||
@Test fun nativeAuthenticationUsesTheSameConsentWithoutTrustingOtherBases() {
|
||||
assertFalse(isNativeDashboardTransportEligible(address))
|
||||
assertTrue(isNativeDashboardTransportEligible(address, consent))
|
||||
assertFalse(isNativeDashboardTransportEligible("http://11.0.0.2:9119", consent))
|
||||
assertNull(normalizeCredentialFreeAuthenticatedDashboardOrigin(address))
|
||||
assertEquals(address, normalizeCredentialFreeAuthenticatedDashboardOrigin(address, consent))
|
||||
assertNotNull(trustedDashboardBearerAuthOrNull(address, address, consent) { mockk(relaxed = true) })
|
||||
assertNull(trustedDashboardBearerAuthOrNull("http://11.0.0.2:9119", address, consent) { error("Must not load credentials") })
|
||||
assertNull(trustedDashboardBearerAuthOrNull("$address/other", "$address/hermes", consent) { error("Must not load credentials") })
|
||||
}
|
||||
}
|
||||
@@ -44,11 +44,20 @@ class ProviderUsagePreferencesTest {
|
||||
val preferences = repository.preferences.first()
|
||||
assertEquals(ProviderUsageLandingMode.Summary, preferences.landingMode)
|
||||
assertEquals(
|
||||
setOf("openai-codex", "nous", "opencode-go"),
|
||||
setOf("openai-codex", "nous", "opencode-go", "supergrok"),
|
||||
preferences.visibleProviders,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun existingInstallWithoutProviderChoiceGetsCurrentDefaults() = runTest {
|
||||
repository.setLandingMode(ProviderUsageLandingMode.Expanded)
|
||||
|
||||
val preferences = repository.preferences.first()
|
||||
assertEquals(ProviderUsageLandingMode.Expanded, preferences.landingMode)
|
||||
assertTrue("supergrok" in preferences.visibleProviders)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistsDisplayMode() = runTest {
|
||||
repository.setLandingMode(ProviderUsageLandingMode.Expanded)
|
||||
@@ -66,4 +75,13 @@ class ProviderUsagePreferencesTest {
|
||||
assertTrue("openai-codex" in preferences.visibleProviders)
|
||||
assertTrue("opencode-go" in preferences.visibleProviders)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistsSuperGrokHiddenChoice() = runTest {
|
||||
repository.setProviderVisible("supergrok", false)
|
||||
|
||||
val preferences = repository.preferences.first()
|
||||
assertTrue("nous" in preferences.visibleProviders)
|
||||
assertFalse("supergrok" in preferences.visibleProviders)
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -48,6 +48,15 @@ class ProactiveMessageHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `notification previews omit media markers while thread text remains complete`() {
|
||||
val text = "Headline\nDetail\nMEDIA:hermes-relay://private-token-123456\nMEDIA:/tmp/report.png"
|
||||
assertEquals("Headline Detail", mediaFreeProactivePreview(text))
|
||||
assertEquals("Attachment", mediaFreeProactivePreview("MEDIA:hermes-relay://private-token-123456"))
|
||||
val fenced = "Example\n```\nMEDIA:/tmp/example.png\n```"
|
||||
assertTrue(mediaFreeProactivePreview(fenced).contains("MEDIA:/tmp/example.png"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `inbox surfacing persists silently`() {
|
||||
val persisted = mutableListOf<ProactiveMessage>()
|
||||
|
||||
+29
@@ -78,6 +78,35 @@ class RelayHttpClientDiagnosticsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun secureLinkHealthWithoutVersionStillSucceeds() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.enqueue(
|
||||
MockResponse().setResponseCode(200).setBody(
|
||||
"""{"status":"ok","surface":"hermes_secure_proxy","security":"pinned_tls"}""",
|
||||
),
|
||||
)
|
||||
server.start()
|
||||
try {
|
||||
val configuredRelay = "ws://${server.hostName}:${server.port}/relay/ws"
|
||||
val client = RelayHttpClient(
|
||||
okHttpClient = OkHttpClient(),
|
||||
relayUrlProvider = { configuredRelay },
|
||||
sessionTokenProvider = { null },
|
||||
)
|
||||
|
||||
val result = client.probeHealth(configuredRelay)
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals("secure-link", result.getOrNull()?.version)
|
||||
assertTrue(
|
||||
DiagnosticsLog.recent(setOf(DiagnosticCategory.Relay))
|
||||
.none { it.detail == "Missing version field" },
|
||||
)
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardIngressUsesOuterAuthClientAndSeparateRelayHeader() = runTest {
|
||||
val server = MockWebServer()
|
||||
|
||||
+23
@@ -73,6 +73,29 @@ class RelayVoiceClientRoutingTest {
|
||||
runCatching { tailscaleServer.shutdown() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun proxyProviderOwnsBothVoiceSessionAndWebSocketRequests() = runTest {
|
||||
val selected = Collections.synchronizedList(mutableListOf<String>())
|
||||
val requests = Collections.synchronizedList(mutableListOf<String>())
|
||||
val proxyClient = httpClient.newBuilder().addInterceptor { chain ->
|
||||
requests.add(chain.request().url.encodedPath)
|
||||
chain.proceed(chain.request())
|
||||
}.build()
|
||||
val client = RelayVoiceClient(
|
||||
context = context,
|
||||
okHttpClient = httpClient.newBuilder().addInterceptor {
|
||||
throw IOException("generic client must not handle this route")
|
||||
}.build(),
|
||||
relayUrlProvider = { relayUrl(lanServer) },
|
||||
sessionTokenProvider = { "session-token" },
|
||||
pluginProxyHttpClientProvider = { url -> selected.add(url); proxyClient },
|
||||
)
|
||||
val result = client.runVoiceOutput("Pinned route") {}
|
||||
assertTrue(result.exceptionOrNull()?.message, result.isSuccess)
|
||||
assertEquals(listOf("/voice/output/session", "/voice/output/session-test"), requests)
|
||||
assertTrue(selected.any { it.endsWith("/voice/output/session-test") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun realtimeAgentAndVoiceOutputFollowSameEffectiveRelayUrlProvider() = runTest {
|
||||
var activeRelayUrl = relayUrl(lanServer)
|
||||
|
||||
+79
@@ -1,6 +1,23 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import com.hermesandroid.relay.data.ProxyEndpoint
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import java.security.MessageDigest
|
||||
import java.security.PublicKey
|
||||
import java.security.cert.CertificateException
|
||||
import java.security.cert.X509Certificate
|
||||
import java.util.Base64
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.net.ssl.X509TrustManager
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -9,6 +26,68 @@ import org.junit.Test
|
||||
class PluginProxyTransportTest {
|
||||
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
|
||||
|
||||
@Test
|
||||
fun `system trust never bypasses the paired leaf pin`() {
|
||||
val key = mockk<PublicKey>()
|
||||
every { key.encoded } returns byteArrayOf(1, 2, 3)
|
||||
val leaf = mockk<X509Certificate>(relaxed = true)
|
||||
every { leaf.publicKey } returns key
|
||||
val matchingPin = "sha256/" + Base64.getEncoder().encodeToString(
|
||||
MessageDigest.getInstance("SHA-256").digest(key.encoded),
|
||||
)
|
||||
for (systemAccepted in listOf(true, false)) {
|
||||
val system = mockk<X509TrustManager>(relaxed = true)
|
||||
if (!systemAccepted) {
|
||||
every { system.checkServerTrusted(any(), any()) } throws CertificateException("untrusted")
|
||||
}
|
||||
PinnedOrSystemTrustManager(system, matchingPin).checkServerTrusted(arrayOf(leaf), "RSA")
|
||||
assertThrows(CertificateException::class.java) {
|
||||
PinnedOrSystemTrustManager(system, pin).checkServerTrusted(arrayOf(leaf), "RSA")
|
||||
}
|
||||
assertThrows(CertificateException::class.java) {
|
||||
PinnedOrSystemTrustManager(system, matchingPin).checkServerTrusted(emptyArray(), "RSA")
|
||||
}
|
||||
}
|
||||
val rejectingSystem = mockk<X509TrustManager>()
|
||||
every { rejectingSystem.checkServerTrusted(any(), any()) } throws CertificateException("untrusted")
|
||||
every { leaf.checkValidity() } throws CertificateException("expired")
|
||||
assertThrows(CertificateException::class.java) {
|
||||
PinnedOrSystemTrustManager(rejectingSystem, matchingPin).checkServerTrusted(arrayOf(leaf), "RSA")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `authority guard rejects HTTP and WebSocket before credentials or network`() {
|
||||
var credentialsRead = false
|
||||
val client = buildPluginProxyClient(
|
||||
OkHttpClient.Builder(),
|
||||
ProxyEndpoint("https://paired.invalid:9443", pinSha256 = pin).toPluginProxyRoutesOrNull()!!,
|
||||
sessionTokenProvider = { credentialsRead = true; "session-token" },
|
||||
)
|
||||
assertFalse(client.followRedirects)
|
||||
assertFalse(client.followSslRedirects)
|
||||
for (url in listOf("http://paired.invalid:9443/relay", "https://other.invalid:9443/relay", "https://paired.invalid:9444/relay")) {
|
||||
val failure = assertThrows(java.io.IOException::class.java) {
|
||||
client.newCall(Request.Builder().url(url).build()).execute().close()
|
||||
}
|
||||
assertTrue(failure.message.orEmpty().contains("paired authority"))
|
||||
}
|
||||
val failed = CountDownLatch(1)
|
||||
var socketFailure: Throwable? = null
|
||||
client.newWebSocket(Request.Builder().url("wss://paired.invalid:9444/relay/ws").build(),
|
||||
object : WebSocketListener() {
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
socketFailure = t
|
||||
failed.countDown()
|
||||
}
|
||||
},
|
||||
)
|
||||
assertTrue(failed.await(3, TimeUnit.SECONDS))
|
||||
assertTrue(socketFailure?.message.orEmpty().contains("paired authority"))
|
||||
assertFalse(credentialsRead)
|
||||
client.dispatcher.executorService.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `derives all proxy surfaces from one authority`() {
|
||||
val routes = ProxyEndpoint(
|
||||
|
||||
@@ -182,6 +182,49 @@ class ChatHandlerTest {
|
||||
assertTrue(handler.messages.value.single().content.contains("MEDIA:/tmp/example.pdf"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun proactiveThreadMessage_dispatchesMediaAfterInsertionAndPreservesTextLines() {
|
||||
val tokens = mutableListOf<Pair<String, String>>()
|
||||
val paths = mutableListOf<Pair<String, String>>()
|
||||
handler.onMediaAttachmentRequested = { id, token ->
|
||||
assertTrue(handler.messages.value.any { it.id == id })
|
||||
tokens += id to token
|
||||
}
|
||||
handler.onMediaBarePathRequested = { id, path -> paths += id to path }
|
||||
|
||||
val content = "Headline\nDetail one\n\nMEDIA:hermes-relay://tok123\nDetail two\nMEDIA:/tmp/report.png"
|
||||
handler.addAgentThreadMessage(content, "push-1", "Agent")
|
||||
handler.addAgentThreadMessage(content, "push-1", "Agent")
|
||||
|
||||
assertEquals(1, handler.messages.value.size)
|
||||
assertEquals("Headline\nDetail one\n\nDetail two", handler.messages.value.single().content)
|
||||
assertEquals(listOf("proactive-push-1" to "tok123"), tokens)
|
||||
assertEquals(listOf("proactive-push-1" to "/tmp/report.png"), paths)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun proactiveThreadMessage_keepsFencedAndProseMediaExamples() {
|
||||
val tokens = mutableListOf<String>()
|
||||
handler.onMediaAttachmentRequested = { _, token -> tokens += token }
|
||||
val content = "Intro\n```\nMEDIA:hermes-relay://example123\n```\nExample: MEDIA:hermes-relay://example456"
|
||||
|
||||
handler.addAgentThreadMessage(content, "push-2", null)
|
||||
|
||||
assertEquals(content, handler.messages.value.single().content)
|
||||
assertTrue(tokens.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun proactiveThreadMessage_doesNotRemoveIdenticalMarkerInsideCodeFence() {
|
||||
val tokens = mutableListOf<String>()
|
||||
handler.onMediaAttachmentRequested = { _, token -> tokens += token }
|
||||
val marker = "MEDIA:hermes-relay://same-token-123456"
|
||||
handler.addAgentThreadMessage("Text\n```\n$marker\n```\n$marker", "push-3", null)
|
||||
|
||||
assertEquals("Text\n```\n$marker\n```", handler.messages.value.single().content)
|
||||
assertEquals(listOf("same-token-123456"), tokens)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onTextDelta_setsStreamingFlag() {
|
||||
handler.onTextDelta("assist-1", "delta")
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import java.io.IOException
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class DashboardSetupVerificationTest {
|
||||
private val server = MockWebServer()
|
||||
private val client = DashboardApiClient(server.url("/").toString().trimEnd('/'))
|
||||
@After fun close() { client.shutdown(); server.shutdown() }
|
||||
private fun response(body: String, code: Int = 200) = server.enqueue(MockResponse().setResponseCode(code).setBody(body))
|
||||
|
||||
@Test fun publicStatusDoesNotAuthorizeLoopbackProtectedRoutes() = runTest {
|
||||
response("""{"auth_required":false}""")
|
||||
response("""{"detail":"Unauthorized"}""", 401)
|
||||
assertTrue(runCatching { client.verifySetup() }.exceptionOrNull() is DashboardLocalAuthenticationRequiredException)
|
||||
assertEquals("/api/status", server.takeRequest().path)
|
||||
assertEquals("/api/auth/me", server.takeRequest().path)
|
||||
assertEquals(2, server.requestCount)
|
||||
}
|
||||
|
||||
@Test fun ordinaryExpiredSessionRequestsSignInWithoutClaimingMisconfiguration() = runTest {
|
||||
response("""{"auth_required":true}""")
|
||||
response("""{"error":"session_expired"}""", 401)
|
||||
val result = client.verifySetup()
|
||||
assertFalse(result.authenticated)
|
||||
assertFalse(result.ticketAvailable)
|
||||
assertTrue(result.status.authRequired)
|
||||
assertEquals(2, server.requestCount)
|
||||
}
|
||||
|
||||
@Test fun successfulRetryProvesSessionAndTicketOnTheSameDashboard() = runTest {
|
||||
response("""{"auth_required":true}""")
|
||||
response("""{"detail":"Unauthorized"}""", 401)
|
||||
assertFalse(client.verifySetup().authenticated)
|
||||
response("""{"auth_required":true}""")
|
||||
response("""{"authenticated":true,"username":"fixture"}""")
|
||||
response("""{"ticket":"fixture-ticket","ttl_seconds":30}""")
|
||||
assertTrue(client.verifySetup().authenticated)
|
||||
val paths = (1..5).map { server.takeRequest().path }
|
||||
assertEquals(listOf("/api/status", "/api/auth/me", "/api/status", "/api/auth/me", "/api/auth/ws-ticket"), paths)
|
||||
}
|
||||
|
||||
@Test fun ticketTransportFailureCannotProduceReady() = runTest {
|
||||
response("""{"auth_required":true}""")
|
||||
response("""{"authenticated":true}""")
|
||||
response("""{"detail":"temporarily unavailable"}""", 503)
|
||||
assertTrue(runCatching { client.verifySetup() }.exceptionOrNull() is IOException)
|
||||
}
|
||||
|
||||
@Test fun expiryBetweenSessionVerificationAndTicketReturnsToSignIn() = runTest {
|
||||
response("""{"auth_required":true}""")
|
||||
response("""{"authenticated":true}""")
|
||||
response("""{"error":"session_expired"}""", 401)
|
||||
assertFalse(client.verifySetup().authenticated)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import kotlinx.serialization.json.put
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
@@ -2087,6 +2088,85 @@ class GatewayChatClientTest {
|
||||
assertEquals(GatewayReconnectDisposition.Terminal, client.reconnectDisposition.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active route retarget replaces socket policy and preserves the live turn`() {
|
||||
val replacement = GatewayClientHarness()
|
||||
fun dashboardFor(target: GatewayClientHarness): DashboardApiClient = DashboardApiClient(
|
||||
baseUrl = target.server.url("/").toString(),
|
||||
okHttpClient = OkHttpClient.Builder().addInterceptor { chain ->
|
||||
if (chain.request().url.port != target.server.port) {
|
||||
throw java.io.IOException("transport belongs to another paired authority")
|
||||
}
|
||||
chain.proceed(chain.request())
|
||||
}.build(),
|
||||
)
|
||||
client.shutdown()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
client = GatewayChatClient(
|
||||
initialDashboardClient = dashboardFor(harness),
|
||||
scope = scope,
|
||||
callbackDispatcher = { it() },
|
||||
midTurnRejoinWindowMs = 3_000L,
|
||||
)
|
||||
try {
|
||||
val recorder = Recorder()
|
||||
client.sendTurn(null, "follow the route", null, recorder.callbacks) {
|
||||
recorder.preflightFailures += it
|
||||
}
|
||||
harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
client.retarget(dashboardFor(replacement))
|
||||
val moved = replacement.awaitServerSocket()
|
||||
val activation = replacement.awaitRpc("session.activate")
|
||||
assertEquals("live-1", activation["session_id"]?.jsonPrimitive?.content)
|
||||
moved.send(replacement.eventFrame("message.complete", buildJsonObject {
|
||||
put("text", "Finished on the new route")
|
||||
}, "live-1"))
|
||||
assertTrue(recorder.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(recorder.errors.isEmpty())
|
||||
assertTrue(recorder.preflightFailures.isEmpty())
|
||||
assertFalse(replacement.rpcLog.any { it.first == "prompt.submit" })
|
||||
} finally {
|
||||
client.shutdown()
|
||||
replacement.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `retarget during ticket mint discards old ticket before socket upgrade`() = runBlocking {
|
||||
val replacement = GatewayClientHarness()
|
||||
val mintStarted = CountDownLatch(1)
|
||||
val releaseMint = CountDownLatch(1)
|
||||
val oldTransport = OkHttpClient.Builder().addInterceptor { chain ->
|
||||
val response = chain.proceed(chain.request())
|
||||
if (chain.request().url.encodedPath.endsWith("/ws-ticket")) {
|
||||
mintStarted.countDown()
|
||||
check(releaseMint.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
response
|
||||
}.build()
|
||||
client.shutdown()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
client = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(harness.server.url("/").toString(), oldTransport),
|
||||
scope = scope,
|
||||
callbackDispatcher = { it() },
|
||||
)
|
||||
try {
|
||||
val pending = async(Dispatchers.IO) { client.prewarmAwait("stored-session") }
|
||||
assertTrue(mintStarted.await(3, TimeUnit.SECONDS))
|
||||
client.retarget(DashboardApiClient(replacement.server.url("/").toString()))
|
||||
releaseMint.countDown()
|
||||
assertTrue(pending.await())
|
||||
assertEquals(1, replacement.ticketMints.get())
|
||||
assertTrue("old ticket must never dial a socket", harness.serverSockets.isEmpty())
|
||||
} finally {
|
||||
releaseMint.countDown()
|
||||
client.shutdown()
|
||||
replacement.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `each connect attempt mints a fresh ticket`() {
|
||||
val r1 = Recorder()
|
||||
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.app.NotificationManager
|
||||
import android.os.Build
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.preferencesOf
|
||||
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
|
||||
import com.hermesandroid.relay.data.relayDataStore
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.slot
|
||||
import io.mockk.spyk
|
||||
import io.mockk.mockkStatic
|
||||
import io.mockk.unmockkAll
|
||||
import io.mockk.verify
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = Application::class, sdk = [31, 35])
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class GatewayKeepAliveServiceTest {
|
||||
private val context = mockk<Context>(relaxed = true)
|
||||
private val start = slot<Intent>()
|
||||
private var service: GatewayKeepAliveService? = null
|
||||
private val preferences = TestPreferences()
|
||||
|
||||
init {
|
||||
every { context.applicationContext } returns context
|
||||
every { context.startForegroundService(capture(start)) } returns
|
||||
ComponentName("test", GatewayKeepAliveService::class.java.name)
|
||||
}
|
||||
|
||||
@Before fun setup() {
|
||||
Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||
GatewayKeepAliveService.resetForTest()
|
||||
mockkStatic("com.hermesandroid.relay.data.DataStoreProviderKt")
|
||||
every { any<Context>().relayDataStore } returns preferences
|
||||
}
|
||||
|
||||
@After fun cleanup() {
|
||||
preferences.gate?.complete(Unit)
|
||||
service?.onDestroy()
|
||||
ActiveTurnKeepAliveRegistry.resetForTest()
|
||||
GatewayKeepAliveService.resetForTest()
|
||||
unmockkAll()
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
private fun create(): GatewayKeepAliveService =
|
||||
Robolectric.buildService(GatewayKeepAliveService::class.java).create().get()
|
||||
.also { service = it }
|
||||
|
||||
@Test fun immediateStopWaitsForForegroundPromotion() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
GatewayKeepAliveService.stop(context)
|
||||
verify(exactly = 0) { context.stopService(any()) }
|
||||
val instance = create()
|
||||
assertNotNull(shadowOf(instance).lastForegroundNotification)
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
}
|
||||
|
||||
@Test fun creationPromotesBeforePublishingTheInstance() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
assertNotNull(shadowOf(create()).lastForegroundNotification)
|
||||
}
|
||||
|
||||
@Test fun queuedStartCannotOverwriteNewerDemand() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val oldStart = start.captured
|
||||
val instance = create()
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2, 1))
|
||||
instance.onStartCommand(oldStart, 0, 1)
|
||||
val notification = shadowOf(instance).lastForegroundNotification!!
|
||||
assertEquals("Hermes is waiting for input", notification.extras.getString("android.title"))
|
||||
assertTrue(notification.actions.isNullOrEmpty())
|
||||
}
|
||||
|
||||
@Test fun overlappingStartsAreCoalescedAndLatestDemandWins() {
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
GatewayKeepAliveService.stop(context)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2))
|
||||
verify(exactly = 1) { context.startForegroundService(any()) }
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
assertEquals("Hermes is finishing 2 turns", notificationTitle(instance))
|
||||
}
|
||||
|
||||
@Test fun siblingSettlementKeepsTheRemainingSessionProtected() {
|
||||
ActiveTurnKeepAliveRegistry.acquire("connection::profile-a::session")
|
||||
ActiveTurnKeepAliveRegistry.acquire("connection::profile-b::session")
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
ActiveTurnKeepAliveRegistry.release("connection::profile-a::session")
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
assertEquals("Hermes is finishing a turn", notificationTitle(instance))
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
ActiveTurnKeepAliveRegistry.release("connection::profile-b::session")
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
}
|
||||
|
||||
@Test fun retiringInstanceIsNotReusedAndItsDestructionCannotClearReplacement() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val old = create()
|
||||
old.onStartCommand(start.captured, 0, 1)
|
||||
GatewayKeepAliveService.stop(context)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
verify(exactly = 2) { context.startForegroundService(any()) }
|
||||
val replacement = create()
|
||||
replacement.onStartCommand(start.captured, 0, 2)
|
||||
old.onDestroy()
|
||||
old.onConfigurationChanged(Configuration())
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2))
|
||||
assertEquals("Hermes is finishing 2 turns", notificationTitle(replacement))
|
||||
verify(exactly = 2) { context.startForegroundService(any()) }
|
||||
}
|
||||
|
||||
@Test fun androidCanDeliverANewStartToTheRetiringInstance() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
GatewayKeepAliveService.stop(context)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
instance.onStartCommand(start.captured, 0, 2)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2))
|
||||
assertEquals("Hermes is finishing 2 turns", notificationTitle(instance))
|
||||
verify(exactly = 2) { context.startForegroundService(any()) }
|
||||
}
|
||||
|
||||
@Test fun backgroundDemandWaitsForVisibilityAndExistingProtectionSurvivesBackgrounding() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot(), false)
|
||||
verify(exactly = 0) { context.startForegroundService(any()) }
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot(), true)
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot(1), false)
|
||||
assertEquals("Hermes is finishing a turn", notificationTitle(instance))
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
}
|
||||
|
||||
@Test fun rejectedLaunchCanRetryOnNextForegroundWithoutReleasingTurnOwnership() {
|
||||
ActiveTurnKeepAliveRegistry.acquire("connection::profile::session")
|
||||
every { context.startForegroundService(any()) } throws IllegalStateException("background start")
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
assertTrue(ActiveTurnKeepAliveRegistry.snapshot.value.required)
|
||||
every { context.startForegroundService(capture(start)) } returns
|
||||
ComponentName("test", GatewayKeepAliveService::class.java.name)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value, false)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.snapshot.value, true)
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
assertEquals("Hermes is finishing a turn", notificationTitle(instance))
|
||||
}
|
||||
|
||||
@Test fun promotionFailureRetiresTheInstanceAndAllowsAFreshLaunch() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = spyk(create()).also { service = it }
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
every { instance.startForeground(any(), any(), any()) } throws SecurityException("denied")
|
||||
} else {
|
||||
every { instance.startForeground(any(), any()) } throws SecurityException("denied")
|
||||
}
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
verify { instance.stopSelf() }
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
verify(exactly = 2) { context.startForegroundService(any()) }
|
||||
}
|
||||
|
||||
@Test fun channelFailureIsContainedBeforePublishingAnOwner() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = spyk(Robolectric.buildService(GatewayKeepAliveService::class.java).get())
|
||||
.also { service = it }
|
||||
every { instance.getSystemService(NotificationManager::class.java) } throws IllegalStateException("channel unavailable")
|
||||
instance.onCreate()
|
||||
verify { instance.stopSelf() }
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
verify(exactly = 2) { context.startForegroundService(any()) }
|
||||
}
|
||||
|
||||
@Test fun taskRemovalPreservesLeasesAndDoesNotRestartUntilTheNextVisibleLifecycle() {
|
||||
ActiveTurnKeepAliveRegistry.acquire("connection::profile::session")
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
instance.onTaskRemoved(null)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
assertTrue(ActiveTurnKeepAliveRegistry.snapshot.value.required)
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.snapshot.value)
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.snapshot.value, false)
|
||||
verify(exactly = 1) { context.startForegroundService(any()) }
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.snapshot.value, true)
|
||||
verify(exactly = 2) { context.startForegroundService(any()) }
|
||||
}
|
||||
|
||||
@Test fun taskRemovalDuringStartupStillAcknowledgesPromotion() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = create()
|
||||
instance.onTaskRemoved(null)
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
assertNotNull(shadowOf(instance).lastForegroundNotification)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
}
|
||||
|
||||
@Test fun processLossDoesNotReplayOldDemandButStillPromotesADeliveredStart() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val oldStart = start.captured
|
||||
GatewayKeepAliveService.resetForTest()
|
||||
val instance = create()
|
||||
assertNull(shadowOf(instance).lastForegroundNotification)
|
||||
instance.onStartCommand(oldStart, 0, 1)
|
||||
assertNotNull(shadowOf(instance).lastForegroundNotification)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
}
|
||||
|
||||
@Test fun staleStartCannotAcknowledgeANewerPendingStart() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val oldStart = start.captured
|
||||
GatewayKeepAliveService.resetForTest()
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
val newStart = start.captured
|
||||
val instance = create()
|
||||
instance.onStartCommand(oldStart, 0, 1)
|
||||
GatewayKeepAliveService.stop(context)
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
instance.onStartCommand(newStart, 0, 2)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
}
|
||||
|
||||
@Test fun notificationOnlyDisablesIdleRetentionAndUsesLatestTurnDemand() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
val action = stopAction(instance)
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot(2, 1))
|
||||
instance.onStartCommand(action, 0, 2)
|
||||
assertEquals(false, preferences.data.value[KEY_GATEWAY_KEEP_ALIVE])
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(2, 1))
|
||||
assertEquals("Hermes is waiting for input", notificationTitle(instance))
|
||||
assertTrue(shadowOf(instance).lastForegroundNotification!!.actions.isNullOrEmpty())
|
||||
}
|
||||
|
||||
@Test fun notificationWriteSurvivesServiceDestruction() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
preferences.gate = CompletableDeferred()
|
||||
instance.onStartCommand(stopAction(instance), 0, 2)
|
||||
instance.onTaskRemoved(null)
|
||||
instance.onDestroy()
|
||||
preferences.gate!!.complete(Unit)
|
||||
assertEquals(false, preferences.data.value[KEY_GATEWAY_KEEP_ALIVE])
|
||||
}
|
||||
|
||||
@Test fun queuedNotificationEditCannotDisableAReenabledPreference() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
val oldAction = stopAction(instance)
|
||||
preferences.gate = CompletableDeferred()
|
||||
instance.onStartCommand(oldAction, 0, 2)
|
||||
GatewayKeepAliveService.update(context, false, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot(1))
|
||||
preferences.gate!!.complete(Unit)
|
||||
assertEquals(true, preferences.data.value[KEY_GATEWAY_KEEP_ALIVE])
|
||||
instance.onStartCommand(oldAction, 0, 3)
|
||||
assertEquals(true, preferences.data.value[KEY_GATEWAY_KEEP_ALIVE])
|
||||
}
|
||||
|
||||
@Test fun failedPreferenceWriteKeepsTruthfulNotificationAndProtection() {
|
||||
GatewayKeepAliveService.update(context, true, ActiveTurnKeepAliveRegistry.Snapshot())
|
||||
val instance = create()
|
||||
instance.onStartCommand(start.captured, 0, 1)
|
||||
preferences.fail = true
|
||||
instance.onStartCommand(stopAction(instance), 0, 2)
|
||||
assertEquals(true, preferences.data.value[KEY_GATEWAY_KEEP_ALIVE])
|
||||
assertFalse(shadowOf(instance).isStoppedBySelf)
|
||||
assertEquals(1, shadowOf(instance).lastForegroundNotification!!.actions.size)
|
||||
}
|
||||
|
||||
@Test fun coldOldNotificationAndNullRestartDoNotEnableIdleRetention() {
|
||||
val instance = create()
|
||||
assertEquals(android.app.Service.START_NOT_STICKY, instance.onStartCommand(null, 0, 1))
|
||||
instance.onStartCommand(Intent().setAction(GatewayKeepAliveService.ACTION_STOP), 0, 2)
|
||||
assertNull(shadowOf(instance).lastForegroundNotification)
|
||||
assertTrue(shadowOf(instance).isStoppedBySelf)
|
||||
assertEquals(true, preferences.data.value[KEY_GATEWAY_KEEP_ALIVE])
|
||||
}
|
||||
|
||||
private fun notificationTitle(instance: GatewayKeepAliveService) =
|
||||
shadowOf(instance).lastForegroundNotification!!.extras.getString("android.title")
|
||||
|
||||
private fun stopAction(instance: GatewayKeepAliveService): Intent =
|
||||
shadowOf(shadowOf(instance).lastForegroundNotification!!.actions.single().actionIntent).savedIntent
|
||||
|
||||
private class TestPreferences : DataStore<Preferences> {
|
||||
override val data = MutableStateFlow(preferencesOf(KEY_GATEWAY_KEEP_ALIVE to true))
|
||||
var gate: CompletableDeferred<Unit>? = null
|
||||
var fail = false
|
||||
override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences {
|
||||
gate?.await()
|
||||
if (fail) throw java.io.IOException("write failed")
|
||||
return transform(data.value).also { data.value = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -12,6 +12,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -94,6 +95,37 @@ class AppearanceShapeScreenshotTest {
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/appearance-shape-balanced-sheet-dark.png")
|
||||
}
|
||||
|
||||
@Test @Config(sdk = [34]) fun coldModelPickerLoadingSurface() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
ModelPickerSheet(
|
||||
options = listOf(ChatInputPickerOption("Server default", null)),
|
||||
loading = true,
|
||||
onRefresh = {},
|
||||
onSelect = {},
|
||||
onDismiss = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Loading provider catalog…").assertExists()
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/model-picker-cold-loading.png")
|
||||
}
|
||||
|
||||
@Test @Config(sdk = [34]) fun coldModelPickerEmptySurface() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
ModelPickerSheet(
|
||||
options = listOf(ChatInputPickerOption("Server default", null)),
|
||||
onRefresh = {},
|
||||
onSelect = {},
|
||||
onDismiss = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("No models available. Try Refresh.").assertExists()
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/model-picker-cold-empty.png")
|
||||
}
|
||||
|
||||
private fun captureMode(shapeId: String, themeId: String, themePreference: String, fontScale: Float) {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(
|
||||
|
||||
+26
-1
@@ -8,6 +8,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.ApiEndpoint
|
||||
import com.hermesandroid.relay.data.DashboardEndpoint
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.ProxyEndpoint
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
@@ -17,11 +18,35 @@ import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w320dp-h720dp-xxhdpi")
|
||||
@Config(sdk = [35], qualifiers = "w320dp-h720dp-xxhdpi")
|
||||
class EndpointsCardCompactLayoutTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun `Secure Link details show derived namespaces rather than unconfigured placeholders`() {
|
||||
val route = EndpointCandidate(
|
||||
role = "plugin_proxy",
|
||||
proxy = ProxyEndpoint(
|
||||
url = "https://relay.example:9443",
|
||||
pinSha256 = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
|
||||
surfaces = listOf("relay", "dashboard"),
|
||||
),
|
||||
)
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
EndpointsCard(
|
||||
endpoints = listOf(route), activeEndpoint = route,
|
||||
preferredRole = null, manualOverrideRole = null,
|
||||
onUseNow = {}, onCancelUseNow = {}, onPreferEndpoint = {},
|
||||
onClearPreferred = {}, onProbeNow = {}, onViewPin = { null },
|
||||
)
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("https://relay.example:9443/dashboard").assertExists()
|
||||
compose.onNodeWithText("wss://relay.example:9443/relay/ws").assertExists()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `long route title keeps active state on a separate visible row`() {
|
||||
val title = "A very long operator-defined reverse proxy route name"
|
||||
|
||||
+46
@@ -3,6 +3,7 @@ package com.hermesandroid.relay.ui.components
|
||||
import com.hermesandroid.relay.data.ApiEndpoint
|
||||
import com.hermesandroid.relay.data.DashboardEndpoint
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.ProxyEndpoint
|
||||
import com.hermesandroid.relay.data.RelayEndpoint
|
||||
import com.hermesandroid.relay.network.shared.EndpointSurface
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -56,6 +57,51 @@ class GatewayRoutesAccessPresentationTest {
|
||||
assertEquals("LAN (HTTP)", presentation.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Secure Link candidate presents pinned HTTPS dashboard not plain 9119`() {
|
||||
val secureLink = EndpointCandidate(
|
||||
role = "plugin_proxy",
|
||||
priority = 0,
|
||||
proxy = ProxyEndpoint(
|
||||
url = "https://192.168.1.20:9443",
|
||||
transportHint = "https",
|
||||
pinSha256 = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
|
||||
surfaces = listOf("relay", "api", "dashboard"),
|
||||
),
|
||||
)
|
||||
|
||||
val presentation = gatewayRoutePresentation(
|
||||
activeEndpoint = secureLink,
|
||||
configuredDashboardUrl = "http://192.168.1.20:9119",
|
||||
)
|
||||
|
||||
assertEquals("https://192.168.1.20:9443/dashboard", presentation.address)
|
||||
assertEquals("Hermes Secure Link (HTTPS)", presentation.label)
|
||||
assertFalse(presentation.publicHttpViolation)
|
||||
assertTrue(presentation.configured)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Secure Link without dashboard surface does not invent a Gateway address`() {
|
||||
val relayOnlyProxy = EndpointCandidate(
|
||||
role = "plugin_proxy",
|
||||
proxy = ProxyEndpoint(
|
||||
url = "https://192.168.1.20:9443",
|
||||
pinSha256 = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
|
||||
surfaces = listOf("relay"),
|
||||
),
|
||||
)
|
||||
|
||||
val presentation = gatewayRoutePresentation(
|
||||
activeEndpoint = relayOnlyProxy,
|
||||
configuredDashboardUrl = "http://192.168.1.20:9119",
|
||||
)
|
||||
|
||||
// No dashboard surface → fall back to the saved configured URL.
|
||||
assertEquals("http://192.168.1.20:9119", presentation.address)
|
||||
assertEquals("LAN (HTTP)", presentation.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `relay-only candidate leaves the Gateway route unconfigured`() {
|
||||
val route = EndpointCandidate(
|
||||
|
||||
+20
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.data.DashboardEndpoint
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.ProxyEndpoint
|
||||
import com.hermesandroid.relay.data.RelayEndpoint
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
@@ -122,6 +123,25 @@ class ConnectionDetailPresentationTest {
|
||||
assertEquals("", route.address)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Secure Link owns current route identity instead of plain LAN fallback`() {
|
||||
val secureLink = EndpointCandidate(
|
||||
role = "plugin_proxy",
|
||||
proxy = ProxyEndpoint(
|
||||
url = "https://192.168.1.20:9443",
|
||||
pinSha256 = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
|
||||
surfaces = listOf("relay", "api", "dashboard"),
|
||||
),
|
||||
)
|
||||
val route = resolveDetailRoutePresentation(
|
||||
activeEndpoint = secureLink,
|
||||
effectiveDashboardUrl = "https://192.168.1.20:9443/dashboard",
|
||||
)
|
||||
|
||||
assertEquals("Hermes Secure Link (HTTPS)", route.label)
|
||||
assertEquals("https://192.168.1.20:9443/dashboard", route.address)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing route does not claim plain HTTP`() {
|
||||
val route = resolveDetailRoutePresentation(
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.hermesandroid.relay.ui.theme
|
||||
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.datastore.preferences.core.mutablePreferencesOf
|
||||
import com.hermesandroid.relay.data.AppearancePreferences
|
||||
import com.hermesandroid.relay.data.CustomThemePreset
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class AppearanceNightModeTest {
|
||||
@Test
|
||||
fun dualModeHonorsExplicitLightAndDark() {
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_NO,
|
||||
AppearanceNightMode.nightModeFor("light", ThemeMode.BOTH),
|
||||
)
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_YES,
|
||||
AppearanceNightMode.nightModeFor("dark", ThemeMode.BOTH),
|
||||
)
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM,
|
||||
AppearanceNightMode.nightModeFor("auto", ThemeMode.BOTH),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fixedThemesIgnorePreferenceAxis() {
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_NO,
|
||||
AppearanceNightMode.nightModeFor("dark", ThemeMode.LIGHT_ONLY),
|
||||
)
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_YES,
|
||||
AppearanceNightMode.nightModeFor("light", ThemeMode.DARK_ONLY),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun customThemeModeWinsOverPreference() {
|
||||
val light = CustomThemePreset(
|
||||
id = "day",
|
||||
name = "Day",
|
||||
mode = CustomThemePreset.MODE_LIGHT,
|
||||
backgroundHex = "#F5F5F5",
|
||||
surfaceHex = "#FFFFFF",
|
||||
accentHex = "#0E18D6",
|
||||
textHex = "#111111",
|
||||
)
|
||||
val dark = light.copy(id = "night", name = "Night", mode = CustomThemePreset.MODE_DARK)
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_NO,
|
||||
AppearanceNightMode.nightModeFor("dark", ThemeMode.BOTH, light),
|
||||
)
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_YES,
|
||||
AppearanceNightMode.nightModeFor("light", ThemeMode.BOTH, dark),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizePreferenceFallsBackToAuto() {
|
||||
assertEquals("auto", AppearanceNightMode.normalizePreference(null))
|
||||
assertEquals("auto", AppearanceNightMode.normalizePreference("sepia"))
|
||||
assertEquals("light", AppearanceNightMode.normalizePreference("light"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistedSnapshotDrivesBothPaletteAndPlatformNightMode() {
|
||||
val saved = mutablePreferencesOf(
|
||||
AppearancePreferences.themeKey to "light",
|
||||
AppearancePreferences.appThemeKey to AppThemes.DEFAULT_ID,
|
||||
)
|
||||
val appearance = AppearancePreferences.decode(saved)
|
||||
assertEquals("light", appearance.themePreference)
|
||||
assertEquals(AppCompatDelegate.MODE_NIGHT_NO, AppearanceNightMode.nightModeFor(appearance))
|
||||
|
||||
saved[AppearancePreferences.themeKey] = "auto"
|
||||
assertEquals(
|
||||
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM,
|
||||
AppearanceNightMode.nightModeFor(AppearancePreferences.decode(saved)),
|
||||
)
|
||||
|
||||
val custom = CustomThemePreset(
|
||||
id = "night",
|
||||
name = "Night",
|
||||
mode = CustomThemePreset.MODE_DARK,
|
||||
backgroundHex = "#0B0B0F",
|
||||
surfaceHex = "#141421",
|
||||
accentHex = "#5B6CFF",
|
||||
textHex = "#F5F6F7",
|
||||
)
|
||||
saved[AppearancePreferences.customThemesKey] =
|
||||
AppearancePreferences.encodeCustomThemes(listOf(custom))
|
||||
saved[AppearancePreferences.appThemeKey] = custom.appThemeId
|
||||
val restoredCustom = AppearancePreferences.decode(saved)
|
||||
assertEquals(custom.id, restoredCustom.customTheme?.id)
|
||||
assertEquals(AppCompatDelegate.MODE_NIGHT_YES, AppearanceNightMode.nightModeFor(restoredCustom))
|
||||
}
|
||||
}
|
||||
+133
-5
@@ -167,6 +167,79 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals("gpt-5.6-sol", viewModel.gatewayCurrentModel.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coldPickerLoadCanBeForceRefreshedWithoutAChatTurnAndLateResultCannotEraseIt() {
|
||||
assertTrue(viewModel.modelProviders.value.isEmpty())
|
||||
gatewayHarness.suppressAckMethods += "model.options"
|
||||
|
||||
viewModel.refreshModelOptions(catalogOnly = true)
|
||||
val coldRequest = gatewayHarness.awaitPendingAck()
|
||||
assertEquals("model.options", coldRequest.method)
|
||||
assertTrue(viewModel.modelOptionsLoading.value)
|
||||
assertFalse(viewModel.modelOptionsRefreshing.value)
|
||||
assertTrue(gatewayHarness.rpcLog.none { it.first == "prompt.submit" || it.first == "session.create" })
|
||||
|
||||
viewModel.refreshModelOptions(refresh = true, catalogOnly = true)
|
||||
val forcedRequest = gatewayHarness.awaitPendingAck()
|
||||
assertEquals("model.options", forcedRequest.method)
|
||||
assertTrue(viewModel.modelOptionsRefreshing.value)
|
||||
assertEquals(
|
||||
true,
|
||||
(gatewayHarness.rpcLog.last { it.first == "model.options" }.second["refresh"] as? JsonPrimitive)?.content == "true",
|
||||
)
|
||||
gatewayHarness.releaseAck(forcedRequest, buildJsonObject {
|
||||
put("providers", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("slug", "openai")
|
||||
put("name", "OpenAI")
|
||||
put("models", buildJsonArray { add(JsonPrimitive("gpt-5.5")) })
|
||||
put("authenticated", true)
|
||||
})
|
||||
})
|
||||
put("model", "gpt-5.5")
|
||||
put("provider", "openai")
|
||||
})
|
||||
awaitCondition { viewModel.modelProviders.value.singleOrNull()?.models == listOf("gpt-5.5") }
|
||||
assertFalse(viewModel.modelOptionsLoading.value)
|
||||
assertFalse(viewModel.modelOptionsRefreshing.value)
|
||||
|
||||
gatewayHarness.releaseAck(coldRequest, buildJsonObject {
|
||||
put("providers", buildJsonArray {})
|
||||
})
|
||||
shadowOf(Looper.getMainLooper()).idleFor(100, TimeUnit.MILLISECONDS)
|
||||
assertEquals(listOf("gpt-5.5"), viewModel.modelProviders.value.single().models)
|
||||
|
||||
viewModel.refreshModelOptions(refresh = true, catalogOnly = true)
|
||||
val repeatedRefresh = gatewayHarness.awaitPendingAck()
|
||||
assertEquals("model.options", repeatedRefresh.method)
|
||||
gatewayHarness.releaseAck(repeatedRefresh, buildJsonObject {
|
||||
put("providers", buildJsonArray {})
|
||||
})
|
||||
awaitCondition { !viewModel.modelOptionsLoading.value }
|
||||
assertTrue(viewModel.modelProviders.value.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun retiredConnectionCannotPublishLateColdCatalogOrKeepItsLoadingState() {
|
||||
gatewayHarness.suppressAckMethods += "model.options"
|
||||
viewModel.refreshModelOptions(catalogOnly = true)
|
||||
val staleRequest = gatewayHarness.awaitPendingAck()
|
||||
assertTrue(viewModel.modelOptionsLoading.value)
|
||||
|
||||
viewModel.updateGatewayClient(null)
|
||||
assertFalse(viewModel.modelOptionsLoading.value)
|
||||
gatewayHarness.releaseAck(staleRequest, buildJsonObject {
|
||||
put("providers", buildJsonArray {
|
||||
add(buildJsonObject {
|
||||
put("slug", "stale")
|
||||
put("models", buildJsonArray { add(JsonPrimitive("wrong-model")) })
|
||||
})
|
||||
})
|
||||
})
|
||||
shadowOf(Looper.getMainLooper()).idleFor(100, TimeUnit.MILLISECONDS)
|
||||
assertTrue(viewModel.modelProviders.value.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun attachingReadyGatewayDoesNotHydrateControlStateAheadOfSessions() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
@@ -642,7 +715,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition { loadedProfile == owner.name }
|
||||
assertEquals(owner.name, viewModel.conversationBinding.value.profileName)
|
||||
assertEquals(owner.name, gatewayClient.sessionProfileProvider())
|
||||
assertEquals("X-bot", handler.activeAgentName)
|
||||
assertEquals("x-bot", handler.activeAgentName)
|
||||
assertEquals("x-bot-session", persistedSession)
|
||||
|
||||
viewModel.switchProfileContext(
|
||||
@@ -694,7 +767,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
)
|
||||
assertEquals(alpha, selected)
|
||||
assertEquals(alpha.name, viewModel.conversationBinding.value.profileName)
|
||||
assertEquals("Alpha", handler.activeAgentName)
|
||||
assertEquals("alpha", handler.activeAgentName)
|
||||
|
||||
viewModel.openProfileSession(
|
||||
profileName = beta.name,
|
||||
@@ -706,7 +779,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals(beta, selected)
|
||||
assertEquals(beta.name, viewModel.conversationBinding.value.profileName)
|
||||
assertEquals(beta.name, gatewayClient.sessionProfileProvider())
|
||||
assertEquals("Beta", handler.activeAgentName)
|
||||
assertEquals("beta", handler.activeAgentName)
|
||||
assertEquals("beta-session", handler.currentSessionId.value)
|
||||
}
|
||||
|
||||
@@ -1462,7 +1535,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals("default", viewModel.conversationBinding.value.profileName)
|
||||
assertEquals("default", gatewayClient.sessionProfileProvider())
|
||||
assertEquals(null, handler.currentSessionId.value)
|
||||
assertEquals("Hermes", handler.activeAgentName)
|
||||
assertEquals("default", handler.activeAgentName)
|
||||
assertEquals("cleared", persistedSession)
|
||||
}
|
||||
|
||||
@@ -2000,7 +2073,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
})
|
||||
}
|
||||
viewModel.setDashboardConfigLoader { Result.success(config) }
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
awaitCondition { viewModel.personalityNames.value == listOf("private-a") }
|
||||
assertEquals(listOf("private-a"), viewModel.personalityNames.value)
|
||||
|
||||
viewModel.resetConnectionCatalogs()
|
||||
@@ -2013,6 +2086,12 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
|
||||
@Test
|
||||
fun unsolicitedGatewayCompletionAppearsAsOneAssistantTurnAndSettles() {
|
||||
val spoken = mutableListOf<String>()
|
||||
var admissions = 0
|
||||
viewModel.gatewayInboundSpeechReceiver = {
|
||||
admissions++
|
||||
{ text -> spoken.add(text); Unit }
|
||||
}
|
||||
// Upstream's process-completion poller currently emits this adjacent
|
||||
// duplicate pair; it must still create exactly one placeholder.
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
@@ -2048,6 +2127,13 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
}
|
||||
assertFalse(handler.messages.value.single().isStreaming)
|
||||
assertFalse(gatewayHarness.rpcLog.any { it.first == "prompt.submit" })
|
||||
assertEquals(1, admissions)
|
||||
assertEquals(listOf(BACKGROUND_ANSWER), spoken)
|
||||
serverWs.send(gatewayHarness.eventFrame("message.complete", buildJsonObject {
|
||||
put("text", BACKGROUND_ANSWER)
|
||||
}, "live-resumed"))
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(listOf(BACKGROUND_ANSWER), spoken)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2077,6 +2163,42 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(activeOwner.content.isBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inboundSpeechIgnoresForeignUnscopedAndFailedTurns() {
|
||||
val spoken = mutableListOf<String>()
|
||||
viewModel.gatewayInboundSpeechReceiver = { { text -> spoken.add(text); Unit } }
|
||||
for (session in listOf("foreign-session", null)) {
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, session))
|
||||
serverWs.send(gatewayHarness.eventFrame("message.complete", buildJsonObject {
|
||||
put("text", "Foreign answer")
|
||||
}, session))
|
||||
}
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(gatewayHarness.eventFrame("message.complete", buildJsonObject {
|
||||
put("status", "error")
|
||||
put("text", "Failed answer")
|
||||
put("error", "Synthetic failure")
|
||||
}, "live-resumed"))
|
||||
awaitCondition { handler.messages.value.any { "Error" in it.badges } }
|
||||
assertTrue(spoken.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inboundSpeechUsesFinalAnswerAfterToolInterim() {
|
||||
val spoken = mutableListOf<String>()
|
||||
viewModel.gatewayInboundSpeechReceiver = { { text -> spoken.add(text); Unit } }
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(gatewayHarness.eventFrame("message.interim", buildJsonObject {
|
||||
put("text", "Checking the completed work.")
|
||||
put("already_streamed", false)
|
||||
}, "live-resumed"))
|
||||
serverWs.send(gatewayHarness.eventFrame("message.complete", buildJsonObject {
|
||||
put("text", "The completed work passed.")
|
||||
}, "live-resumed"))
|
||||
awaitCondition { spoken.isNotEmpty() }
|
||||
assertEquals(listOf("The completed work passed."), spoken)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedMainDispatchAdmitsBackgroundStartAfterLocalCompletion() {
|
||||
viewModel.sendMessage("Local gateway turn")
|
||||
@@ -2499,6 +2621,12 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
gatewayHarness.awaitRpc("approval.respond")
|
||||
awaitCondition { !handler.isStreaming.value }
|
||||
awaitCondition { checkpointStore.checkpoint == null }
|
||||
// The RPC log records request receipt, before its acknowledgement is
|
||||
// dispatched back to Main. Checkpoint retirement is independent too.
|
||||
awaitCondition {
|
||||
handler.messages.value.singleOrNull { it.id == "ask-approval-1" }
|
||||
?.cardDispatches?.isNotEmpty() == true
|
||||
}
|
||||
assertEquals(
|
||||
"once",
|
||||
handler.messages.value.single { it.id == "ask-approval-1" }
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.audio.VoicePlayer
|
||||
import com.hermesandroid.relay.audio.VoiceRecorder
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
import com.hermesandroid.relay.data.VoiceEngineMode
|
||||
import com.hermesandroid.relay.network.shared.VoiceAudioClient
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.verify
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class VoiceInboundCompletionTest {
|
||||
private val dispatcher = StandardTestDispatcher()
|
||||
private lateinit var chat: ChatViewModel
|
||||
private lateinit var handler: ChatHandler
|
||||
private lateinit var voice: VoiceViewModel
|
||||
private lateinit var recorder: VoiceRecorder
|
||||
private lateinit var player: VoicePlayer
|
||||
private val synthesis = mutableListOf<String>()
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
Dispatchers.setMain(dispatcher)
|
||||
handler = ChatHandler().also { it.setSessionId("session-a") }
|
||||
chat = ChatViewModel().also {
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
}
|
||||
recorder = mockk(relaxed = true) {
|
||||
every { amplitude } returns MutableStateFlow(0f)
|
||||
every { isRecording() } returns false
|
||||
}
|
||||
player = mockk(relaxed = true) {
|
||||
every { amplitude } returns MutableStateFlow(0f)
|
||||
}
|
||||
val app = ApplicationProvider.getApplicationContext<Application>()
|
||||
val audio = object : VoiceAudioClient {
|
||||
override val route = VoiceAudioRoute.Standard
|
||||
override suspend fun transcribe(audioFile: File) = Result.success("")
|
||||
override suspend fun synthesize(text: String): Result<File> {
|
||||
synthesis.add(text)
|
||||
return Result.success(File.createTempFile("inbound-voice", ".wav", app.cacheDir))
|
||||
}
|
||||
}
|
||||
voice = VoiceViewModel(app).also {
|
||||
it.initialize(
|
||||
voiceClient = mockk(relaxed = true), voiceAudioClient = audio,
|
||||
chatViewModel = chat, recorder = recorder, player = player,
|
||||
sfxPlayer = mockk(relaxed = true),
|
||||
)
|
||||
it.enterVoiceMode()
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
fun teardown() {
|
||||
voice.exitVoiceMode()
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
private fun admission(): (String) -> Unit = requireNotNull(chat.gatewayInboundSpeechReceiver?.invoke())
|
||||
|
||||
@Test
|
||||
fun settledCompletionUsesConfiguredTtsExactlyOnce() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val receipt = admission()
|
||||
receipt("The timer finished.")
|
||||
receipt("The timer finished.")
|
||||
runCurrent()
|
||||
assertEquals(listOf("The timer finished."), synthesis)
|
||||
verify(exactly = 1) { player.play(any()) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fastInboundStartCannotBeConsumedByPreviousVoiceObserver() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
// Exercise the production observer with the Main dispatcher held between
|
||||
// the old terminal and the next inbound admission, as OkHttp can do.
|
||||
VoiceViewModel::class.java.getDeclaredMethod("startStreamObserver", ChatViewModel::class.java)
|
||||
.apply { isAccessible = true }.invoke(voice, chat)
|
||||
handler.addPlaceholderMessage(ChatMessage(
|
||||
id = "ordinary", role = MessageRole.ASSISTANT, content = "Work started.",
|
||||
timestamp = 1L, isStreaming = true,
|
||||
))
|
||||
handler.onStreamComplete("ordinary")
|
||||
val receipt = admission()
|
||||
handler.addPlaceholderMessage(ChatMessage(
|
||||
id = "inbound", role = MessageRole.ASSISTANT, content = "Work finished.",
|
||||
timestamp = 2L, isStreaming = true,
|
||||
))
|
||||
handler.onStreamComplete("inbound")
|
||||
receipt("Work finished.")
|
||||
runCurrent()
|
||||
assertEquals(listOf("Work started.", "Work finished."), synthesis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completionWaitsForEarlierSpeechAndPreservesOrder() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
voice.seedSpeakingStateForTest(listOf("Earlier answer"), 0)
|
||||
admission()("Process finished.")
|
||||
admission()("Delegated work finished.")
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
voice.finishAgentAudioOutputForTest()
|
||||
runCurrent()
|
||||
assertEquals(listOf("Process finished.", "Delegated work finished."), synthesis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeCaptureIsNeverCancelledForCompletionSpeech() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
every { recorder.isRecording() } returns true
|
||||
admission()("Watch matched.")
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
verify(exactly = 0) { recorder.cancel() }
|
||||
every { recorder.isRecording() } returns false
|
||||
voice.finishAgentAudioOutputForTest()
|
||||
runCurrent()
|
||||
assertEquals(listOf("Watch matched."), synthesis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stopInvalidatesAdmittedAndQueuedCompletions() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val late = admission()
|
||||
voice.seedSpeakingStateForTest(emptyList(), 0)
|
||||
admission()("Queued answer.")
|
||||
voice.interruptSpeaking()
|
||||
late("Late answer.")
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
assertNull(chat.gatewayInboundSpeechReceiver?.invoke())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exitAndReentryRejectsOldReceiptButAcceptsNewTurn() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val old = admission()
|
||||
voice.exitVoiceMode()
|
||||
voice.enterVoiceMode()
|
||||
old("Old answer.")
|
||||
admission()("New answer.")
|
||||
runCurrent()
|
||||
assertEquals(listOf("New answer."), synthesis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionSwitchRejectsOldReceiptAndDoesNotAdoptNewSession() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val old = admission()
|
||||
handler.setSessionId("session-b")
|
||||
old("Wrong session.")
|
||||
runCurrent()
|
||||
assertNull(chat.gatewayInboundSpeechReceiver?.invoke())
|
||||
handler.setSessionId("session-a")
|
||||
old("Stale return.")
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sameSessionIdInAnotherProfileCannotSpeak() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val old = admission()
|
||||
chat.switchProfileContext("connection-b::profile-b", "session-a")
|
||||
old("Wrong profile.")
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
assertNull(chat.gatewayInboundSpeechReceiver?.invoke())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun realtimeEngineDoesNotConsumeGatewaySpeech() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val old = admission()
|
||||
voice.setVoiceEngineModeForTest(VoiceEngineMode.RealtimeAgent)
|
||||
old("Wrong engine.")
|
||||
assertNull(chat.gatewayInboundSpeechReceiver?.invoke())
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun switchingEnginesBackCannotReviveAnOldReceipt() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
val old = admission()
|
||||
val applySettings = VoiceViewModel::class.java.getDeclaredMethod(
|
||||
"applyVoiceSettingsSnapshot", com.hermesandroid.relay.data.VoiceSettings::class.java,
|
||||
).apply { isAccessible = true }
|
||||
applySettings.invoke(voice, com.hermesandroid.relay.data.VoiceSettings(
|
||||
engineMode = VoiceEngineMode.RealtimeAgent.storageValue,
|
||||
))
|
||||
applySettings.invoke(voice, com.hermesandroid.relay.data.VoiceSettings())
|
||||
old("Stale engine receipt.")
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun newVoiceConversationAdoptsOnlyItsSubmittedSession() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
voice.exitVoiceMode()
|
||||
handler.setSessionId(null)
|
||||
voice.enterVoiceMode()
|
||||
val fence = VoiceTurnSessionFence(null).also { it.bindSubmittedUser("voice-user") }
|
||||
VoiceViewModel::class.java.getDeclaredField("voiceTurnSessionFence")
|
||||
.apply { isAccessible = true }.set(voice, fence)
|
||||
handler.addUserMessage(ChatMessage(
|
||||
id = "voice-user", role = MessageRole.USER, content = "Start work.", timestamp = 1L,
|
||||
))
|
||||
handler.setSessionId("new-voice-session")
|
||||
runCurrent()
|
||||
admission()("New conversation completion.")
|
||||
runCurrent()
|
||||
assertEquals(listOf("New conversation completion."), synthesis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun conversationChangeCancelsPendingSynthesisWithoutCancellingChat() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
voice.stopTtsConsumerForTest()
|
||||
admission()("Old profile output.")
|
||||
chat.switchProfileContext("connection-b::profile-b", "session-b")
|
||||
runCurrent()
|
||||
assertTrue(voice.drainTtsQueueForTest().isEmpty())
|
||||
assertTrue(synthesis.isEmpty())
|
||||
verify(atLeast = 1) { player.stop() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun historyAndForegroundReplayNeverCreateSpeech() = runTest(dispatcher) {
|
||||
runCurrent()
|
||||
handler.addPlaceholderMessage(ChatMessage(
|
||||
id = "history-a", role = MessageRole.ASSISTANT, content = "Historical answer.",
|
||||
timestamp = 1L, isStreaming = false,
|
||||
))
|
||||
voice.onAppResumed()
|
||||
runCurrent()
|
||||
assertTrue(synthesis.isEmpty())
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
plugins {
|
||||
id("com.android.application") version "9.4.0" apply false
|
||||
id("com.android.library") version "9.4.0" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.10" apply false
|
||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.4.10" apply false
|
||||
id("com.android.application") version "9.4.1" apply false
|
||||
id("com.android.library") version "9.4.1" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.20" apply false
|
||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.4.20" apply false
|
||||
}
|
||||
|
||||
@@ -16,6 +16,14 @@ subcommands provide scriptable chat, pairing, sessions, daemon management,
|
||||
grants, diagnostics, and desktop-tool routing. The optional systray is only a
|
||||
Windows management surface over those same commands and state files.
|
||||
|
||||
Secure Link is enabled on the **server**, using Dashboard/Desktop Relay setup or
|
||||
the host-side `hermes relay secure-link` readiness command. This CLI+UI remains a
|
||||
client: use `hermes-relay pair --pair-qr '<signed invite>'` to import its authority,
|
||||
certificate, and pin. A bare address or pairing code cannot establish new Secure
|
||||
Link trust. The tray and CLI use the same saved host trust; neither enables the
|
||||
server, rotates its certificate, or treats transport reachability as Dashboard
|
||||
sign-in. Generate a fresh invite and explicitly re-pair after identity changes.
|
||||
|
||||
> **What this is not:** A local Hermes install. Point it at an existing Hermes-Relay server (`ws://host:8767`). For the full TUI with Ink, see the sibling package [`ui-tui`](../../hermes-agent-tui-smoke/ui-tui) in the hermes-agent fork.
|
||||
|
||||
## Desktop surfaces
|
||||
@@ -425,6 +433,8 @@ The server-side plugin (`plugin/tools/desktop_tool.py`) registers `desktop_*` to
|
||||
|
||||
`desktop_computer_status`, `desktop_computer_screenshot`, `desktop_computer_action`, `desktop_computer_grant_request`, and `desktop_computer_cancel` are registered server-side but the desktop client advertises and serves them only when explicitly enabled:
|
||||
|
||||
The screenshot tool attaches a validated PNG or JPEG as a native host image result when the bounded relay response contains image bytes. A `save_to` capture remains a saved-path response. The desktop wire budget still rejects oversized captures rather than placing unbounded image data in a tool result.
|
||||
|
||||
```sh
|
||||
hermes-relay computer-use enable
|
||||
hermes-relay computer-use status
|
||||
|
||||
@@ -329,6 +329,7 @@ async function cuaSnapshot(args: Record<string, unknown>, ctx: ToolContext): Pro
|
||||
elements: safeElements,
|
||||
tree_markdown: raw.tree_markdown,
|
||||
screenshot_base64: raw.screenshot_base64,
|
||||
screenshot_mime_type: raw.screenshot_mime_type,
|
||||
screenshot_width: raw.screenshot_width,
|
||||
screenshot_height: raw.screenshot_height,
|
||||
truncated: elements.length > safeElements.length
|
||||
|
||||
@@ -51,7 +51,9 @@ class FakeCuaSession {
|
||||
return {
|
||||
snapshot_id: `s0000000${this.snapshotNumber}`,
|
||||
elements: [{ element_index: 7, element_token: 'e1234abcd', role: 'button', label: 'Seven' }],
|
||||
tree_markdown: '[7] button Seven'
|
||||
tree_markdown: '[7] button Seven',
|
||||
screenshot_base64: 'aW1hZ2U=',
|
||||
screenshot_mime_type: 'image/png'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,9 +142,13 @@ test('CUA handlers issue a Hermes token, execute once, and verify with a fresh s
|
||||
ok: boolean
|
||||
backend: string
|
||||
elements: Array<{ snapshot_token: string; element_token?: string }>
|
||||
screenshot_base64: string
|
||||
screenshot_mime_type: string
|
||||
}
|
||||
assert.equal(observed.ok, true)
|
||||
assert.equal(observed.backend, 'cua_driver')
|
||||
assert.equal(observed.screenshot_base64, 'aW1hZ2U=')
|
||||
assert.equal(observed.screenshot_mime_type, 'image/png')
|
||||
assert.equal(observed.elements[0]!.element_token, undefined)
|
||||
assert.match(observed.elements[0]!.snapshot_token, /^hermes-snapshot-/)
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "secondary-windows",
|
||||
"description": "Dismiss the connection notice and screenshot evidence windows",
|
||||
"windows": ["notice", "evidence"],
|
||||
"permissions": ["core:window:allow-hide"]
|
||||
}
|
||||
@@ -2514,10 +2514,14 @@ mod app {
|
||||
label,
|
||||
event: WindowEvent::CloseRequested { api, .. },
|
||||
..
|
||||
} if label == "main" => {
|
||||
} if matches!(label.as_str(), "main" | "grant" | "notice" | "evidence") => {
|
||||
api.prevent_close();
|
||||
if let Some(window) = handle.get_webview_window("main") {
|
||||
request_main_hide(&window);
|
||||
if let Some(window) = handle.get_webview_window(&label) {
|
||||
if label == "main" {
|
||||
request_main_hide(&window);
|
||||
} else {
|
||||
let _ = window.hide();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -340,3 +340,47 @@ fn management_window_keeps_the_reviewed_compact_geometry() {
|
||||
assert!(ui.contains("hide().finally(() => setWindowVisible(true))"));
|
||||
assert!(ui.contains("document.visibilityState === 'visible'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secondary_windows_have_only_the_dismissal_permission() {
|
||||
let config: serde_json::Value =
|
||||
serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
|
||||
let main: serde_json::Value =
|
||||
serde_json::from_str(include_str!("../capabilities/default.json")).unwrap();
|
||||
let secondary: serde_json::Value =
|
||||
serde_json::from_str(include_str!("../capabilities/secondary-windows.json")).unwrap();
|
||||
|
||||
let configured: std::collections::BTreeSet<&str> = config["app"]["windows"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|window| window["label"].as_str().unwrap())
|
||||
.collect();
|
||||
let main_windows: std::collections::BTreeSet<&str> = main["windows"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|label| label.as_str().unwrap())
|
||||
.collect();
|
||||
let secondary_windows: std::collections::BTreeSet<&str> = secondary["windows"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|label| label.as_str().unwrap())
|
||||
.collect();
|
||||
|
||||
assert_eq!(main_windows, ["main", "grant"].into_iter().collect());
|
||||
assert_eq!(
|
||||
secondary_windows,
|
||||
["notice", "evidence"].into_iter().collect()
|
||||
);
|
||||
assert_eq!(
|
||||
configured,
|
||||
main_windows.union(&secondary_windows).copied().collect()
|
||||
);
|
||||
assert!(main_windows.is_disjoint(&secondary_windows));
|
||||
assert_eq!(
|
||||
secondary["permissions"],
|
||||
serde_json::json!(["core:window:allow-hide"])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -286,16 +286,20 @@ function EvidenceWindow() {
|
||||
const [evidenceId, setEvidenceId] = useState<string | null>(null)
|
||||
const [source, setSource] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const requestGeneration = useRef(0)
|
||||
useEffect(() => {
|
||||
const receive = (event: Event) => {
|
||||
const id = (event as CustomEvent<{ evidenceId: string }>).detail.evidenceId
|
||||
const generation = ++requestGeneration.current
|
||||
setEvidenceId(id); setSource(null); setError(null)
|
||||
void call<string>('get_activity_screenshot', { evidenceId: id }).then(setSource).catch(value => setError(String(value)))
|
||||
void call<string>('get_activity_screenshot', { evidenceId: id })
|
||||
.then(value => { if (generation === requestGeneration.current) setSource(value) })
|
||||
.catch(value => { if (generation === requestGeneration.current) setError(String(value)) })
|
||||
}
|
||||
const close = (event: KeyboardEvent) => { if (event.key === 'Escape') void getCurrentWindow().hide() }
|
||||
window.addEventListener('hermes-screenshot-evidence', receive)
|
||||
window.addEventListener('keydown', close)
|
||||
return () => { window.removeEventListener('hermes-screenshot-evidence', receive); window.removeEventListener('keydown', close) }
|
||||
return () => { requestGeneration.current++; window.removeEventListener('hermes-screenshot-evidence', receive); window.removeEventListener('keydown', close) }
|
||||
}, [])
|
||||
return <div className="evidence-shell">
|
||||
<header><span><Eye /><strong>Screenshot evidence</strong><small>Stored locally with this activity event</small></span><button aria-label="Close screenshot" onClick={() => getCurrentWindow().hide()}><X /></button></header>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Gateway foreground-service startup (#603)
|
||||
|
||||
## Confirmed defect and limits
|
||||
|
||||
Issue #603 reports `ForegroundServiceDidNotStartInTimeException` naming
|
||||
`GatewayKeepAliveService` on Android 12/API 31. The report contains no preceding
|
||||
lifecycle log and no comments. It does not establish an OEM-specific cause or
|
||||
implicate the voice overlay.
|
||||
|
||||
Before this fix, demand could call `startForegroundService()` and then
|
||||
`stopService()` before Android delivered `onCreate` or `onStartCommand`.
|
||||
Android 12's `ActiveServices.bringDownServiceLocked` explicitly schedules a
|
||||
foreground-service crash when teardown encounters `fgRequired`. Promotion in
|
||||
`onStartCommand` alone therefore did not protect immediate cancellation.
|
||||
|
||||
Three focused API 31 regressions failed against the previous implementation:
|
||||
immediate stop called `stopService` with an outstanding start; creation had no
|
||||
foreground notification; and a queued persistent-only start overwrote newer
|
||||
active/waiting-turn notification state. These establish client defects, not the
|
||||
precise callback sequence on the reporting device.
|
||||
|
||||
## Lifecycle audit
|
||||
|
||||
| Path | Resulting contract |
|
||||
| --- | --- |
|
||||
| Controller | Main-thread collection combines the persistent preference, scoped turn leases, and process visibility. Socket-retention demand remains separate from service-launch eligibility. |
|
||||
| First start | One pending token; channel creation, notification construction, and promotion happen synchronously in `onCreate`, without coroutine, datastore, or network work first. |
|
||||
| Start then stop / overlapping demands | Coalesce current demand until the start command promotes and acknowledges its obligation. No `stopService` cancellation of pending starts. |
|
||||
| Running updates | Apply current demand only to the live owner. Clear that owner before requesting teardown; a late old `onDestroy` cannot clear a replacement. |
|
||||
| Delivered stale start / process loss | Promote a delivered foreground start, but never restore its old demand. A cold stale notification action does not restore idle retention. `START_NOT_STICKY` remains in effect. |
|
||||
| Settlement / session switch | Existing connection/profile/session leases settle independently. This service sends no interrupt, resume, activate, or transport-routing command. |
|
||||
| Always-on notification action | Identity includes the current enable cycle. Preference persistence outlives service teardown and rechecks its token inside the edit. Current turn demand determines eventual shutdown. Write failure leaves the preference and notification truthful. |
|
||||
| Background eligibility | Do not request a new service from a known background lifecycle. Existing protection continues. Launch rejection is logged; a later visible transition retries remaining demand. |
|
||||
| Task removal | Release local foreground protection without deleting chat-owned leases or assuming the process dies. Suppress restart until a new visible lifecycle transition. |
|
||||
| Startup failure | Channel/build/promotion exceptions retire the unusable instance and clear pending launch state. They never cancel a server-owned turn. Platform-level asynchronous failures cannot be converted into successful foreground protection. |
|
||||
| Configuration change | Only the current live owner refreshes the notification. |
|
||||
| Notification/type policy | Existing low-importance channel, immutable intents, non-exported service, and both-flavor `specialUse` declaration remain. API 34+ uses the declared type/permission; API 31 uses the two-argument promotion. No permissions or dependencies added. |
|
||||
|
||||
The Gateway protocol, recovery/history contract, and session owner are unchanged,
|
||||
so no new Gateway fixture scenario or upstream-conformance requirement is
|
||||
introduced. The additional instrumentation exercises Android ActivityManager
|
||||
and notification PendingIntent delivery without a server.
|
||||
|
||||
## Verification scope
|
||||
|
||||
`GatewayKeepAliveServiceTest` exercises API 31 and 35, including startup,
|
||||
cancellation, failure, stale generations, notification persistence, task removal,
|
||||
and scoped sibling settlement. It and `ActiveTurnKeepAliveRegistryTest` are in
|
||||
both-flavor focused verification. `GatewayKeepAliveServiceInstrumentedTest`
|
||||
targets the Standard Phone API 36 lane and observes the real platform watchdog
|
||||
after rapid starts/stops, plus notification actions crossed by new turn demand.
|
||||
Exact execution results belong to the PR's verification section.
|
||||
|
||||
Huawei firmware, physical-device behavior, and unrelated main-thread stalls
|
||||
remain unverified. The change does not claim that every possible foreground-start
|
||||
timeout has the same cause.
|
||||
|
||||
## Android sources
|
||||
|
||||
- [Android 12 ActiveServices](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android12-release/services/core/java/com/android/server/am/ActiveServices.java): `bringDownServiceLocked`, `setServiceForegroundInnerLocked`, and `serviceForegroundTimeout`.
|
||||
- [Foreground-service troubleshooting](https://developer.android.com/develop/background-work/services/fgs/troubleshooting): startup timeout versus background-start rejection.
|
||||
- [Launching a foreground service](https://developer.android.com/develop/background-work/services/fgs/launch): prompt promotion, notification priority, and API 34 type prerequisites.
|
||||
- [Background-start restrictions](https://developer.android.com/develop/background-work/services/fgs/restrictions-bg-start): API 31 restrictions and user-interaction exceptions.
|
||||
@@ -4444,3 +4444,32 @@ Source and merged-manifest validation enforce this boundary. Foreground-service
|
||||
lifecycle tests and rendered permission/Stop controls supplement, but do not
|
||||
replace, device tests or a reviewed Play test-track submission. See
|
||||
[Play declarations](play-store-listing.md#voice-overlay-review-before-production).
|
||||
|
||||
|
||||
## ADR 75 — Dashboard HTTP exceptions require exact-origin user consent
|
||||
|
||||
**Status:** Accepted (2026-09-18).
|
||||
|
||||
**Context.** Address-range classification does not establish whether traffic
|
||||
travels through a custom VPN. It blocked adding or migrating a Dashboard using
|
||||
HTTP on a non-private-range address, even when the operator intentionally routed
|
||||
that address through a private tunnel.
|
||||
|
||||
**Decision.** Keep HTTPS as the default. Offer an unchecked, explicit warning
|
||||
and acknowledgement when a user configures an otherwise-restricted HTTP
|
||||
Dashboard address. Persist consent only on that connection for the exact HTTP
|
||||
scheme, host and port. A different origin requires new consent; editing retires
|
||||
the old origin's exception and Dashboard authentication without replacing the
|
||||
connection identity or deleting drafts/history. Setup, route editing and native
|
||||
authentication share this authority. No Relay grant or global insecure-mode flag
|
||||
is reused. Consent is not a VPN or encryption verdict.
|
||||
|
||||
The app does not detect or enforce VPN protection. The user accepts cleartext
|
||||
exposure if the tunnel drops or traffic uses another route. Authentication still
|
||||
uses the upstream Dashboard contract; a public status response cannot prove
|
||||
protected access or Gateway readiness. Generic 401s retain sign-in/retry recovery;
|
||||
loopback/public_url guidance is conditional on additional setup evidence.
|
||||
|
||||
**Consequences.** Advanced network setups are usable with explicit assumed risk.
|
||||
The exception must not cross connection or credential-origin boundaries. VPN
|
||||
monitoring or route enforcement would be separate work, not an implied guarantee.
|
||||
|
||||
@@ -68,6 +68,7 @@ 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 |
|
||||
| `unsolicited_voice_completions` | One submitted turn followed by live same-session process, watch, and delegation answers, including duplicate start/terminal frames; Standard Voice receives each admitted answer once |
|
||||
| `clarify_legacy` | Top-level single question and unkeyed `clarify.respond` |
|
||||
| `clarify_normalized_single` | One normalized `questions[]` entry still requires its exact `qid` |
|
||||
| `clarify_batch` | Independent qid responses, partial acknowledgement, and answered-question replay on reconnect |
|
||||
@@ -179,6 +180,47 @@ redacted.
|
||||
|
||||
## Current-upstream conformance
|
||||
|
||||
The `secure_link_gateway_auth` scenario exercises query and subprotocol ticket
|
||||
admission through the real Secure Link proxy, single-use rejection, a completed
|
||||
turn, and live-session activation after reconnect. Run its wire regression with
|
||||
`python -m unittest plugin.tests.test_secure_proxy_contract`; it also checks
|
||||
compression boundaries, health coalescing, and bounded Dashboard rewrites.
|
||||
Pass that scenario's JSON manifest to the conformance checker below to verify
|
||||
the upstream ticket/public-protocol and live-activation seams. Android's focused
|
||||
`PluginProxyTransportTest`, `GatewayChatClientTest`, and `RelayVoiceClientRoutingTest`
|
||||
cover pin rejection, route replacement during an active turn or ticket mint, and
|
||||
the voice HTTP/WebSocket client selection. These are protocol tests, not physical
|
||||
device or OEM TLS certification.
|
||||
|
||||
Standard Voice receives successful unsolicited assistant answers from live Chat
|
||||
admission, with a receipt captured before the new assistant placeholder exists.
|
||||
The receipt belongs to the active voice generation and conversation binding;
|
||||
history reads, passive Desktop observation, unmatched terminal recovery, and
|
||||
queued-checkpoint restoration do not create speech receipts. Stop, voice exit,
|
||||
engine changes, and conversation changes invalidate pending receipts. An active
|
||||
microphone capture or earlier spoken answer finishes before queued speech starts.
|
||||
The existing Continuous microphone release barrier still owns rearming.
|
||||
|
||||
Process completion/watch notifications and async delegation wakes enter upstream's
|
||||
ordinary prompt runner (`tui_gateway/session_notifications.py` and `prompt_turn.py`
|
||||
in current split upstream sources). The resulting assistant answer uses the same
|
||||
live admission contract, regardless of its trigger. Raw process output, child
|
||||
previews, and `background.complete` side-agent events are not assistant answers
|
||||
and do not independently trigger narration. Reconnect history remains silent;
|
||||
new live turns after reconnect can receive new receipts for the same owner.
|
||||
|
||||
`VoiceInboundCompletionTest` exercises the voice receipt and configured synthesis
|
||||
path; `ChatViewModelGatewayInboundTurnTest` exercises real WebSocket admission.
|
||||
The `unsolicited_voice_completions` manifest certifies the upstream terminal
|
||||
contract without making provider or physical-audio claims.
|
||||
|
||||
For emulator lifecycle coverage, start that fixture on host loopback and run
|
||||
`GatewayExternalFixtureInstrumentedTest#unsolicitedVoiceCompletions_surviveActivityPauseWithoutHistorySpeech`
|
||||
on `standardPhoneApi36`, passing its emulator-accessible URL through
|
||||
`gatewayFixtureBaseUrl`. The test uses production Chat/Voice view models and a
|
||||
synthetic Standard audio client returning silent WAVs; it asserts three synthesis
|
||||
requests across Activity pause/resume, with no provider calls or microphone capture.
|
||||
|
||||
Run against a clean checkout of `NousResearch/hermes-agent`:
|
||||
|
||||
```powershell
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8588c42385e783a2ddf888b515ca6b97a5df44a30d3619c048d3d03d91dd5278",
|
||||
"main": "87e9f0e2fe07b89cb2647413eff8a6b4f600666d23cc96ab72d145ef55544f9e",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -25,8 +25,8 @@
|
||||
"docs_locale": "de",
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "57620215fb98a676f1b92d45596d44aa369dacc6e16dad17242f6e3e5cc38906",
|
||||
"guide/getting-started.md": "a30d0553f962f780573054dfa148a5c1dd88e258cb8fcaee9fdaed63346efeba",
|
||||
"guide/quick-start.md": "60d0ac8c35a03b3e4231329956e1bfee7dd276181d7513ecb5a877c323a282f2",
|
||||
"guide/getting-started.md": "909d4114f0a99d62627673d69b50743ec257df8e83199f90b27788318b0b88bc",
|
||||
"guide/release-tracks.md": "5d9ba422975459581fdbbc0b9e6f9b9c7dc53f9196606455b418da11d63d3a63",
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
@@ -48,7 +48,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8588c42385e783a2ddf888b515ca6b97a5df44a30d3619c048d3d03d91dd5278",
|
||||
"main": "87e9f0e2fe07b89cb2647413eff8a6b4f600666d23cc96ab72d145ef55544f9e",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -60,8 +60,8 @@
|
||||
"docs_locale": "es",
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "57620215fb98a676f1b92d45596d44aa369dacc6e16dad17242f6e3e5cc38906",
|
||||
"guide/getting-started.md": "a30d0553f962f780573054dfa148a5c1dd88e258cb8fcaee9fdaed63346efeba",
|
||||
"guide/quick-start.md": "60d0ac8c35a03b3e4231329956e1bfee7dd276181d7513ecb5a877c323a282f2",
|
||||
"guide/getting-started.md": "909d4114f0a99d62627673d69b50743ec257df8e83199f90b27788318b0b88bc",
|
||||
"guide/release-tracks.md": "5d9ba422975459581fdbbc0b9e6f9b9c7dc53f9196606455b418da11d63d3a63",
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8588c42385e783a2ddf888b515ca6b97a5df44a30d3619c048d3d03d91dd5278",
|
||||
"main": "87e9f0e2fe07b89cb2647413eff8a6b4f600666d23cc96ab72d145ef55544f9e",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -84,8 +84,8 @@
|
||||
"docs_locale": "ja",
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "57620215fb98a676f1b92d45596d44aa369dacc6e16dad17242f6e3e5cc38906",
|
||||
"guide/getting-started.md": "a30d0553f962f780573054dfa148a5c1dd88e258cb8fcaee9fdaed63346efeba",
|
||||
"guide/quick-start.md": "60d0ac8c35a03b3e4231329956e1bfee7dd276181d7513ecb5a877c323a282f2",
|
||||
"guide/getting-started.md": "909d4114f0a99d62627673d69b50743ec257df8e83199f90b27788318b0b88bc",
|
||||
"guide/release-tracks.md": "5d9ba422975459581fdbbc0b9e6f9b9c7dc53f9196606455b418da11d63d3a63",
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
@@ -96,7 +96,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8588c42385e783a2ddf888b515ca6b97a5df44a30d3619c048d3d03d91dd5278",
|
||||
"main": "87e9f0e2fe07b89cb2647413eff8a6b4f600666d23cc96ab72d145ef55544f9e",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -108,8 +108,8 @@
|
||||
"docs_locale": "pt-BR",
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "57620215fb98a676f1b92d45596d44aa369dacc6e16dad17242f6e3e5cc38906",
|
||||
"guide/getting-started.md": "a30d0553f962f780573054dfa148a5c1dd88e258cb8fcaee9fdaed63346efeba",
|
||||
"guide/quick-start.md": "60d0ac8c35a03b3e4231329956e1bfee7dd276181d7513ecb5a877c323a282f2",
|
||||
"guide/getting-started.md": "909d4114f0a99d62627673d69b50743ec257df8e83199f90b27788318b0b88bc",
|
||||
"guide/release-tracks.md": "5d9ba422975459581fdbbc0b9e6f9b9c7dc53f9196606455b418da11d63d3a63",
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
@@ -120,7 +120,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8588c42385e783a2ddf888b515ca6b97a5df44a30d3619c048d3d03d91dd5278",
|
||||
"main": "87e9f0e2fe07b89cb2647413eff8a6b4f600666d23cc96ab72d145ef55544f9e",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -135,7 +135,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "8588c42385e783a2ddf888b515ca6b97a5df44a30d3619c048d3d03d91dd5278",
|
||||
"main": "87e9f0e2fe07b89cb2647413eff8a6b4f600666d23cc96ab72d145ef55544f9e",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -147,8 +147,8 @@
|
||||
"docs_locale": "zh-CN",
|
||||
"docs_source_sha256": {
|
||||
"index.md": "101ef2e9394b76e822d0c828e2100bf18a9d3f450224f5f0ae3ea01cb02fab0d",
|
||||
"guide/quick-start.md": "57620215fb98a676f1b92d45596d44aa369dacc6e16dad17242f6e3e5cc38906",
|
||||
"guide/getting-started.md": "a30d0553f962f780573054dfa148a5c1dd88e258cb8fcaee9fdaed63346efeba",
|
||||
"guide/quick-start.md": "60d0ac8c35a03b3e4231329956e1bfee7dd276181d7513ecb5a877c323a282f2",
|
||||
"guide/getting-started.md": "909d4114f0a99d62627673d69b50743ec257df8e83199f90b27788318b0b88bc",
|
||||
"guide/release-tracks.md": "5d9ba422975459581fdbbc0b9e6f9b9c7dc53f9196606455b418da11d63d3a63",
|
||||
"guide/troubleshooting.md": "9ace84208d2109d3ae7b35a21838eae146db3171236568d3ae60fb8d9de882cf"
|
||||
},
|
||||
|
||||
@@ -201,6 +201,12 @@ The Play build declares `SYSTEM_ALERT_WINDOW` only for explicitly user-started V
|
||||
|
||||
The Play build does **not** declare `FOREGROUND_SERVICE_MEDIA_PROJECTION` or the Device Control accessibility/bridge services — those are sideload-only.
|
||||
|
||||
#### Reviewer recording retention
|
||||
|
||||
Android 1.17.0 (57) recordings cover [microphone use: Voice Overlay and local wake](https://hermes-relay.dev/play-review/android-microphone-fgs-v1.17.0.mp4) and the [connection foreground service](https://hermes-relay.dev/play-review/android-connection-service-v1.17.0.mp4). The [reviewer page](https://hermes-relay.dev/play-review/) records their emulator scope and limitations. These versioned recordings do not certify later builds.
|
||||
|
||||
Keep Console-linked footage in persistent media storage so website deployments preserve the links. Before updating a declaration, verify public access, `video/mp4` content type, byte-range playback and published checksums.
|
||||
|
||||
### Data safety
|
||||
|
||||
There is no telemetry, advertising, or third-party analytics SDK. App traffic goes
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-09-14 — Android 1.17.0 and Plugin 1.11.3 publication verified
|
||||
|
||||
Published [Hermes-Relay Android 1.17.0](https://github.com/Codename-11/hermes-relay/releases/tag/android-v1.17.0) (versionCode 57) and [Hermes-Relay Plugin 1.11.3](https://github.com/Codename-11/hermes-relay/releases/tag/server-v1.11.3) from `52f3f7565811828824d42bc9b432296271a2f9c3`. Both immutable tags retain tree `b366c9567759e509d39b6495197ffd35b3eeb430`. Android public APK/AAB bytes match the signed Play preflight artifact; Plugin wheel/sdist metadata and checksums were independently verified.
|
||||
|
||||
Play accepted code 57 on Internal testing and Production. At initial verification, the Publisher API reported Production `completed` while Console showed the release in review, with Managed Publishing off. Console subsequently confirmed Android 1.17.0/code 57 as **Available on Google Play** on September 14, 2026, across 177 countries/regions. English and Chinese Play notes match the tagged sources.
|
||||
|
||||
Canonical and legacy privacy pages were published and matched the committed policy. Data Safety and foreground-service declarations were reconciled, and [versioned reviewer videos](https://hermes-relay.dev/play-review/) use persistent storage. API 36 emulator evidence covers overlay access gating, background capture, notification Stop, screen-lock shutdown, standalone wake listening and persistent-connection controls. Physical Android 14–16/OEM testing was waived; speech-provider behavior and combined voice/wake handoff are not certified by these recordings.
|
||||
|
||||
Release follow-ups closed #474 and #556 as fixed. #557 remains the upstream-tracked context gap; its existing reply was preserved. The contributor on #583 was notified after Plugin publication.
|
||||
|
||||
## 2026-09-13 — Android 1.17.0 and Plugin 1.11.3 release preparation
|
||||
|
||||
Prepared Android 1.17.0 (versionCode 57) with Google Play Voice Overlay, progressive Clarify batches, chat card presentation, transport-accurate context previews and profile display names. Prepared Plugin 1.11.3 for current and legacy Dashboard WebSocket guard ownership. CLI+UI remains 0.4.0-beta.7.
|
||||
|
||||
@@ -6,6 +6,19 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
|
||||
|
||||
---
|
||||
|
||||
## Secure Link managed activation
|
||||
|
||||
The first guided setup uses shared read-only checks, copyable startup settings,
|
||||
explicit operator restart, and a re-checked pairing handoff. Add automatic
|
||||
activation only for explicitly supported service-manager adapters that prove
|
||||
ownership, preview the exact change and interruption, preserve the prior
|
||||
configuration, verify the new listener, and roll back a failed activation.
|
||||
Unknown/embedded managers must retain the guided-command path. Never infer a
|
||||
service name, change an upstream bind, open firewall ports, rotate keys, or
|
||||
restart Gateway merely because a user opens setup.
|
||||
|
||||
---
|
||||
|
||||
## Restore the plugin manifest v2 declaration after the Hermes installer fix ships
|
||||
|
||||
Hermes installers in affected stable releases reject `manifest_version: 2`
|
||||
|
||||
@@ -370,6 +370,7 @@ See [`docs/spec.md` §3.3](spec.md) for the full auth flow and the QR wire forma
|
||||
|-------|--------|---------|
|
||||
| `/ws`, `/` | GET (upgrade) | Main WebSocket endpoint. Phone connects, sends `system/auth`, then multiplexes `chat`/`terminal`/`bridge` envelopes. |
|
||||
| `/health` | GET | Returns `{status, version, clients, sessions}` JSON. |
|
||||
| `/secure-link/preflight` | GET | **Loopback only.** Read-only Secure Link checks for a proposed `host` and `port`, with startup instructions and restart impact. The Dashboard/Desktop setup UI and `hermes relay secure-link` share this report. No configuration or service mutations. |
|
||||
| `/pairing/register` | POST | **Loopback only.** Pre-register an externally-provided pairing code so it can appear in a QR payload before the phone scans it. Request body: `{"code": "ABCD12", "ttl_seconds": 2592000, "grants": {"terminal": 604800, "bridge": 86400}, "transport_hint": "wss"}` — `ttl_seconds` / `grants` / `transport_hint` are all optional; if omitted the SessionManager's bounded defaults are used. Client-supplied policy in the WebSocket auth envelope is never authoritative. Response: `{"ok": true, "code": "ABCD12"}`. Returns HTTP 403 for any `request.remote` other than `127.0.0.1` / `::1`. **As of ADR 15 this endpoint clears all rate-limit blocks on success** — the operator is explicitly re-pairing, stale blocks should not prevent the new code from being consumed. Used by `hermes pair` / `/hermes-relay-pair`; `hermes-pair` remains a compatibility shim. |
|
||||
| `/pairing/mint` | POST | **Loopback only.** Mint a fresh pairing code and return the signed QR payload plus `pairing_url` (`hermes-relay://pair?payload=...`) used by dashboard and desktop pair/repair flows. Reads `API_SERVER_KEY` from the host-local config chain when the dashboard does not pass `api_key` explicitly. Optional request field `dashboard_url` is mirrored into the QR payload and response. |
|
||||
| `/pairing/approve` | POST | **Loopback only, Phase 3 stub.** Same wire shape and loopback gate as `/pairing/register` — present so the Android client can target the route today. The semantic difference (operator reviewing a phone-initiated pending code before approval) still needs the pending-codes store + approval UX, marked `# TODO(Phase 3)` in the handler. |
|
||||
@@ -378,10 +379,11 @@ See [`docs/spec.md` §3.3](spec.md) for the full auth flow and the QR wire forma
|
||||
| `/sessions/{token_prefix}` | PATCH | Bearer-auth'd, self-targeted, and reduction-only. Body `{"ttl_seconds": 3600}`, `{"grants": {"terminal": 600}}`, or both may shorten the caller's current session policy. A bearer cannot target another session, extend its lifetime, add or lengthen grants, or change a finite expiry to never-expire; authority-increasing changes require a fresh operator-approved pairing flow. Omitted grants retain their existing absolute ceilings and are clamped if the parent session is shortened. Returns 200 with the reduced `{expires_at, grants}`; 400 on missing/invalid or unknown grants; 403 on cross-session targets or policy expansion; 404 on prefix miss; 409 on ambiguous prefix. |
|
||||
| `/chat/image-activity` | GET | Optional read-only Standard Gateway compatibility route. Requires a valid Relay bearer with an active `chat` grant and query parameters `profile`, `session_id`, and `since` (Unix seconds). Reads the selected profile's Hermes `state.db` without mutation and returns persisted `image_generate` calls as `running` or `completed`. Android polls only during an active turn, deduplicates against native Gateway tool events, and silently disables the bridge when the route is absent. |
|
||||
| `/clipboard/inbox` | POST | Bearer-auth'd clipboard rendezvous used by remote clients before native platform clipboard fallback. |
|
||||
| `/media/register` | POST | **Loopback only.** Register a file path with the in-memory `MediaRegistry` and receive an opaque token. Used by host-local tools (`android_screenshot` etc.) to make a file fetchable by the paired phone without leaking the filesystem path. Request body: `{"path": "/abs/path", "content_type": "image/jpeg", "file_name": "screenshot.jpg"}`. Response: `{"ok": true, "token": "<url-safe-16>", "expires_at": <unix>}`. Returns 403 for non-loopback callers, 400 on validation failure (relative path, missing file, oversized, outside allowed roots, etc). Path sandboxing is enforced server-side — see ADR 14. |
|
||||
| `/media/upload` | POST | Bearer-auth'd small upload endpoint for phone-originated media. Accepts JSON `{file_name, content_type, content}` where `content` is base64 and registers the decoded bytes with the media registry. |
|
||||
| `/media/register` | POST | **Loopback only.** Register a file path with the in-memory `MediaRegistry` and receive an opaque token. Host-owned files are never deleted by the registry. A relay-managed `android_screenshot_` temp file can opt into cleanup with `owned_file: true`; the registry validates its location and name. Request body: `{"path": "/abs/path", "content_type": "image/png", "file_name": "screenshot.png"}`. Response: `{"ok": true, "token": "<token>", "expires_at": <unix>}`. Returns 403 for non-loopback callers, 400 on validation failure. |
|
||||
| `/media/upload` | POST | Bearer-authenticated multipart upload for phone-originated media (`file` field). Streams to a size-bounded relay-owned temporary file and registers a token. Relay-owned files are removed on token expiry, LRU eviction, or orderly shutdown. |
|
||||
| `/media/{token}/sensitive` | POST | **Loopback only.** Mark an existing token sensitive before the host tool returns its marker. The subsequent media fetch includes `X-Media-Sensitive: 1`; no second image copy is created. Returns 404 for missing or expired tokens. |
|
||||
| `/media/{token}` | GET | Stream the bytes of a previously-registered file. Requires `Authorization: Bearer <session_token>` (same token the WSS channel uses; validated against `SessionManager`). Response has the registered `Content-Type` plus `Content-Disposition: inline; filename="..."` when a file name was provided. Returns 401 without auth or with an invalid bearer, 404 if the token is unknown or expired. The client never sees the underlying path — the token is the only handle. |
|
||||
| `/media/by-path` | GET | Stream the bytes of a file **addressed by absolute path** rather than by registry token. Covers the case where an agent's LLM freeform-emits a `MEDIA:/abs/path.ext` marker in its response text (upstream `hermes-agent/agent/prompt_builder.py` explicitly instructs the model to do this) — no loopback register step is needed. Query parameters: `path` (required, absolute) and `content_type` (optional; otherwise guessed from extension via Python's `mimetypes`). Requires `Authorization: Bearer <session_token>`. Path sandboxing is identical to `/media/register`: must be absolute, must `realpath`-resolve under an allowed root (`tempfile.gettempdir()` + `HERMES_WORKSPACE` + `RELAY_MEDIA_ALLOWED_ROOTS`), must exist, must be a regular file, must fit under `RELAY_MEDIA_MAX_SIZE_MB`. Response carries `Content-Type` and `Content-Disposition: inline; filename="<basename>"`. Error shapes: 400 missing `path`; 401 missing/invalid bearer; 403 outside sandbox / not absolute / too large; 404 file not found or not a regular file. See ADR 14. |
|
||||
| `/media/by-path` | GET | Bearer-authenticated fetch for an absolute-path `MEDIA:/...` marker. Requires a regular file within the size cap and always rejects credential/system paths. Allowed-root enforcement is opt-in through `RELAY_MEDIA_STRICT_SANDBOX=1`; default mode accepts other absolute readable paths. Optional `content_type` overrides extension guessing. Returns 400 for a missing path, 401 for invalid auth, 403 for policy/size failures, and 404 for a missing file. |
|
||||
| `/voice/transcribe` | POST | Bearer-auth'd via either a Relay session token with active `voice:stt` grant or a valid Hermes API bearer token. Non-loopback API-bearer calls require HTTPS unless `RELAY_ALLOW_INSECURE_API_BEARER=1`. `multipart/form-data` with an audio file field (any name — first field is used). Android may include `?profile=<name>` so the active profile context is recorded in the response/UI; execution still goes through the upstream STT helper. |
|
||||
| `/voice/synthesize` | POST | Bearer-auth'd via either a Relay session token with active `voice:tts` grant or a valid Hermes API bearer token. Non-loopback API-bearer calls require HTTPS unless `RELAY_ALLOW_INSECURE_API_BEARER=1`. JSON body `{"text": "...", "profile": "mizu"}` (max 5000 chars) runs the basic fallback TTS helper and serves the resulting mp3. Normal assistant speech prefers `/voice/output/*`. |
|
||||
| `/voice/config` | GET | Bearer-auth'd via either a Relay session token with active `voice:config` grant or a valid Hermes API bearer token. Optional `?profile=<name>` resolves `tts:` / `stt:` from `~/.hermes/profiles/<name>/config.yaml` where present, otherwise falls back. Returns provider info plus `profile`, `config_scope`, and `fallback_to_global`. |
|
||||
|
||||
@@ -152,6 +152,14 @@ public `:8767`.
|
||||
|
||||
### Hermes Secure Link
|
||||
|
||||
Start with the shared read-only setup check: **Relay → Remote Access → Secure
|
||||
Link** in Dashboard or the Desktop Relay pane, or
|
||||
`hermes relay secure-link --host <phone-reachable-address> --port 9443` on the
|
||||
host. It verifies prerequisites, previews environment/startup settings and
|
||||
restart impact, and requires a re-check of the active listener before offering
|
||||
the pairing handoff. It does not guess a service manager, write configuration,
|
||||
open ports, or rotate keys. See the [guided user flow](../user-docs/guide/remote-access.md#optional-hermes-secure-link).
|
||||
|
||||
Enable Secure Link when a pairing-pinned unified route is desired. Its
|
||||
default listener is `https://<host>:9443`; Relay health is
|
||||
`GET /relay/health`, the authenticated Relay WebSocket is
|
||||
|
||||
@@ -15,6 +15,29 @@ must make the listener reachable.
|
||||
Secure Link is not an arbitrary reverse proxy and does not replace any
|
||||
service's authentication or authorization.
|
||||
|
||||
## Guided setup control surface
|
||||
|
||||
`GET /secure-link/preflight` is a loopback-only, read-only Relay operator route.
|
||||
The authenticated Dashboard/Desktop plugin forwards it through
|
||||
`GET /remote-access/secure-link/preflight`; `hermes relay secure-link` consumes
|
||||
the same report from the running Relay. Public `/relay/*` ingress never exposes
|
||||
this operator endpoint. Client input selects only the proposed listener address
|
||||
and port; it cannot select a probe upstream or certificate/key file.
|
||||
|
||||
The report checks a usable bind address, port availability, existing certificate
|
||||
identity, fixed loopback upstreams, Dashboard authentication, and restart impact.
|
||||
It does not mutate configuration, generate/rotate secrets, or manage services.
|
||||
Instructions preserve the existing service owner and require an explicit operator
|
||||
restart. Re-checking an active matching origin enables the pairing handoff; a
|
||||
proposed address alone never enables it. Report readiness is not client sign-in,
|
||||
network reachability from another device, or Gateway Chat readiness.
|
||||
|
||||
Pairing previews derive declared namespaces from validated proxy advertisements
|
||||
without displaying their certificate/pin or treating ordinary system-TLS probe
|
||||
failure as proof that the paired route is broken. Signed QR import remains the
|
||||
client trust ceremony. Unsupported/older Relay setup endpoints fail visibly and
|
||||
never fall back to browser-side configuration writes.
|
||||
|
||||
## Trust boundaries
|
||||
|
||||
- The operator-reviewed pairing QR is the first-pair trust ceremony. It must
|
||||
@@ -58,6 +81,10 @@ service's authentication or authorization.
|
||||
Relay still requires its normal first-frame pairing/session authentication,
|
||||
enforces expiry and grants, rate-limits failures, and binds the resulting
|
||||
connection to that authenticated session.
|
||||
- Relay-native `/voice/*` HTTP routes and management/session HTTP routes are
|
||||
not exposed beneath `/relay`. A pinned client alone does not enable them.
|
||||
Standard voice uses the independently authenticated Dashboard namespace;
|
||||
native Relay voice requires a separately supported ingress.
|
||||
- Client-controlled hosts, origins, absolute URLs, proxy headers, redirects,
|
||||
encoded separators, and path traversal can never select an upstream.
|
||||
- The external `Host` header is validated against the configured Secure Link
|
||||
@@ -67,6 +94,17 @@ service's authentication or authorization.
|
||||
- HTTP request and response bodies are bounded, and upstream connect/read/total
|
||||
timeouts are finite. Long-lived traffic uses the separately bounded WebSocket
|
||||
path rather than an unlimited HTTP proxy request.
|
||||
- Dashboard login HTML and JSON landing paths are rewritten under `/dashboard`.
|
||||
Rewrites request identity encoding and enforce the response limit while reading,
|
||||
including chunked responses. An upstream that ignores the identity request and
|
||||
sends compressed HTML/JSON receives a 502; compressed bytes are never returned
|
||||
with their encoding header removed.
|
||||
- Gateway query tickets and ticket subprotocols survive the WebSocket proxy.
|
||||
Upstream authenticates before the outer upgrade succeeds. Only the selected
|
||||
public protocol is returned; ticket-bearing protocols are never reflected.
|
||||
The upstream leg disables compression independently of the downstream leg.
|
||||
- Public Relay health reads version and counters from the same server instance;
|
||||
it does not make a second loopback Relay health request.
|
||||
- Secure Link failing to initialize must not silently advertise a
|
||||
candidate. It must not make the ordinary Relay unavailable unless the
|
||||
operator explicitly configured strict startup behavior.
|
||||
@@ -81,6 +119,10 @@ service's authentication or authorization.
|
||||
remains enabled; clients never disable certificate validation to learn a pin.
|
||||
- The pin and each service credential are scoped to the exact host and port.
|
||||
Redirects or retries outside that authority fail before credentials are sent.
|
||||
- Android enforces the paired leaf SPKI inside its trust manager even when system
|
||||
trust succeeds. HTTP and WebSocket requests use the same HTTPS authority guard;
|
||||
automatic redirects are disabled. Gateway route changes replace the ticket and
|
||||
socket transport together, discarding a ticket minted for a superseded route.
|
||||
- A declared Secure Link route fails closed if its pinned client cannot be
|
||||
built; it must not fall back to a generic TLS or TOFU client.
|
||||
- UI security labels derive from the validated proxy contract, not from a
|
||||
|
||||
+30
-2
@@ -117,6 +117,14 @@ 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.
|
||||
|
||||
Users may explicitly accept cleartext HTTP risk for an otherwise-restricted
|
||||
Dashboard origin. Consent belongs to the saved connection and exact HTTP host
|
||||
and port. It neither detects nor enforces VPN protection, asserts encryption,
|
||||
bypasses authentication, nor grants Relay access. Address changes require fresh
|
||||
consent and retire the previous origin's exception and Dashboard credentials.
|
||||
Public status proves discovery only; setup verifies protected authentication
|
||||
before presenting it as verified, and Chat readiness still requires Gateway Ready.
|
||||
|
||||
Dashboard route/auth availability and Gateway socket readiness are separate
|
||||
authorities. A successful Dashboard status/auth probe enables Manage, session
|
||||
browsing, and standard voice, but Chat is connected through Gateway only after
|
||||
@@ -126,6 +134,22 @@ authentication, unsupported-protocol, and access-policy failures stop automatic
|
||||
retry. After a socket has reached Ready once, ordinary network loss remains a
|
||||
non-terminal reconnect episode while Chat is visible.
|
||||
|
||||
Gateway background protection follows process-local, connection/profile/session
|
||||
turn leases. Idle retention remains opt-in through Persistent connection. An
|
||||
accepted Android foreground-service start is promoted before shutdown, including
|
||||
when a turn finishes before the start callback arrives. Overlapping demand uses
|
||||
the latest state; old start commands never restore old turn counts. New service
|
||||
launches wait for a visible application lifecycle, while an existing foreground
|
||||
service continues protecting active work after backgrounding. A rejected launch
|
||||
is logged and may retry on a later foreground transition.
|
||||
|
||||
The notification's **Turn off always-on** action persists that preference before
|
||||
the collector reconciles current turn leases. It does not interrupt Hermes work.
|
||||
Task removal drops local foreground protection without clearing chat-owned
|
||||
leases or assuming process termination; if the process survives, returning to
|
||||
the app can protect unfinished turns again. The service is not sticky and does
|
||||
not restart idle retention from stale notification actions after process death.
|
||||
|
||||
The session drawer is a Dashboard REST consumer, not a Gateway-socket view.
|
||||
Profile-scoped session browsing and stored transcript reads remain available
|
||||
whenever the authenticated Dashboard route is available, including while the
|
||||
@@ -667,6 +691,9 @@ The bridge UI drives — and is driven by — Tier 5 safety-rails (`BridgeSafety
|
||||
**Global unattended-access affordance (v0.4.1).** When master + unattended are both on (sideload only), `UnattendedGlobalBanner` renders as a 28dp amber strip at the top of `RelayApp`'s scaffold on every tab — pulsing dot + "Unattended access ON — agent can wake and drive this device" + chevron → tap navigates to Bridge. Theme-aware colours (amber-on-dark in dark mode, dark-amber-on-pale-amber in light). The banner handles visibility while the user is INSIDE Hermes-Relay; the existing WindowManager `BridgeStatusOverlayChip` handles visibility when the app is BACKGROUNDED. See `docs/decisions.md` §18 for the split rationale.
|
||||
|
||||
### Settings Tab
|
||||
|
||||
At startup, the first app frame uses one saved Appearance snapshot for its Compose palette, while AppCompat's activity night mode follows that same snapshot. The splash stays up until the snapshot is loaded; Auto follows the system, and fixed or custom presets keep their own light/dark mode.
|
||||
|
||||
- **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. 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.
|
||||
@@ -714,6 +741,7 @@ HTTP routes registered by `create_app()` in `plugin/relay/server.py`:
|
||||
|-------|--------|---------|
|
||||
| `/ws`, `/` | GET (upgrade) | WebSocket handler — main multiplexed channel |
|
||||
| `/health` | GET | Health check — returns `{status, version, clients, sessions}` |
|
||||
| `/secure-link/preflight` | GET | **Loopback only.** Read-only Secure Link setup checks and startup instructions for a proposed `host` and `port`. No configuration, key, or service mutations. Dashboard/Desktop and the host CLI share this report. |
|
||||
| `/pairing/register` | POST | **Loopback only.** Pre-register an externally-provided pairing code. Used by the pair command (`hermes pair`, `/hermes-relay-pair`, or compatibility `hermes-pair`) to inject codes that will appear in QR payloads. Request: `{"code": "ABCD12"}`. Rejects non-loopback peers with HTTP 403. |
|
||||
| `/pairing/mint` | POST | **Loopback only.** Mint a fresh pairing code and signed QR payload plus `pairing_url` (`hermes-relay://pair?payload=...`) for dashboard and CLI/tray pair/repair flows. Optional request field `dashboard_url` is copied into the QR payload for custom dashboard routes. |
|
||||
| `/api/profiles/{name}/config` | GET | Profile-scoped read-only config. Returns `{profile, path, config, readonly: true}`. Loopback callers receive the parsed `config.yaml` and absolute path. Remote callers require a relay session bearer and receive only the explicitly public `description` and `model.default` fields with `path: "config.yaml"`; arbitrary provider, platform, integration, and extension sections never cross the remote boundary. 404 on missing profile / missing config.yaml; 500 on yaml parse error. See §22 in decisions.md. |
|
||||
@@ -952,7 +980,7 @@ Tools register against the Hermes plugin API in `plugin/tools/android_tool.py` (
|
||||
|------|-----------|---------|--------|
|
||||
| `android_ping` | `GET /ping` | Liveness check — does not require master enable | sideload Device Control |
|
||||
| `android_screen` | `GET /screen` | Serialize the accessibility tree → `ScreenContent` | sideload Device Control |
|
||||
| `android_screenshot` | `GET /screenshot` | `MediaProjection` PNG → `MEDIA:hermes-relay://<token>` | sideload Device Control |
|
||||
| `android_screenshot` | `GET /screenshot`, then authenticated `GET /media/<token>` | `MediaProjection` PNG → bounded native image tool result with the `MEDIA:hermes-relay://<token>` phone-delivery marker; older inline base64 responses remain readable | sideload Device Control |
|
||||
| `android_current_app` | `GET /current_app` | Best-effort foregrounded package name; use `/screen` for verification | sideload Device Control |
|
||||
| `android_get_apps` (`/apps` legacy) | `GET /get_apps` | Installed launcher apps | sideload Device Control |
|
||||
| `android_tap` | `POST /tap` | Tap at `(x, y)` or on resolved `node_id` | sideload Device Control |
|
||||
@@ -1199,7 +1227,7 @@ utilities.
|
||||
transfers ownership so assistant-process cleanup cannot cancel the main-app flow.
|
||||
While keyguard is active, the surface keeps only generic phase and retry copy;
|
||||
transcript, response, route-specific errors, and screen context remain hidden.
|
||||
- Stable voice integrates with `ChatViewModel` by **observing** `messages: StateFlow`; transcribed text goes through normal `chatVm.sendMessage(text)` so voice utterances appear as regular user messages in chat history. Experimental Realtime Agent creates a mirrored chat turn and applies broker events directly so tool state, transcript text, assistant deltas, and final responses appear without leaving voice mode.
|
||||
- Stable voice observes the submitted run through `messages: StateFlow`; transcribed text uses the normal Chat pipeline. While voice remains active, successful live unsolicited Gateway turns in that exact conversation also deliver their settled answer once through the configured voice output. Delivery waits for current capture/playback; Stop, exit, engine changes, and conversation changes invalidate pending speech. History/reconnect replay and passive observation never create speech. Experimental Realtime Agent retains its separate mirrored chat turn and broker events.
|
||||
- `VoiceModeOverlay` — full-screen UI with the MorphingSphere at 60% height in `voiceMode=true`, transcribed + response text, mic button supporting Tap / Hold / Continuous interaction modes.
|
||||
- The optional `SYSTEM_ALERT_WINDOW` Voice control is user-invoked from an
|
||||
active in-app turn. It starts as a wide compact bar, expands for transcript,
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
[versions]
|
||||
appVersionName = "1.17.0"
|
||||
appVersionCode = "57"
|
||||
agp = "9.4.0"
|
||||
kotlin = "2.4.10"
|
||||
compose-bom = "2026.08.00"
|
||||
navigation-compose = "2.10.0"
|
||||
agp = "9.4.1"
|
||||
kotlin = "2.4.20"
|
||||
compose-bom = "2026.09.00"
|
||||
navigation-compose = "2.10.1"
|
||||
okhttp = "5.5.0"
|
||||
kotlinx-serialization = "1.11.0"
|
||||
kotlinx-coroutines = "1.11.0"
|
||||
mockk = "1.14.11"
|
||||
robolectric = "4.16.1"
|
||||
robolectric = "4.17"
|
||||
konsist = "0.17.3"
|
||||
security-crypto = "1.1.0"
|
||||
tink-android = "1.23.0"
|
||||
@@ -22,13 +22,13 @@ exifinterface = "1.4.2"
|
||||
datastore = "1.2.1"
|
||||
splashscreen = "1.2.0"
|
||||
markdown-renderer = "0.45.0"
|
||||
coil = "3.6.2"
|
||||
coil = "3.6.3"
|
||||
haze = "1.7.3"
|
||||
mlkit-barcode = "17.3.0"
|
||||
zxing-core = "3.5.4"
|
||||
camera = "1.6.1"
|
||||
play-publisher = "4.1.1"
|
||||
media3 = "1.11.0"
|
||||
media3 = "1.11.1"
|
||||
androidVad = "2.0.10"
|
||||
sherpaOnnx = "v1.13.4"
|
||||
onnxRuntime = "1.27.0"
|
||||
|
||||
@@ -24,6 +24,8 @@ import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
from argparse import Namespace
|
||||
|
||||
|
||||
# ── hermes pair ───────────────────────────────────────────────────────────────
|
||||
@@ -154,12 +156,24 @@ def register_relay_cli(subparser) -> None:
|
||||
"""
|
||||
sub = subparser.add_subparsers(dest="relay_cmd", required=True)
|
||||
|
||||
setup = sub.add_parser("secure-link", help="Check Secure Link readiness and show setup instructions (read-only)")
|
||||
setup.add_argument("--host", help="LAN, VPN, or DNS address the phone will use")
|
||||
setup.add_argument("--port", type=int, help="Secure Link HTTPS port (default: current configuration)")
|
||||
setup.add_argument("--relay-port", type=int, default=None, help="Running Relay loopback port")
|
||||
setup.add_argument("--json", action="store_true", help="Emit the same readiness report used by Dashboard and Desktop")
|
||||
setup.set_defaults(func=relay_secure_link_command)
|
||||
|
||||
start = sub.add_parser(
|
||||
"start",
|
||||
help="Run the Hermes-Relay WSS server (chat + terminal + bridge)",
|
||||
)
|
||||
start.add_argument("--host", metavar="HOST", help="Bind address (default: 0.0.0.0)")
|
||||
start.add_argument("--port", type=int, help="Listen port (default: 8767)")
|
||||
import argparse
|
||||
start.add_argument("--secure-link", action=argparse.BooleanOptionalAction, default=None,
|
||||
help="Enable or disable the optional pinned-TLS listener")
|
||||
start.add_argument("--secure-link-host", help="Secure Link bind/advertised address")
|
||||
start.add_argument("--secure-link-port", type=int, help="Secure Link HTTPS port (default: 9443)")
|
||||
start.add_argument(
|
||||
"--no-ssl",
|
||||
action="store_true",
|
||||
@@ -319,6 +333,45 @@ def relay_doctor_command(args) -> None:
|
||||
raise SystemExit(code)
|
||||
|
||||
|
||||
def relay_secure_link_command(args: Namespace) -> None:
|
||||
"""Read the running host's report without enabling, rotating, or restarting."""
|
||||
relay_port = args.relay_port or int(os.environ.get("RELAY_PORT", "8767"))
|
||||
if not 1 <= relay_port <= 65535:
|
||||
raise SystemExit("Relay port must be between 1 and 65535")
|
||||
query = urllib.parse.urlencode({
|
||||
key: value for key, value in {"host": args.host, "port": args.port}.items() if value is not None
|
||||
})
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{relay_port}/secure-link/preflight?{query}", timeout=15) as response:
|
||||
report = json.load(response)
|
||||
except (urllib.error.URLError, OSError, ValueError) as exc:
|
||||
raise SystemExit("Secure Link checks are unavailable. Start/update Relay and retry; no configuration was changed.") from exc
|
||||
if not isinstance(report, dict) or report.get("schema_version") != 1 or not isinstance(report.get("checks"), list):
|
||||
raise SystemExit("Relay returned an unsupported setup report. Update Relay and retry; no configuration was changed.")
|
||||
if args.json:
|
||||
sys.stdout.write(json.dumps(report, indent=2) + "\n")
|
||||
else:
|
||||
lines = [f"Secure Link: {report['state'].replace('_', ' ')}"]
|
||||
if report.get("url"):
|
||||
lines.append(f"HTTPS origin: {report['url']}")
|
||||
lines.extend(f"[{c['status']}] {c['label']}: {c['detail']}" for c in report["checks"])
|
||||
lines.extend([report["restart_notice"], report.get("configuration_note", "")])
|
||||
if report["ready_to_enable"] and not report["pairing_ready"]:
|
||||
lines.append("Add these settings to the existing Relay environment, then restart its owner:")
|
||||
lines.extend(f"{key}={value}" for key, value in report["environment"].items())
|
||||
lines.extend([
|
||||
"Or add to the existing Relay startup command: " + " ".join(report["start_arguments"]),
|
||||
"Re-run this check after restart. Do not launch a second Relay.",
|
||||
])
|
||||
if report["pairing_ready"]:
|
||||
lines.extend(["Create a fresh signed QR: hermes pair --png",
|
||||
"Scan it, then sign into Dashboard on the client. Listener health is not Chat readiness."])
|
||||
lines.append("To disable: set RELAY_SECURE_LINK_ENABLED=0 (or use --no-secure-link), then restart Relay's owner.")
|
||||
sys.stdout.write("\n".join(lines) + "\n")
|
||||
if not report["ready_to_enable"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def relay_compat_command(args) -> None:
|
||||
"""Manage the optional legacy compatibility startup hook."""
|
||||
from .compat import compat_command
|
||||
@@ -436,6 +489,12 @@ def relay_start_command(args) -> None:
|
||||
config.port = args.port
|
||||
if getattr(args, "webapi_url", None):
|
||||
config.webapi_url = args.webapi_url
|
||||
if getattr(args, "secure_link", None) is not None:
|
||||
config.secure_proxy_enabled = args.secure_link
|
||||
if getattr(args, "secure_link_host", None):
|
||||
config.secure_proxy_host = args.secure_link_host
|
||||
if getattr(args, "secure_link_port", None) is not None:
|
||||
config.secure_proxy_port = args.secure_link_port
|
||||
if getattr(args, "log_level", None):
|
||||
config.log_level = args.log_level
|
||||
if getattr(args, "shell", None):
|
||||
|
||||
@@ -12,6 +12,13 @@ independent of the Hermes-Relay service. It renders a tokenless setup QR contain
|
||||
standard Dashboard/Gateway connection. Hermes-Relay pairing remains a separate,
|
||||
explicit **Pair new device** flow.
|
||||
|
||||
**Remote Access → Hermes Secure Link → Set up Secure Link** runs the host's
|
||||
read-only preflight, displays blockers and restart impact, and supplies settings
|
||||
for the existing Relay owner. **Check again** must confirm the active selected
|
||||
origin before **Create pairing QR** is offered. This flow does not persist settings
|
||||
or restart services. The Desktop Relay pane and `hermes relay secure-link` use the
|
||||
same backend report; Android imports the resulting QR and signs in separately.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Node.js 18+
|
||||
|
||||
Vendored
+7
-6
File diff suppressed because one or more lines are too long
@@ -600,6 +600,7 @@ async def _proxy_get(
|
||||
path: str,
|
||||
*,
|
||||
params: Optional[dict[str, Any]] = None,
|
||||
timeout: float = _TIMEOUT,
|
||||
) -> Any:
|
||||
"""Forward a GET to the relay, translating errors per this module's contract.
|
||||
|
||||
@@ -609,7 +610,7 @@ async def _proxy_get(
|
||||
"""
|
||||
url = f"{_RELAY_BASE}{path}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
|
||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||
resp = await client.get(url, params=params)
|
||||
except (httpx.TimeoutException, httpx.ConnectError, httpx.TransportError) as err:
|
||||
raise _relay_unreachable(err) from err
|
||||
@@ -1090,6 +1091,7 @@ async def get_remote_access_status() -> dict[str, Any]:
|
||||
|
||||
secure_link: dict[str, Any] = {
|
||||
"enabled": False,
|
||||
"state": "disabled",
|
||||
"reason": "Hermes Secure Link is not enabled on the Relay host",
|
||||
}
|
||||
try:
|
||||
@@ -1105,6 +1107,7 @@ async def get_remote_access_status() -> dict[str, Any]:
|
||||
reach = relay_secure_link.get("reach", {}) if isinstance(relay_secure_link, dict) else {}
|
||||
secure_link = {
|
||||
"enabled": True,
|
||||
"state": "enabled",
|
||||
"role": candidate.get("role"),
|
||||
"recommended": candidate.get("recommended") is True,
|
||||
"security": candidate.get("security"),
|
||||
@@ -1116,9 +1119,16 @@ async def get_remote_access_status() -> dict[str, Any]:
|
||||
"last_error": reach.get("last_error") if isinstance(reach.get("last_error"), str) else None,
|
||||
} if isinstance(reach, dict) else {"enabled": False, "state": "disabled"},
|
||||
}
|
||||
elif isinstance(relay_health, dict) and isinstance(relay_health.get("secure_link"), dict) and relay_health["secure_link"].get("enabled") is True:
|
||||
secure_link = {
|
||||
"enabled": False,
|
||||
"state": "unavailable",
|
||||
"reason": "Secure Link is configured but its listener is unavailable. Run setup checks before retrying.",
|
||||
}
|
||||
except HTTPException as exc:
|
||||
secure_link = {
|
||||
"enabled": False,
|
||||
"state": "unknown",
|
||||
"reason": f"Relay status unavailable: {exc.detail}",
|
||||
}
|
||||
|
||||
@@ -1134,6 +1144,14 @@ async def get_remote_access_status() -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/remote-access/secure-link/preflight")
|
||||
async def get_secure_link_preflight(host: str | None = None, port: str | None = None) -> Any:
|
||||
"""Use the running Relay's read-only checks, not the Dashboard's environment."""
|
||||
return await _proxy_get("/secure-link/preflight", params={
|
||||
key: value for key, value in {"host": host, "port": port}.items() if value is not None
|
||||
}, timeout=15.0)
|
||||
|
||||
|
||||
@router.post("/remote-access/tailscale/enable")
|
||||
async def tailscale_enable(
|
||||
body: dict[str, Any] = Body(default_factory=dict),
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
const SDK = window.__HERMES_PLUGIN_SDK__;
|
||||
const { React } = SDK;
|
||||
const { useState, useRef, useEffect } = SDK.hooks;
|
||||
const { Input, Label } = SDK.components;
|
||||
|
||||
import { getSecureLinkPreflight } from "../lib/api.js";
|
||||
import { Button, Badge, Alert, AlertTitle, AlertDescription } from "../lib/ui-shims.jsx";
|
||||
|
||||
/** Readiness and instructions only: the browser never guesses a service owner. */
|
||||
export default function SecureLinkSetup({ status, onPair, onInvalidateInvite, pairingBusy = false }) {
|
||||
const initial = (() => { try { return new URL(status.url); } catch { return null; } })();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [host, setHost] = useState(initial?.hostname || "");
|
||||
const [port, setPort] = useState(initial?.port || "9443");
|
||||
const [report, setReport] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const sequence = useRef(0);
|
||||
useEffect(() => {
|
||||
sequence.current += 1;
|
||||
setReport(null);
|
||||
setBusy(false);
|
||||
onInvalidateInvite?.();
|
||||
}, [status.url]);
|
||||
const change = (setter, value) => {
|
||||
sequence.current += 1;
|
||||
setter(value);
|
||||
setReport(null);
|
||||
setError("");
|
||||
setCopied(false);
|
||||
setBusy(false);
|
||||
onInvalidateInvite?.();
|
||||
};
|
||||
const check = async () => {
|
||||
const request = ++sequence.current;
|
||||
setOpen(true);
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setCopied(false);
|
||||
onInvalidateInvite?.();
|
||||
try {
|
||||
const next = await getSecureLinkPreflight({ host: host.trim() || undefined, port });
|
||||
if (request !== sequence.current) return;
|
||||
if (next?.schema_version !== 1 || !Array.isArray(next.checks)) throw new Error("Relay returned an unsupported setup report.");
|
||||
setReport(next);
|
||||
if (!host.trim() && next.host) setHost(next.host);
|
||||
} catch (err) {
|
||||
if (request !== sequence.current) return;
|
||||
setReport(null);
|
||||
setError(`Setup checks unavailable. Confirm Relay is running and supports Secure Link setup checks. ${err.message || ""}`);
|
||||
} finally {
|
||||
if (request === sequence.current) setBusy(false);
|
||||
}
|
||||
};
|
||||
const environment = Object.entries(report?.environment || {}).map(([key, value]) => `${key}=${value}`).join("\n");
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(environment);
|
||||
setCopied(true);
|
||||
} catch { setError("Clipboard access is unavailable. Select and copy the settings below."); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{!open ? <Button variant="outline" onClick={check}>{status.enabled ? "Check Secure Link" : "Set up Secure Link"}</Button> : (
|
||||
<div className="space-y-4 border-t border-border pt-3">
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">1. Check this server</h4>
|
||||
<p className="text-xs text-muted-foreground">Checks are read-only. They do not change settings, create keys, or restart services.</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="secure-link-host">Address the phone will use</Label>
|
||||
<Input id="secure-link-host" value={host} placeholder="192.168.1.20 or relay.example"
|
||||
onChange={(event) => change(setHost, event.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="secure-link-port">HTTPS port</Label>
|
||||
<Input id="secure-link-port" value={port} inputMode="numeric"
|
||||
onChange={(event) => change(setPort, event.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" disabled={busy} onClick={check}>{busy ? "Checking…" : "Check again"}</Button>
|
||||
</div>
|
||||
{error ? <Alert variant="destructive"><AlertTitle>Check needed</AlertTitle><AlertDescription>{error}</AlertDescription></Alert> : null}
|
||||
{report ? (
|
||||
<>
|
||||
<div role="list" className="space-y-2" aria-live="polite">
|
||||
{report.checks.map((item) => (
|
||||
<div role="listitem" key={item.id} className="rounded-md border border-border p-3 space-y-1">
|
||||
<div className="flex items-center justify-between gap-2 text-sm">
|
||||
<span>{item.label}</span><Badge variant={item.status === "blocked" ? "destructive" : "outline"}>
|
||||
{item.status === "ok" ? "Checked" : item.status === "warning" ? "Optional / unavailable" : "Needs attention"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{item.detail}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{report.ready_to_enable && !report.pairing_ready ? (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">2. Review and enable</h4>
|
||||
<p className="font-mono text-xs break-all">{report.url}</p>
|
||||
{report.requires_repair ? <p className="text-xs text-muted-foreground">This changes the paired address or port. Existing clients must re-pair after activation; no certificate is replaced by this check.</p> : null}
|
||||
<p className="text-xs text-muted-foreground">Add these settings to the existing Relay environment. Restart its owner, then choose Check again. Do not start a second Relay.</p>
|
||||
<p className="text-xs text-muted-foreground">{report.connected_clients} Relay client(s) connected. {report.restart_notice}</p>
|
||||
<p className="text-xs text-muted-foreground">{report.configuration_note}</p>
|
||||
<pre className="rounded-md bg-muted/20 p-3 text-xs whitespace-pre-wrap break-all select-text">{environment}</pre>
|
||||
<Button size="sm" variant="outline" onClick={copy}>{copied ? "Copied" : "Copy settings"}</Button>
|
||||
<details className="text-xs text-muted-foreground">
|
||||
<summary className="cursor-pointer">Foreground / CLI startup</summary>
|
||||
<p className="mt-2">Add to your existing <code>hermes relay start</code> command, preserving its other arguments:</p>
|
||||
<pre className="mt-2 whitespace-pre-wrap break-all select-text">{report.start_arguments.join(" ")}</pre>
|
||||
</details>
|
||||
</div>
|
||||
) : null}
|
||||
{report.pairing_ready ? (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">3. Pair a device</h4>
|
||||
<p className="font-mono text-xs break-all">{report.current_url}</p>
|
||||
<p className="text-xs text-muted-foreground">Secure Link is listening. Create a fresh signed QR below, scan it in Android, then sign into Dashboard. Chat becomes ready only after Gateway connects. Existing devices must re-pair to import this certificate and pin.</p>
|
||||
<Button disabled={pairingBusy || busy} onClick={() => onPair(report.current_url)}>{pairingBusy ? "Creating invite…" : "Create pairing QR"}</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<details className="text-xs text-muted-foreground">
|
||||
<summary className="cursor-pointer">Disable or recover</summary>
|
||||
<p className="mt-2">Set <code>RELAY_SECURE_LINK_ENABLED=0</code> (or replace the startup flag with <code>--no-secure-link</code>), then restart Relay using its existing manager. Keep the certificate and key if you intend to re-enable the same route. Address or certificate changes require explicit re-pairing.</p>
|
||||
<p className="mt-2">This flow does not restart services or open firewall ports. If activation fails, restore the previous Relay settings and check its health before retrying.</p>
|
||||
</details>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -84,6 +84,13 @@ export function getRemoteAccessStatus() {
|
||||
return fetchJSON("/remote-access/status");
|
||||
}
|
||||
|
||||
export function getSecureLinkPreflight({ host, port } = {}) {
|
||||
const query = new URLSearchParams();
|
||||
if (host !== undefined) query.set("host", host);
|
||||
if (port !== undefined) query.set("port", port);
|
||||
return fetchJSON(`/remote-access/secure-link/preflight?${query}`);
|
||||
}
|
||||
|
||||
export function enableTailscale(port) {
|
||||
return fetchJSON("/remote-access/tailscale/enable", {
|
||||
method: "POST",
|
||||
@@ -115,12 +122,21 @@ export function putPublicUrl(url, { legacyDirectRelay = false } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
export function probeEndpoints(candidates) {
|
||||
return fetchJSON("/remote-access/probe", {
|
||||
export async function probeEndpoints(candidates) {
|
||||
const entries = Array.isArray(candidates) ? candidates : [];
|
||||
// A generic server-side TLS probe does not own the recipient's paired
|
||||
// trust. Do not misreport self-signed Secure Link as broken or disable TLS.
|
||||
const paired = entries.filter((item) => item.requires_paired_client).map((item) => ({
|
||||
...item, reachable: null, status: null, latency_ms: null, error: null,
|
||||
}));
|
||||
const ordinary = entries.filter((item) => !item.requires_paired_client);
|
||||
if (!ordinary.length) return { results: paired };
|
||||
const result = await fetchJSON("/remote-access/probe", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ candidates: Array.isArray(candidates) ? candidates : [] }),
|
||||
body: JSON.stringify({ candidates: ordinary }),
|
||||
});
|
||||
return { ...result, results: [...(result.results || []), ...paired] };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user