Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52f3f75658 | ||
|
|
1d25985aca | ||
|
|
500cc83de6 | ||
|
|
7d3c761c6a | ||
|
|
2e097035fb | ||
|
|
280c20dbca | ||
|
|
86a570e72d | ||
|
|
cbe811fb52 | ||
|
|
ac2508c5ce | ||
|
|
2ad7de4cc9 | ||
|
|
5eb5d198f4 | ||
|
|
7a86b9cee7 | ||
|
|
60f93994f5 | ||
|
|
52e0e38a81 | ||
|
|
471595240b | ||
|
|
061512d330 | ||
|
|
1c59f44ad7 | ||
|
|
269a2b5b36 | ||
|
|
a6879aac6f | ||
|
|
a04930c946 | ||
|
|
b71fea701f | ||
|
|
af54cdddb3 | ||
|
|
1a6f9cc10b | ||
|
|
a717278e95 | ||
|
|
19d5237ebb | ||
|
|
6fbb21f437 | ||
|
|
c7f54321ad | ||
|
|
e6b9933d46 | ||
|
|
c27ee439ef | ||
|
|
68fce1b1da | ||
|
|
2865456761 | ||
|
|
4547031bba | ||
|
|
41e9acf4c2 | ||
|
|
a5f671c06c | ||
|
|
5372fc1fef | ||
|
|
6c5ecbb028 | ||
|
|
bd5a1c3335 | ||
|
|
2c740c9f04 | ||
|
|
3ec89680ed | ||
|
|
42860d38cd | ||
|
|
ef4b3bdb6c | ||
|
|
44bbb16cd3 | ||
|
|
1f5b7e68fc | ||
|
|
4bb8d6fa7b | ||
|
|
6395e73927 | ||
|
|
c956232b96 | ||
|
|
9814cdca55 | ||
|
|
0c337c9384 | ||
|
|
273e3f5aff | ||
|
|
ac1f42b7d5 | ||
|
|
88591fca89 | ||
|
|
75feb55adf | ||
|
|
f4b366389b | ||
|
|
2ec7b7aac9 |
@@ -17,6 +17,7 @@ function classifyCiPaths(paths) {
|
||||
android: forceAll || under(['app/', 'gradle/']) || exact([
|
||||
'build.gradle.kts', 'settings.gradle.kts', 'gradle.properties', 'gradlew', 'gradlew.bat',
|
||||
'scripts/check-android-locales.py', 'scripts/android-locale-harness.py',
|
||||
'scripts/check-android-capabilities.py', 'scripts/tests/check_android_capabilities_test.py',
|
||||
'scripts/check-android-collection-apis.py', 'scripts/check-android-native-compat.py',
|
||||
'scripts/check-android-release-notes.py',
|
||||
'scripts/android_release_artifacts.py',
|
||||
|
||||
@@ -128,3 +128,6 @@ assert.match(releaseTrainWorkflow, /name: Hermes-Relay Coordinated Release Appro
|
||||
assert.match(releaseTrainWorkflow, /Coordinated Android approval is stable-only/);
|
||||
|
||||
console.log('CI path classification tests passed.');
|
||||
|
||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-capabilities.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/check_android_capabilities_test.py']), { ...none, android: true });
|
||||
|
||||
@@ -166,6 +166,9 @@ jobs:
|
||||
- name: Build debug APKs
|
||||
run: ./gradlew assembleDebug --console=plain
|
||||
|
||||
- name: Verify Play capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayDebug
|
||||
|
||||
- name: Verify packaged native compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
@@ -203,6 +206,9 @@ jobs:
|
||||
- name: Build release bundles and APKs
|
||||
run: ./gradlew bundleRelease assembleRelease --console=plain
|
||||
|
||||
- name: Verify Play release capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayRelease
|
||||
|
||||
- name: Scan release DEX for unsupported collection APIs
|
||||
run: |
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
|
||||
@@ -34,6 +34,8 @@ on:
|
||||
- "scripts/check-android-locales.py"
|
||||
- "scripts/android-locale-harness.py"
|
||||
- "scripts/check-android-collection-apis.py"
|
||||
- "scripts/check-android-capabilities.py"
|
||||
- "scripts/tests/check_android_capabilities_test.py"
|
||||
- "scripts/check-android-native-compat.py"
|
||||
- "scripts/check-android-release-notes.py"
|
||||
- "scripts/tests/check_android_native_compat_test.py"
|
||||
@@ -73,6 +75,11 @@ jobs:
|
||||
with:
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
- name: Validate Play capability boundary
|
||||
run: |
|
||||
python3 scripts/check-android-capabilities.py
|
||||
python3 -m unittest scripts.tests.check_android_capabilities_test
|
||||
|
||||
- name: Validate translation catalogs
|
||||
run: python3 scripts/check-android-locales.py
|
||||
|
||||
@@ -117,6 +124,9 @@ jobs:
|
||||
- name: Build debug APK
|
||||
run: ./gradlew assembleDebug --console=plain
|
||||
|
||||
- name: Verify Play capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayDebug
|
||||
|
||||
- name: Verify packaged ONNX Runtime compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
|
||||
@@ -8,6 +8,15 @@ on:
|
||||
- "assets/screenshots/03_voice.png"
|
||||
- "assets/screenshots/06_manage.png"
|
||||
- "docs/media/screenshots.json"
|
||||
- "docs/media/desktop-ui-screenshots.json"
|
||||
- "assets/screenshots/desktop-ui/**"
|
||||
- "desktop/tray/ui/**"
|
||||
- "desktop/tray/scripts/*.mjs"
|
||||
- "desktop/tray/package-lock.json"
|
||||
- "desktop/tray/index.html"
|
||||
- "desktop/tray/icons/icon-256.png"
|
||||
- "desktop/src/endpoint.ts"
|
||||
- "desktop/src/transportSecurity.ts"
|
||||
- ".github/workflows/ci-website.yml"
|
||||
push:
|
||||
branches: [main, dev]
|
||||
@@ -17,6 +26,15 @@ on:
|
||||
- "assets/screenshots/03_voice.png"
|
||||
- "assets/screenshots/06_manage.png"
|
||||
- "docs/media/screenshots.json"
|
||||
- "docs/media/desktop-ui-screenshots.json"
|
||||
- "assets/screenshots/desktop-ui/**"
|
||||
- "desktop/tray/ui/**"
|
||||
- "desktop/tray/scripts/*.mjs"
|
||||
- "desktop/tray/package-lock.json"
|
||||
- "desktop/tray/index.html"
|
||||
- "desktop/tray/icons/icon-256.png"
|
||||
- "desktop/src/endpoint.ts"
|
||||
- "desktop/src/transportSecurity.ts"
|
||||
- ".github/workflows/ci-website.yml"
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -106,6 +106,9 @@ jobs:
|
||||
:app:assembleSideloadRelease \
|
||||
--console=plain
|
||||
|
||||
- name: Verify Play capability manifest
|
||||
run: python3 scripts/check-android-capabilities.py --variant googlePlayRelease
|
||||
|
||||
- name: Scan final release DEX
|
||||
run: |
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
|
||||
@@ -6,15 +6,50 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [Android 1.17.0] - 2026-09-13
|
||||
|
||||
### Added
|
||||
|
||||
- Optional voice controls over other apps in Google Play, with contextual permission setup, a persistent Stop voice notification, and session shutdown on screen lock or permission loss. Phone control remains sideload-only.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Relay tool availability avoids repeated Windows loopback delays and preserves multi-PC capabilities.** Host-local Android, Desktop, and Phone paths use explicit IPv4 loopback, while Desktop checks share a bounded health snapshot that preserves per-client advertisements and fails closed when Hermes-Relay is unavailable. (#562, #563)
|
||||
- Android shows standalone response cards without an outer bubble, uses subtler assistant surfaces, and places delivery status beside message timestamps.
|
||||
- Android answers upstream Clarify batches one question at a time, with independent choices, custom answers, and confirmed progress preserved across reconnects. (#474)
|
||||
- Android context previews mark phone status and turn context as unavailable in Gateway chats instead of claiming they are sent. Settings clarify that automatic phone-status sharing applies to API-only chats. (#556)
|
||||
- Android shows Hermes profile display names and groups the resolved server default under its agent identity, while preserving explicit profile selection and saved conversations.
|
||||
|
||||
## [Plugin 1.11.3] - 2026-09-13
|
||||
|
||||
### Fixed
|
||||
|
||||
- Relay Dashboard WebSockets work with current Hermes authentication helpers while preserving older-host compatibility, single-use tickets, Host/Origin/IP checks, and Relay session authentication.
|
||||
|
||||
## [Android 1.16.1] - 2026-09-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- Android Dashboard-only connections start the profile-scoped session directory before Gateway readiness, so a cold launch no longer leaves both the directory and passive Gateway socket waiting on each other. (#495, #528)
|
||||
|
||||
## [Android 1.16.0] - 2026-09-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- Android no longer crashes when a route probe finishes while a network change invalidates the endpoint cache.
|
||||
- Android opens an authenticated Gateway chat on the first foreground launch instead of waiting for a background-and-resume cycle to leave the waking state. (#495, #528)
|
||||
- Android Dashboard sign-in removes pasted line breaks from username and password fields, matching the browser login while preserving every other credential character. (#541)
|
||||
- Android keeps saved Dashboard sign-ins bound to their connection when switching gateways, rather than letting a stale resolver route invalidate another connection's session.
|
||||
- Bot Mode no longer crashes when different connections have bots with the same profile name. Both the conversation list and Active Now strip preserve each bot's connection, and opening progress appears only on the selected bot.
|
||||
- Android feedback uses themed banners and action cards instead of platform toasts and default snackbars. Dashboard errors no longer misidentify missing resources as an outdated Relay. Developer settings includes local-only message previews.
|
||||
- Missing chat attachments show their error and retry in the attachment card without repeated global popups. Global action messages occupy the top message area instead of covering the composer.
|
||||
- Chat distinguishes session preparation from response streaming and retains initialization errors that arrive before the session acknowledgement. Long-press the agent header to open a live session-diagnostics drawer.
|
||||
- Delegated-agent activity survives parent replies and leaves compact history entries for later read-only review. The activity strip appears only while work runs; historical process views cannot stop or dismiss live work. (#447)
|
||||
|
||||
## [Plugin 1.11.2] - 2026-09-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Relay tool availability avoids repeated Windows loopback delays and preserves multi-PC capabilities.** Host-local Android, Desktop, and Phone paths use explicit IPv4 loopback, while Desktop checks share a bounded health snapshot that preserves per-client advertisements and fails closed when Hermes-Relay is unavailable. (#562, #563)
|
||||
- **`android_*` tools resolve bridge credentials written after host startup.** Requests retry profile-scoped env and active bridge-session credentials after a stale token is rejected, and vision navigation now shares the same current Relay transport instead of the retired standalone default.
|
||||
- **`android_setup` accepts both its canonical and legacy schema keys.** `bridge_session_token` and `pairing_code` are accepted, while a missing token returns a structured error.
|
||||
- **Android tool setup tests use a temporary Hermes home.** Test runs no longer write bridge settings into a developer environment.
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
# Hermes-Relay Plugin v__VERSION__
|
||||
|
||||
**Release Date:** August 31, 2026
|
||||
**Release Date:** September 13, 2026
|
||||
|
||||
## Summary
|
||||
|
||||
This patch restores native installation compatibility on affected Hermes versions and makes Relay prompt context advertise only capabilities the selected session can actually call. Standard Chat, Manage, standard voice, and ordinary inbound files remain upstream-owned.
|
||||
Dashboard WebSocket connections work again with current Hermes authentication helpers, while older Hermes hosts remain supported.
|
||||
|
||||
## Fixed
|
||||
|
||||
- **Native installer compatibility.** The plugin keeps its complete current manifest while avoiding the installer/runtime schema mismatch that caused `manifest_version 2` installs to fail after an apparent Hermes update.
|
||||
- **Capability-gated phone context.** Phone-control and cross-platform delivery guidance now follows the selected session/profile tool catalog instead of implying unavailable `android_*` or `send_message` callables.
|
||||
- Resolve WebSocket guards from their current upstream module and retain the older-host fallback. Single-use tickets, Host/Origin/IP checks, and independent Hermes-Relay session authentication remain enforced. Missing or incomplete helper contracts deny admission.
|
||||
|
||||
## Install / update
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.15.1
|
||||
# Hermes-Relay Android v1.17.0
|
||||
|
||||
**Release Date:** September 2, 2026
|
||||
**Release Date:** September 13, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.15.1-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.17.0-sideload-release.apk` and tap it for the full feature set, or install from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,29 +12,28 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This patch improves chat, media, and voice reliability. It reduces memory-heavy work, keeps attachment previews stable through rotation, and makes follow-up message behavior and voice errors easier to understand.
|
||||
Google Play gains optional voice controls over other apps. This release also makes Clarify batches, profile identity, and chat context easier to follow while preserving confirmed answers and saved conversations.
|
||||
|
||||
## Added
|
||||
|
||||
- Start Voice Overlay from Voice Focus after granting microphone, notification, and display-over-other-apps access. Permission grants require a separate Start action. Stop voice from the overlay or persistent notification; screen lock, task removal, and permission loss end the session.
|
||||
|
||||
## Changed
|
||||
|
||||
- Choose Correct now or Queue next from a slim tray behind the composer. Chat settings sets the default; the tray overrides one message. Stop pauses the queue, Resume continues it, and editing or removing an item preserves its successors.
|
||||
- Chat and Voice use readable centered layouts on wider screens, including landscape Voice Focus.
|
||||
- Standalone response cards use one surface, assistant bubbles are subtler, and timestamps share a row with delivery status.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Correction and delivery labels remain visible inside user-message bubbles.
|
||||
- Voice errors open in a scrollable dialog with separate Retry and Dismiss actions.
|
||||
- Attachment previews remain open through rotation, and video previews preserve their proportions.
|
||||
- Release optimization preserves the native speech configuration required for wake-word startup.
|
||||
- Standard Hermes attachments download directly to disk with bounded size checks.
|
||||
- Session refresh avoids repeated request loops; history loads, Markdown, image previews, and media exports keep memory use bounded.
|
||||
- Image-generation progress stays visible through gaps between interim replies and returned media.
|
||||
- The first prompt waits for Gateway session readiness. Ownership refusals retain the prompt for retry and show the original server error.
|
||||
- Answer upstream Clarify batches one question at a time, with independent choices, custom answers, and confirmed progress across reconnects. (#474)
|
||||
- Context previews show that Gateway chats cannot send phone status or general turn context. Automatic phone-status sharing remains supported for API-only chats. (#556)
|
||||
- Profiles display their Hermes names and group the resolved server default under its agent identity, preserving explicit selection and saved conversations.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.15.1** (versionCode **54**).
|
||||
- App version: **1.17.0** (versionCode **57**).
|
||||
- Standard Chat, sessions, profiles, Manage, voice, and ordinary media use current upstream Hermes. Speech-to-text still requires a configured provider on the host.
|
||||
- Hermes-Relay Plugin **1.11.1** remains the current optional plugin release; this Android patch does not require a new plugin version.
|
||||
- Paused text queues can be restored. Attachment bytes are not persisted in preferences; unrestorable attachment queues must be reviewed and sent again.
|
||||
- Hermes-Relay Plugin **1.11.3** is the optional release for Hermes-Relay tools and current Dashboard WebSocket compatibility.
|
||||
- Explicit Direct API/API-only connections remain supported and are not used as silent failover for Dashboard-owned chats.
|
||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only.
|
||||
- Voice Overlay is available in Google Play and sideload builds. Device Control remains sideload-only.
|
||||
- Gateway phone-status delivery and automatic Android identification remain unavailable pending upstream support.
|
||||
- Physical Android 14-16 and OEM voice-overlay testing was not performed for this release. Code, rendered UI, existing emulator evidence, CI, and signed-package preflight provide the recorded verification.
|
||||
|
||||
@@ -100,9 +100,9 @@ android {
|
||||
}
|
||||
|
||||
// ─── Bridge release tracks ─────────────────────────────────────────────────
|
||||
// Google Play ships Bridge Core only: pairing, chat, voice, terminal/TUI,
|
||||
// Google Play ships Bridge Core and user-started voice-only overlay: pairing, chat, voice, terminal/TUI,
|
||||
// media, notification companion, relay sessions, and status. It does not
|
||||
// declare AccessibilityService, overlay, MediaProjection, wake-lock device
|
||||
// declare AccessibilityService, MediaProjection, wake-lock device
|
||||
// control, SMS/call/contact/location, or unattended-control permissions.
|
||||
//
|
||||
// googlePlay — canonical Play Store install. Bridge Core only.
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.ApiEndpoint
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Protocol
|
||||
import okhttp3.Response
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.InterruptedIOException
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EndpointResolverConcurrencyInstrumentedTest {
|
||||
|
||||
@Test
|
||||
fun probeCompletionRacingInvalidation_staysCrashFreeOnAndroidCollections() = runBlocking {
|
||||
repeat(25) { iteration ->
|
||||
val candidateCount = 8
|
||||
val requestsStarted = CountDownLatch(candidateCount)
|
||||
val releaseRequests = CountDownLatch(1)
|
||||
val raceGate = CountDownLatch(1)
|
||||
val requestSequence = AtomicInteger(0)
|
||||
val client = OkHttpClient.Builder()
|
||||
.addInterceptor { chain ->
|
||||
if (requestSequence.incrementAndGet() <= candidateCount) {
|
||||
requestsStarted.countDown()
|
||||
releaseRequests.await(5, TimeUnit.SECONDS)
|
||||
throw InterruptedIOException("instrumented invalidation race")
|
||||
}
|
||||
Response.Builder()
|
||||
.request(chain.request())
|
||||
.protocol(Protocol.HTTP_1_1)
|
||||
.code(200)
|
||||
.message("OK")
|
||||
.body("{}".toResponseBody())
|
||||
.build()
|
||||
}
|
||||
.build()
|
||||
val resolver = EndpointResolver(client)
|
||||
val candidates = (1..candidateCount).map { index ->
|
||||
EndpointCandidate(
|
||||
role = "instrumented-$iteration-$index",
|
||||
priority = 0,
|
||||
api = ApiEndpoint(host = "127.0.0.1", port = 1, tls = false),
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
val staleResolve = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
resolver.resolve(candidates, EndpointSurface.Api)
|
||||
}
|
||||
assertTrue(requestsStarted.await(5, TimeUnit.SECONDS))
|
||||
|
||||
val invalidation = async(Dispatchers.Default) {
|
||||
raceGate.await(5, TimeUnit.SECONDS)
|
||||
resolver.clearCache()
|
||||
}
|
||||
val completions = async(Dispatchers.Default) {
|
||||
raceGate.await(5, TimeUnit.SECONDS)
|
||||
releaseRequests.countDown()
|
||||
}
|
||||
raceGate.countDown()
|
||||
|
||||
withTimeout(2_000L) {
|
||||
invalidation.await()
|
||||
completions.await()
|
||||
staleResolve.await()
|
||||
}
|
||||
assertTrue(resolver.cacheSnapshot().isEmpty())
|
||||
|
||||
resolver.clearCache()
|
||||
val freshWinner = withTimeout(2_000L) {
|
||||
resolver.resolve(listOf(candidates.first()), EndpointSurface.Api)
|
||||
}
|
||||
assertEquals(candidates.first(), freshWinner)
|
||||
assertTrue(
|
||||
resolver.probeOutcomes.value.getValue(
|
||||
EndpointResolver.cacheKey(candidates.first(), EndpointSurface.Api),
|
||||
).reachable,
|
||||
)
|
||||
} finally {
|
||||
raceGate.countDown()
|
||||
releaseRequests.countDown()
|
||||
client.dispatcher.executorService.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performImeAction
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||
import com.hermesandroid.relay.ui.components.MessageBubble
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.WebSocket
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
/** Production socket, ViewModel, transcript, Compose and IME actions on a virtual device. */
|
||||
class ClarifyBatchInstrumentedTest {
|
||||
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
|
||||
private lateinit var fixture: AndroidGatewayContractFixture
|
||||
private lateinit var scope: CoroutineScope
|
||||
private lateinit var gateway: GatewayChatClient
|
||||
private lateinit var viewModel: ChatViewModel
|
||||
private lateinit var handler: ChatHandler
|
||||
private lateinit var socket: WebSocket
|
||||
|
||||
@Before fun setUp() {
|
||||
fixture = AndroidGatewayContractFixture()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val http = OkHttpClient()
|
||||
gateway = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(fixture.server.url("/").toString().trimEnd('/'), http),
|
||||
okHttpClient = http, scope = scope,
|
||||
callbackDispatcher = { Handler(Looper.getMainLooper()).post(it) },
|
||||
)
|
||||
handler = ChatHandler().also { it.setSessionId("20260821_120000_fixture") }
|
||||
viewModel = ChatViewModel().also {
|
||||
it.initialize(HermesApiClient(fixture.server.url("/").toString(), "fixture-key"), handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoader { Result.success(emptyList()) }
|
||||
it.updateGatewayClient(gateway)
|
||||
}
|
||||
compose.setContent {
|
||||
val messages by handler.messages.collectAsStateWithLifecycle()
|
||||
MaterialTheme {
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(messages.size, key = { messages[it].id }) { index ->
|
||||
MessageBubble(messages[index], showTimestamps = false,
|
||||
onCardInput = viewModel::answerAsk, animationEnabled = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait("20260821_120000_fixture") })
|
||||
socket = fixture.awaitServerSocket()
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
gateway.shutdown()
|
||||
scope.cancel()
|
||||
fixture.shutdown()
|
||||
}
|
||||
|
||||
@Test fun confirmedProgressSurvivesLifecycleAndCustomAnswerUsesIme() {
|
||||
compose.runOnIdle { viewModel.sendMessage("Ask two questions") }
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
socket.send(fixture.event("clarify.request", Json.parseToJsonElement("""
|
||||
{"request_id":"batch-device","questions":[
|
||||
{"qid":"route/a","question":"Which route?","choices":["Canary","Immediate"]},
|
||||
{"qid":"notes:b","question":"Anything else?","choices":null}
|
||||
]}
|
||||
""") as JsonObject, "fixture-live-1"))
|
||||
compose.waitUntil(10_000) { viewModel.pendingAsk.value != null }
|
||||
compose.onNodeWithText("Canary").performClick()
|
||||
compose.waitUntil(10_000) { viewModel.pendingAsk.value?.ask?.answers?.get("route/a") == "Canary" }
|
||||
assertEquals(JsonPrimitive("route/a"), fixture.awaitRpc("clarify.respond")["question_id"])
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
compose.onNodeWithText("Question 2 of 2").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("Type an answer…").apply {
|
||||
performClick()
|
||||
performTextInput(" Keep rollback ready ")
|
||||
performImeAction()
|
||||
}
|
||||
compose.waitUntil(10_000) { viewModel.pendingAsk.value == null }
|
||||
compose.onNodeWithText("All questions answered").assertIsDisplayed()
|
||||
assertEquals(2, fixture.rpcCount("clarify.respond"))
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,12 @@ import android.os.Looper
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertTextEquals
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
@@ -17,25 +18,30 @@ import androidx.compose.ui.test.onAllNodesWithTag
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.ChatTurnAssistantCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
|
||||
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayConnectionState
|
||||
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessStrip
|
||||
import com.hermesandroid.relay.ui.components.SubagentPreviewVisibility
|
||||
import com.hermesandroid.relay.ui.screens.shouldOwnVisibleGateway
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
@@ -85,6 +91,8 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
@Volatile
|
||||
private var persistedHistory: List<MessageItem> = emptyList()
|
||||
private val historySignInRequired = MutableStateFlow(false)
|
||||
private val coldStartAdmissionEnabled = MutableStateFlow(false)
|
||||
private val coldStartGatewayAvailability = MutableStateFlow(GatewayAvailability.Unknown)
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
@@ -119,6 +127,19 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
||||
val children by viewModel.subagentActivities.collectAsStateWithLifecycle()
|
||||
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
|
||||
val admissionEnabled by coldStartAdmissionEnabled.collectAsStateWithLifecycle()
|
||||
val admissionAvailability by coldStartGatewayAvailability.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(admissionEnabled, admissionAvailability) {
|
||||
if (admissionEnabled) {
|
||||
viewModel.setChatVisible(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = true,
|
||||
isGatewayTransport = true,
|
||||
gatewayAvailability = admissionAvailability,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
MaterialTheme {
|
||||
Column(Modifier.testTag("contract-transcript")) {
|
||||
GatewayBackgroundProcessStrip(
|
||||
@@ -156,6 +177,122 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
fixture.awaitRpc("session.resume")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun authenticatedUnknownColdLaunch_opensObservationSocketWithoutLifecycleBounce() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"prompt.submit",
|
||||
"session.interrupt",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val ticketMintsBefore = fixture.requestsTo("/api/auth/ws-ticket")
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = okHttp,
|
||||
),
|
||||
okHttpClient = okHttp,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
coldStartGatewayAvailability.value = GatewayAvailability.Unknown
|
||||
coldStartAdmissionEnabled.value = true
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
gatewayClient.connectionState.value == GatewayConnectionState.Ready
|
||||
}
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
assertEquals(ticketMintsBefore + 1, fixture.requestsTo("/api/auth/ws-ticket"))
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"cold observation sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardOnlyColdLaunch_waitsForExactDirectoryThenOpensObservationSocket() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val directoryStarted = CompletableDeferred<Unit>()
|
||||
val directoryResult = CompletableDeferred<Result<List<SessionItem>>>()
|
||||
viewModel.setProfileSessionLister { profile ->
|
||||
assertEquals(PROFILE_NAME, profile)
|
||||
directoryStarted.complete(Unit)
|
||||
directoryResult.await()
|
||||
}
|
||||
handler.setSessionId(null)
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("fixture-connection", PROFILE_NAME),
|
||||
STORED_SESSION_ID,
|
||||
)
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"prompt.submit",
|
||||
"session.interrupt",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val ticketMintsBefore = fixture.requestsTo("/api/auth/ws-ticket")
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = okHttp,
|
||||
),
|
||||
okHttpClient = okHttp,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
viewModel.setChatVisible(true)
|
||||
|
||||
// This is the production binder's Dashboard/profile hydration edge.
|
||||
// The socket must stay passive and closed until the exact-owner REST
|
||||
// directory publishes, then open without a lifecycle bounce.
|
||||
viewModel.refreshSessions()
|
||||
compose.waitUntil(5_000) { directoryStarted.isCompleted }
|
||||
assertEquals(ticketMintsBefore, fixture.requestsTo("/api/auth/ws-ticket"))
|
||||
|
||||
directoryResult.complete(
|
||||
Result.success(listOf(SessionItem(id = STORED_SESSION_ID, title = "Fixture session"))),
|
||||
)
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
gatewayClient.connectionState.value == GatewayConnectionState.Ready
|
||||
}
|
||||
serverSocket = fixture.awaitServerSocket()
|
||||
assertEquals(ticketMintsBefore + 1, fixture.requestsTo("/api/auth/ws-ticket"))
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"directory-gated cold observation sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
Google Play ships Hermes Bridge Core only. It intentionally does not merge
|
||||
any Device Control services or permissions.
|
||||
|
||||
This file is intentionally kept as an empty overlay so future flavor-specific
|
||||
This overlay owns the voice-only special access so future flavor-specific
|
||||
permissions / activities have an obvious home. Mirror structural additions
|
||||
in `app/src/sideload/AndroidManifest.xml` unless the change is intentionally
|
||||
track-specific.
|
||||
@@ -22,6 +22,9 @@
|
||||
android:name="android.permission.WAKE_LOCK"
|
||||
tools:node="remove" />
|
||||
|
||||
<!-- User-started voice controls only; does not enable Device Control. -->
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
|
||||
<application />
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -23,7 +23,7 @@ GOOGLE PLAY AND SIDELOAD
|
||||
|
||||
The Google Play build includes Chat, voice, sessions, Manage, profiles, notifications, media, and Terminal/TUI when the Hermes-Relay plugin is paired.
|
||||
|
||||
Google Play does not include Android Device Control. It cannot read the phone screen, tap, type, swipe, take device screenshots, send SMS, place calls, or access contacts or location.
|
||||
Google Play does not include Android Device Control. It cannot tap, type, swipe, send SMS, place calls, or access contacts or location. Optional Voice Overlay provides user-started voice controls over other apps, with microphone notification and Stop voice. Selecting Hermes as Android Digital Assistant can provide bounded screen text and a screenshot for an explicit unlocked assistant invocation; this context goes to your configured server and AI provider.
|
||||
|
||||
Device Control is available only in the signed Sideload build on this project's GitHub Releases. It requires the Sideload app, a paired Hermes-Relay plugin, explicit Android accessibility permission, and the app's safety controls.
|
||||
|
||||
@@ -32,9 +32,6 @@ FEATURES
|
||||
- Streaming Chat with reasoning, markdown, tool progress, attachments, mid-turn steering, edit-and-resend, and searchable commands.
|
||||
- Manage models and provider keys, edit profiles, and browse, install, or update skills through the Hermes Dashboard.
|
||||
- Hands-free voice through your server's speech providers. Hermes-Relay pairing adds per-profile voices and an experimental realtime engine.
|
||||
- Create, switch, search, rename, pin, archive, and continue sessions.
|
||||
- Connect multiple Hermes servers and switch in one tap; add LAN, Tailscale, or public routes.
|
||||
- Pair the Hermes-Relay plugin for Terminal/TUI, notifications, media, enhanced voice, Relay sessions, and per-feature grants.
|
||||
- Inspect connection readiness, routes, response timing, token usage, and stream health without exposing credentials.
|
||||
|
||||
SECURITY AND PRIVACY
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
v1.17.0 - Voice over other apps and clearer conversations
|
||||
|
||||
More reliable chats and media: fewer memory-heavy refreshes, smoother large histories, and attachment previews that survive rotation. Choose whether follow-ups correct the current response or wait in a queue. Voice errors are easier to read, image-generation progress stays visible, and wake-word startup and first-message readiness are fixed.
|
||||
Use optional voice controls over other apps, with clear permission setup and an immediate Stop action. Answer Clarify batches one question at a time, with progress preserved across reconnects. Enjoy cleaner chat cards, recognizable profile names, and context previews that show what your connection supports. Phone control remains sideload-only.
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
新增监督模式:家长可配置并固定到指定配置文件,设置受设备身份验证保护。家长可限制附件、标准语音、生成媒体、历史记录、操作和技术详情。实时活动不可用时会话行保持中性显示,从家长设置返回时监督聊天也不再空白。
|
||||
v1.17.0 - 跨应用语音与更清晰的对话
|
||||
|
||||
可选的语音悬浮控件让你在使用其他应用时继续语音会话,提供清晰的权限说明和随时停止操作。逐题回答 Clarify 批量问题,重连后保留已确认的进度。聊天卡片更简洁,配置文件显示名称更易辨认,上下文预览准确说明当前连接支持发送哪些信息。设备控制仍仅限侧载版本。
|
||||
|
||||
@@ -1,6 +1,119 @@
|
||||
{
|
||||
"schema": 3,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.17.0",
|
||||
"title": "Voice over other apps and clearer conversations",
|
||||
"date": "2026-09-13",
|
||||
"summary": "Google Play gains optional voice controls over other apps. Clarify questions, profile names, and chat context are easier to follow without losing confirmed answers or saved conversations.",
|
||||
"changes": [
|
||||
{"id": "play-voice-overlay", "kind": "added", "title": "Keep voice controls over other apps", "summary": "Start Voice Overlay from Voice Focus after granting microphone, notification, and display-over-other-apps access. Stop voice from its controls or persistent notification; screen lock and permission loss end the session.", "highlight": true},
|
||||
{"id": "clarify-batches", "kind": "fixed", "title": "Answer Clarify questions one at a time", "summary": "Multi-question requests support separate choices and custom answers. Confirmed progress survives reconnects, and failed sends keep the current answer available.", "highlight": true},
|
||||
{"id": "chat-card-surfaces", "kind": "improved", "title": "Read cleaner chat cards", "summary": "Standalone response cards lose the extra outer bubble, assistant messages use quieter surfaces, and delivery status sits beside the timestamp."},
|
||||
{"id": "transport-context-preview", "kind": "fixed", "title": "See which context your chat can send", "summary": "Gateway previews mark phone status and turn context as unavailable. Automatic phone-status sharing is labeled for API-only chats, where it remains supported."},
|
||||
{"id": "profile-display-names", "kind": "fixed", "title": "Recognize profiles by their display names", "summary": "Profiles use their Hermes display names, and the resolved server default appears under its agent identity. Explicit profile choices and saved conversations are preserved.", "highlight": true}
|
||||
],
|
||||
"compatibility": [
|
||||
"Voice Overlay is now available in Google Play and sideload builds. Device Control remains sideload-only.",
|
||||
"Standard Chat and voice use upstream Hermes without requiring Hermes-Relay Plugin. Gateway phone-status delivery and automatic Android identification remain unavailable."
|
||||
],
|
||||
"playNotes": "Use optional voice controls over other apps, with clear permission setup and an immediate Stop action. Answer Clarify batches one question at a time, with progress preserved across reconnects. Enjoy cleaner chat cards, recognizable profile names, and context previews that show what your connection supports. Phone control remains sideload-only.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.16.1",
|
||||
"title": "Dashboard-only cold starts recover",
|
||||
"date": "2026-09-12",
|
||||
"summary": "Dashboard-only connections can now prepare the selected profile and open Gateway chat without waiting for a background, resume, or network-route change.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "gateway-directory-bootstrap",
|
||||
"kind": "fixed",
|
||||
"title": "Open Gateway chat from a Dashboard-only cold start",
|
||||
"summary": "The selected profile's session directory starts before Gateway readiness, so it cannot wait on the same passive socket that depends on its result.",
|
||||
"highlight": true
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Dashboard and Gateway chat continue to use current upstream Hermes without requiring the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.2 remains the matching optional release for Relay tools."
|
||||
],
|
||||
"playNotes": "Dashboard-only connections now prepare the selected profile before Gateway readiness, fixing a remaining cold-start path that could stay on waking or waiting for Gateway until the app resumed or its network route changed.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.16.0",
|
||||
"title": "Safer startup, connections, and activity",
|
||||
"date": "2026-09-10",
|
||||
"summary": "Gateway chat opens reliably from a cold launch, saved sign-ins stay with the correct connection, and network changes no longer race the route cache. Bot Mode and delegated-work feedback also remain stable across multiple gateways and later review.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "gateway-cold-start",
|
||||
"kind": "fixed",
|
||||
"title": "Open Gateway chat on the first launch",
|
||||
"summary": "An authenticated Gateway wakes and opens from a cold foreground start instead of waiting for the app to background and resume.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "connection-owned-signin",
|
||||
"kind": "fixed",
|
||||
"title": "Keep saved sign-ins with their connection",
|
||||
"summary": "Switching gateways cannot reuse an outgoing resolver route to invalidate another connection's saved Dashboard session.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "network-change-invalidation",
|
||||
"kind": "fixed",
|
||||
"title": "Recover safely when the network changes",
|
||||
"summary": "Route-probe completion and endpoint-cache invalidation are serialized so Wi-Fi, mobile-data, VPN, or Tailscale changes do not trigger the reported crash.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "bot-mode-connection-identity",
|
||||
"kind": "fixed",
|
||||
"title": "Open same-named bots from multiple gateways",
|
||||
"summary": "Bot Mode and Active Now keep connection and profile identity together, avoiding duplicate list keys and opening progress on the selected bot."
|
||||
},
|
||||
{
|
||||
"id": "delegated-activity-receipts",
|
||||
"kind": "improved",
|
||||
"title": "Review delegated work after it finishes",
|
||||
"summary": "Compact, bounded activity receipts survive parent replies and remain available read-only, while the live strip appears only during active work.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "chat-feedback-surfaces",
|
||||
"kind": "improved",
|
||||
"title": "Keep feedback with the surface that owns it",
|
||||
"summary": "Themed banners and action cards replace platform popups, global actions stay clear of the composer, and local Developer previews make feedback states inspectable."
|
||||
},
|
||||
{
|
||||
"id": "attachment-error-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Retry missing attachments in place",
|
||||
"summary": "A missing attachment keeps its error and Retry action in the attachment card without producing repeated global messages."
|
||||
},
|
||||
{
|
||||
"id": "session-preparation-diagnostics",
|
||||
"kind": "improved",
|
||||
"title": "See session preparation and initialization failures",
|
||||
"summary": "Chat distinguishes session preparation from response streaming, retains early initialization errors, and opens session diagnostics from the agent header."
|
||||
},
|
||||
{
|
||||
"id": "pasted-dashboard-credentials",
|
||||
"kind": "fixed",
|
||||
"title": "Paste Dashboard credentials without hidden line breaks",
|
||||
"summary": "Username and password fields remove pasted carriage returns and line feeds while preserving every other credential character."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Chat, sessions, profiles, Manage, voice, Bot Mode, and delegated activity continue to use current upstream Hermes without requiring the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.2 is the matching optional release for Relay tools. Existing erased or revoked Dashboard credentials still require a legitimate sign-in.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain sideload-only."
|
||||
],
|
||||
"playNotes": "Gateway chat now opens reliably on a cold launch. Saved Dashboard sign-ins stay bound to the correct connection, pasted credentials ignore accidental line breaks, and network changes no longer race the route cache. Bot Mode supports duplicate profile names across gateways, while delegated work, session setup, attachment errors, and feedback remain visible and easier to review.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.15.1",
|
||||
"title": "Steadier chat, media, and voice",
|
||||
|
||||
@@ -1,24 +1,19 @@
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
v1.17.0 - Voice over other apps and clearer conversations
|
||||
|
||||
Summary
|
||||
* Chats use less memory, attachment previews stay in place, and voice failures are easier to recover from. Follow-up controls make it clear whether a message changes the current response or waits for the next turn.
|
||||
* Google Play gains optional voice controls over other apps. Clarify questions, profile names, and chat context are easier to follow without losing confirmed answers or saved conversations.
|
||||
|
||||
Highlights
|
||||
* Choose when follow-up messages are sent — A slim tray behind the composer offers Correct now or Queue next. Chat settings sets the default, and a composer choice applies to one message. Stop pauses pending work until Resume; editing or removing an item keeps the remaining queue usable.
|
||||
* Keep attachment previews open through rotation — Image, video, audio, PDF, text, and file previews stay open as the screen rotates. Videos retain their original proportions.
|
||||
* Keep large chats and media manageable — Automatic session refresh no longer loops. Routine history loads, chat rendering, image previews, and media exports use bounded memory instead of allocating entire large responses.
|
||||
* Keep voice controls over other apps — Start Voice Overlay from Voice Focus after granting microphone, notification, and display-over-other-apps access. Stop voice from its controls or persistent notification; screen lock and permission loss end the session.
|
||||
* Answer Clarify questions one at a time — Multi-question requests support separate choices and custom answers. Confirmed progress survives reconnects, and failed sends keep the current answer available.
|
||||
* Recognize profiles by their display names — Profiles use their Hermes display names, and the resolved server default appears under its agent identity. Explicit profile choices and saved conversations are preserved.
|
||||
|
||||
Improved
|
||||
* Make better use of wider screens — Chat and Voice keep text and controls on readable centered layouts. Landscape Voice Focus separates identity controls from conversation activity.
|
||||
* Read cleaner chat cards — Standalone response cards lose the extra outer bubble, assistant messages use quieter surfaces, and delivery status sits beside the timestamp.
|
||||
|
||||
Fixed
|
||||
* Read message delivery status clearly — Correction and delivery labels use contrasting text instead of disappearing into the message bubble.
|
||||
* Read and dismiss voice errors — Voice errors open in a contained dialog with scrollable details and separate Retry and Dismiss actions, without overlapping chat controls.
|
||||
* Fix wake-word startup in release builds — Release optimization now preserves the native speech configuration names needed to initialize wake-word detection.
|
||||
* Download attachments with less memory — Standard Hermes attachments stream into the on-disk cache while download size limits remain enforced.
|
||||
* Keep image-generation progress visible — The working indicator stays visible between interim replies and the generated image, including gateways that omit tool activity events.
|
||||
* Wait for new chats to be ready — The first message waits for the Gateway session to initialize. Ownership refusals keep the prompt retryable and show the server's error.
|
||||
* See which context your chat can send — Gateway previews mark phone status and turn context as unavailable. Automatic phone-status sharing is labeled for API-only chats, where it remains supported.
|
||||
|
||||
Compatibility
|
||||
* Standard Chat, sessions, media, and voice continue to use upstream Hermes. Voice transcription still requires a configured speech-to-text provider on the Hermes host.
|
||||
* Paused text queues can be restored. Attachment bytes are not stored in preferences; an attachment queue that cannot be restored must be reviewed and sent again.
|
||||
* Voice Overlay is now available in Google Play and sideload builds. Device Control remains sideload-only.
|
||||
* Standard Chat and voice use upstream Hermes without requiring Hermes-Relay Plugin. Gateway phone-status delivery and automatic Android identification remain unavailable.
|
||||
|
||||
@@ -34,9 +34,7 @@ object AgentDisplay {
|
||||
profiles: List<Profile>,
|
||||
): Profile? = selectedProfile
|
||||
|
||||
// Display can use the root default profile's metadata without making it a
|
||||
// request/session override. Verbose SOUL summaries are filtered by
|
||||
// profileDisplayName below, so this is safe for headers/cards.
|
||||
// Display resolution never changes selection or persistence identity.
|
||||
fun effectiveDisplayProfile(
|
||||
selectedProfile: Profile?,
|
||||
profiles: List<Profile>,
|
||||
@@ -44,36 +42,22 @@ object AgentDisplay {
|
||||
): Profile? {
|
||||
selectedProfile?.let { return it }
|
||||
val resolvedServerDefault = profileRequestName(serverDefaultProfileName)
|
||||
return resolvedServerDefault
|
||||
?.let { activeName ->
|
||||
profiles.firstOrNull { it.name.equals(activeName, ignoreCase = true) }
|
||||
}
|
||||
?: profiles.firstOrNull { it.name.equals("default", ignoreCase = true) }
|
||||
// An absent roster row is not authority to substitute the root profile.
|
||||
// Retain the confirmed name while its display metadata is loading.
|
||||
return resolvedServerDefault?.let { activeName ->
|
||||
profiles.firstOrNull { it.name == activeName }
|
||||
?: Profile(name = activeName, model = "")
|
||||
}
|
||||
}
|
||||
|
||||
// The NAME goes in the name slot. Non-default profiles use their profile
|
||||
// name first. The synthetic default profile uses its description only when
|
||||
// that description looks like a concise human agent name ("Victor"), not a
|
||||
// verbose SOUL summary.
|
||||
// Match upstream Desktop: presentation-only display_name, then exact request name.
|
||||
fun profileDisplayName(profile: Profile?): String? {
|
||||
if (profile == null) return null
|
||||
if (profile.name.equals("default", ignoreCase = true)) {
|
||||
return defaultProfileDisplayName(profile)
|
||||
}
|
||||
return when {
|
||||
profile.name.isNotBlank() -> titleCase(profile.name.trim())
|
||||
profile.description.isNotBlank() -> profile.description.trim()
|
||||
else -> null
|
||||
}
|
||||
return profile.displayName.trim().takeIf(String::isNotEmpty)
|
||||
?: profile.name.trim().takeIf(String::isNotEmpty)
|
||||
}
|
||||
|
||||
fun defaultProfileDisplayName(profile: Profile?): String? =
|
||||
profile
|
||||
?.description
|
||||
?.trim()
|
||||
?.takeIf { it.looksLikeConciseAgentName() }
|
||||
?.let(::titleCase)
|
||||
|
||||
@Suppress("UNUSED_PARAMETER") // connectionLabel retained for source compatibility.
|
||||
fun agentName(
|
||||
profile: Profile?,
|
||||
selectedPersonality: String,
|
||||
@@ -86,7 +70,7 @@ object AgentDisplay {
|
||||
|
||||
// "none"/"neutral" are the upstream "cleared overlay" aliases — treat
|
||||
// them like "default" for identity: fall through to the server default
|
||||
// (or the base connection identity) rather than rendering the literal
|
||||
// identity rather than rendering the literal
|
||||
// word as an agent name.
|
||||
val personalityName = if (
|
||||
isClearedPersonality(selectedPersonality) &&
|
||||
@@ -102,7 +86,6 @@ object AgentDisplay {
|
||||
return when {
|
||||
personalityName.isNotBlank() && personalityName != "default" ->
|
||||
titleCase(personalityName.trim())
|
||||
!connectionLabel.isNullOrBlank() -> connectionLabel.trim()
|
||||
else -> "Hermes"
|
||||
}
|
||||
}
|
||||
@@ -199,16 +182,6 @@ object AgentDisplay {
|
||||
?.replace(Regex("\\s+"), " ")
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
|
||||
private fun String.looksLikeConciseAgentName(): Boolean {
|
||||
if (isBlank() || length > 40 || contains('\n') || contains('\r')) {
|
||||
return false
|
||||
}
|
||||
if (any { it == '.' || it == ':' || it == ';' }) {
|
||||
return false
|
||||
}
|
||||
return trim().split(Regex("\\s+")).size <= 4
|
||||
}
|
||||
|
||||
private fun titleCase(value: String): String =
|
||||
value.replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.hermesandroid.relay.network.upstream.GatewayClarifyQuestion
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
@@ -135,6 +136,9 @@ data class ChatTurnAskCheckpoint(
|
||||
val text: String,
|
||||
val choices: List<String>? = null,
|
||||
val multiSelect: Boolean = false,
|
||||
val questions: List<GatewayClarifyQuestion> = emptyList(),
|
||||
val answers: Map<String, String> = emptyMap(),
|
||||
val ownerId: String? = null,
|
||||
val smartDenied: Boolean = false,
|
||||
val envVar: String? = null,
|
||||
val timeoutSeconds: Int,
|
||||
|
||||
@@ -96,7 +96,8 @@ object FeatureFlags {
|
||||
* flavor ships AccessibilityService-backed Device Control. The `googlePlay`
|
||||
* flavor is Bridge Core: relay pairing, chat, voice, terminal, notification
|
||||
* companion, media, and session-grant surfaces without screen reading, taps,
|
||||
* typing, screenshots, overlays, or unattended control.
|
||||
* typing, MediaProjection screenshots, or unattended control. Voice-only overlay
|
||||
* presentation is a separate capability shared by both flavors.
|
||||
*
|
||||
* Device Control tier definitions (see `Phase 3 — Bridge Channel.md`):
|
||||
* 1. baseline — sideload only (app open, tap, navigate within app)
|
||||
@@ -126,6 +127,9 @@ object BuildFlavor {
|
||||
*/
|
||||
val isSideload: Boolean get() = current == SIDELOAD
|
||||
|
||||
/** Voice presentation does not grant Device Control. Unknown distributions fail closed. */
|
||||
val voiceSystemOverlay: Boolean get() = current == GOOGLE_PLAY || current == SIDELOAD
|
||||
|
||||
val bridgeTier1: Boolean get() = current == SIDELOAD // baseline device control
|
||||
val bridgeTier2: Boolean get() = current == SIDELOAD // screen context
|
||||
val bridgeTier3: Boolean get() = current == SIDELOAD // voice-first
|
||||
|
||||
@@ -71,6 +71,8 @@ data class HermesCard(
|
||||
* actions.
|
||||
*/
|
||||
val input: HermesCardInput? = null,
|
||||
/** Local Gateway batch; never an ordinary chat-message answer protocol. */
|
||||
val clarifyBatch: HermesCardClarifyBatch? = null,
|
||||
) {
|
||||
object BuiltInTypes {
|
||||
const val SKILL_RESULT = "skill_result"
|
||||
@@ -96,6 +98,25 @@ data class HermesCard(
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class HermesCardClarifyBatch(
|
||||
val questions: List<HermesCardClarifyQuestion>,
|
||||
val expiresAtMillis: Long? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class HermesCardClarifyQuestion(
|
||||
val key: String,
|
||||
val question: String,
|
||||
val input: HermesCardInput,
|
||||
val answer: String? = null,
|
||||
val submitting: Boolean = false,
|
||||
)
|
||||
|
||||
/** Local callback identity. The RPC always uses the original qid, never this UI key. */
|
||||
fun clarifyQuestionCardKey(cardKey: String, qid: String): String =
|
||||
Json.encodeToString(listOf(cardKey, qid))
|
||||
|
||||
/**
|
||||
* Interactive input slot on a [HermesCard]. The flags compose rather than
|
||||
* branch — a sudo ask can be `masked + holdToConfirm` (password field whose
|
||||
|
||||
@@ -111,6 +111,8 @@ data class Profile(
|
||||
val hasAvatar: Boolean = false,
|
||||
@SerialName("ui_meta")
|
||||
val uiMeta: JsonObject = JsonObject(emptyMap()),
|
||||
@SerialName("display_name")
|
||||
val displayName: String = "",
|
||||
) {
|
||||
val hasIsolatedApi: Boolean
|
||||
get() = !apiServerUrl.isNullOrBlank()
|
||||
|
||||
@@ -149,7 +149,10 @@ class EndpointResolver(
|
||||
)
|
||||
|
||||
private val probeCache = ConcurrentHashMap<String, CacheEntry>()
|
||||
private val inFlightProbes = ConcurrentHashMap<String, Deferred<Boolean>>()
|
||||
// Every access is owned by [probeStateLock]. This must not be a
|
||||
// concurrently-mutated collection: clearCache() takes a stable snapshot
|
||||
// while completion callbacks remove finished probes.
|
||||
private val inFlightProbes = mutableMapOf<String, Deferred<Boolean>>()
|
||||
private val probeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val probeStateLock = Any()
|
||||
private var probeGeneration = 0L
|
||||
@@ -486,7 +489,13 @@ class EndpointResolver(
|
||||
probe(candidate, surface, generation)
|
||||
}.also { deferred ->
|
||||
inFlightProbes[key] = deferred
|
||||
deferred.invokeOnCompletion { inFlightProbes.remove(key, deferred) }
|
||||
deferred.invokeOnCompletion {
|
||||
synchronized(probeStateLock) {
|
||||
// Identity-aware removal prevents an invalidated
|
||||
// probe from removing its fresh replacement.
|
||||
inFlightProbes.remove(key, deferred)
|
||||
}
|
||||
}
|
||||
deferred.start()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,6 +518,16 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/** Refresh only an existing local ask, preserving its dispatches and transcript position. */
|
||||
fun updateAskCardMessage(messageId: String, card: HermesCard) {
|
||||
_messages.update { list ->
|
||||
list.map { message ->
|
||||
if (message.clientOnly && message.matchesIdentity(messageId)) message.copy(cards = listOf(card))
|
||||
else message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit-and-regenerate local truncation: drop [messageId] and everything
|
||||
* after it. The gateway performs the authoritative truncation via
|
||||
|
||||
@@ -29,6 +29,7 @@ import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
@@ -1506,7 +1507,7 @@ class DashboardApiClient(
|
||||
val patched = buildJsonObject {
|
||||
obj.forEach { (k, v) -> put(k, v) }
|
||||
if (obj["name"] == null && !nameOverride.isNullOrBlank()) put("name", nameOverride)
|
||||
if (obj["model"] == null) put("model", "")
|
||||
if (obj["model"] == null || obj["model"] == JsonNull) put("model", "")
|
||||
}
|
||||
json.decodeFromJsonElement(Profile.serializer(), patched)
|
||||
}.getOrNull()
|
||||
@@ -1525,10 +1526,14 @@ class DashboardApiClient(
|
||||
password: String,
|
||||
next: String = "/",
|
||||
): Result<DashboardLoginResponse> = withContext(Dispatchers.IO) {
|
||||
// Match the Dashboard's single-line HTML username/password controls:
|
||||
// remove only forbidden line breaks and preserve every other code point.
|
||||
val normalizedUsername = username.replace("\r", "").replace("\n", "")
|
||||
val normalizedPassword = password.replace("\r", "").replace("\n", "")
|
||||
val payload = buildJsonObject {
|
||||
put("provider", provider)
|
||||
put("username", username)
|
||||
put("password", password)
|
||||
put("username", normalizedUsername)
|
||||
put("password", normalizedPassword)
|
||||
put("next", next)
|
||||
}
|
||||
val httpUrl = resolveUrl("/auth/password-login")
|
||||
|
||||
@@ -1586,6 +1586,7 @@ class GatewayChatClient(
|
||||
claimedBackground?.pendingAsk?.let { ask ->
|
||||
boundTurn.restoreInteraction(ask)
|
||||
}
|
||||
boundTurn.restorePendingClarify(response)
|
||||
boundTurn.armWatchdog()
|
||||
} else if (queued != null) {
|
||||
synchronized(recoveryEventLock) { recoveryEvents = null }
|
||||
@@ -1746,17 +1747,39 @@ class GatewayChatClient(
|
||||
)
|
||||
|
||||
/** Answer a [GatewayAsk.Kind.CLARIFY] ask. */
|
||||
suspend fun respondClarify(requestId: String, answer: String): Result<GatewayAskResponse> {
|
||||
suspend fun respondClarify(
|
||||
requestId: String,
|
||||
answer: String,
|
||||
questionId: String? = null,
|
||||
): Result<GatewayAskResponse> {
|
||||
val respondingTurn = activeTurn
|
||||
if (questionId != null) {
|
||||
val ask = respondingTurn?.pendingInteraction
|
||||
// A lost acknowledgement is ambiguous until activation replays server progress.
|
||||
// Never overwrite an accepted answer while reconnect is still reconciling it.
|
||||
if (rejoinInProgress || ask?.kind != GatewayAsk.Kind.CLARIFY || ask.requestId != requestId ||
|
||||
ask.questions.none { it.qid == questionId } || ask.ownershipToken.retired.get() ||
|
||||
questionId in ask.ownershipToken.answers.get()
|
||||
) return Result.failure(GatewayRpcException("Clarification is not ready for this question"))
|
||||
}
|
||||
val generation = respondingTurn?.interactionGeneration
|
||||
val ownershipToken = respondingTurn?.pendingInteraction?.ownershipToken
|
||||
return rpc(
|
||||
"clarify.respond",
|
||||
buildJsonObject {
|
||||
put("request_id", requestId)
|
||||
put("answer", answer)
|
||||
questionId?.let { put("question_id", it) }
|
||||
},
|
||||
).map {
|
||||
it.gatewayAskResponse().also {
|
||||
respondingTurn?.acknowledgeInteraction(GatewayAskExpiry(GatewayAsk.Kind.CLARIFY, requestId))
|
||||
if (generation != null) {
|
||||
respondingTurn.acknowledgeClarify(requestId, questionId, answer, it == GatewayAskResponse.EXPIRED, generation)
|
||||
}
|
||||
val currentTurn = activeTurn
|
||||
if (ownershipToken != null && currentTurn !== respondingTurn) {
|
||||
currentTurn?.acknowledgeClarifyOwner(requestId, questionId, answer, it == GatewayAskResponse.EXPIRED, ownershipToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1913,6 +1936,7 @@ class GatewayChatClient(
|
||||
model = row.stringField("model").orEmpty(),
|
||||
provider = row.stringField("provider").orEmpty(),
|
||||
description = row.stringField("description").orEmpty(),
|
||||
displayName = row.stringField("display_name").orEmpty(),
|
||||
skillCount = (row["skill_count"] as? JsonPrimitive)?.intOrNull ?: 0,
|
||||
isDefault = (row["is_default"] as? JsonPrimitive)?.booleanOrNull ?: false,
|
||||
hasAvatar = (row["has_avatar"] as? JsonPrimitive)?.booleanOrNull ?: false,
|
||||
@@ -3853,7 +3877,10 @@ class GatewayChatClient(
|
||||
val interactionRequest = GatewayEventMapper.interactionRequest(type, payload)
|
||||
if (interactionRequest != null) {
|
||||
val previous = backgroundTurn.pendingAsk
|
||||
backgroundTurn.pendingAsk = interactionRequest
|
||||
backgroundTurn.pendingAsk = if (previous?.kind == interactionRequest.kind &&
|
||||
previous.requestId == interactionRequest.requestId && interactionRequest.questions.isNotEmpty()
|
||||
) interactionRequest.withAnswers(previous.answers + interactionRequest.answers, previous)
|
||||
else interactionRequest
|
||||
if (previous?.kind != interactionRequest.kind ||
|
||||
previous.requestId != interactionRequest.requestId
|
||||
) {
|
||||
@@ -3880,6 +3907,7 @@ class GatewayChatClient(
|
||||
// be replayed or buffered. Only an authoritative expiry retires a
|
||||
// detached ask; an explicit response is retired by its foreground VM.
|
||||
if (explicitlyExpired) {
|
||||
pendingAsk.ownershipToken.retired.set(true)
|
||||
backgroundTurn.pendingAsk = null
|
||||
callbackDispatcher {
|
||||
backgroundInteractionListener?.invoke(
|
||||
@@ -3997,6 +4025,9 @@ class GatewayChatClient(
|
||||
}
|
||||
return
|
||||
}
|
||||
if (type == "session.info" && eventSessionId != null && eventSessionId == liveSessionId) {
|
||||
payload?.let(turn::restorePendingClarify)
|
||||
}
|
||||
turn.onEvent(type, payload)
|
||||
if (turn.ended) {
|
||||
if (activeTurn === turn) activeTurn = null
|
||||
@@ -4203,6 +4234,7 @@ class GatewayChatClient(
|
||||
activated.isSuccess -> {
|
||||
activated.getOrNull()?.let { result ->
|
||||
applySessionResultInfo(result)
|
||||
turn.restorePendingClarify(result)
|
||||
turn.settleFromAuthoritativeSessionState(
|
||||
running = result.booleanField("running"),
|
||||
source = "session.activate",
|
||||
@@ -4505,6 +4537,19 @@ class GatewayChatClient(
|
||||
fun acknowledgeInteraction(expiry: GatewayAskExpiry) {
|
||||
mapper.acknowledgeInteraction(expiry)
|
||||
}
|
||||
val interactionGeneration: Long get() = mapper.interactionGeneration
|
||||
fun acknowledgeClarify(requestId: String, questionId: String?, answer: String, expired: Boolean, generation: Long) {
|
||||
mapper.acknowledgeClarify(requestId, questionId, answer, expired, generation)
|
||||
}
|
||||
fun acknowledgeClarifyOwner(requestId: String, questionId: String?, answer: String, expired: Boolean, owner: GatewayAskOwnership) {
|
||||
mapper.acknowledgeClarifyOwner(requestId, questionId, answer, expired, owner)
|
||||
}
|
||||
fun restorePendingClarify(snapshot: JsonObject) {
|
||||
val payload = snapshot["pending_clarify"] as? JsonObject
|
||||
?: (snapshot["info"] as? JsonObject)?.get("pending_clarify") as? JsonObject
|
||||
?: return
|
||||
GatewayEventMapper.interactionRequest("clarify.request", payload)?.let(mapper::restoreInteraction)
|
||||
}
|
||||
private val deferredEventLock = Any()
|
||||
private val deferredEvents = mutableListOf<Pair<String, JsonObject?>>()
|
||||
private var eventsDeferred = deferEvents
|
||||
@@ -5268,6 +5313,7 @@ private fun parseBotRosterEntry(row: JsonObject): BotRosterEntry? {
|
||||
model = row.stringField("model").orEmpty(),
|
||||
provider = row.stringField("provider").orEmpty(),
|
||||
description = row.stringField("description")?.take(512).orEmpty(),
|
||||
displayName = row.stringField("display_name").orEmpty(),
|
||||
skillCount = (row["skill_count"] as? JsonPrimitive)?.intOrNull ?: 0,
|
||||
isDefault = (row["is_default"] as? JsonPrimitive)?.booleanOrNull ?: false,
|
||||
hasAvatar = (row["has_avatar"] as? JsonPrimitive)?.booleanOrNull ?: false,
|
||||
|
||||
@@ -32,19 +32,66 @@ class GatewayEventMapper(
|
||||
var turnEnded: Boolean = false
|
||||
private set
|
||||
|
||||
@get:Synchronized
|
||||
internal val currentInteraction: GatewayAsk?
|
||||
get() = pendingInteraction
|
||||
@Volatile internal var interactionGeneration: Long = 0
|
||||
private set
|
||||
|
||||
internal fun restoreInteraction(ask: GatewayAsk) {
|
||||
val duplicate = pendingInteraction?.sameRequestAs(ask) == true
|
||||
pendingInteraction = ask
|
||||
if (!duplicate) callbacks.onInteractionRequest(ask)
|
||||
@Synchronized internal fun restoreInteraction(ask: GatewayAsk) {
|
||||
val previous = pendingInteraction
|
||||
val duplicate = previous?.sameRequestAs(ask) == true
|
||||
if (!duplicate) interactionGeneration++
|
||||
val merged = if (duplicate && ask.questions.isNotEmpty()) {
|
||||
ask.withAnswers(previous.answers + ask.answers, previous)
|
||||
} else if (ask.questions.isNotEmpty()) ask.withAnswers(emptyMap()) else ask
|
||||
if (merged.ownershipToken.retired.get() && !merged.clarifyComplete) {
|
||||
if (duplicate) pendingInteraction = null
|
||||
callbacks.onInteractionExpired(GatewayAskExpiry(merged.kind, merged.requestId))
|
||||
if (pendingInteraction == null) drainDeferredTerminalEvent()
|
||||
return
|
||||
}
|
||||
pendingInteraction = merged
|
||||
if (!duplicate || previous != merged) callbacks.onInteractionRequest(merged)
|
||||
if (merged.clarifyComplete) {
|
||||
pendingInteraction = null
|
||||
drainDeferredTerminalEvent()
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized internal fun acknowledgeClarify(
|
||||
requestId: String,
|
||||
questionId: String?,
|
||||
answer: String,
|
||||
expired: Boolean,
|
||||
generation: Long = interactionGeneration,
|
||||
) {
|
||||
if (generation != interactionGeneration) return
|
||||
val pending = pendingInteraction ?: return
|
||||
if (pending.kind != GatewayAsk.Kind.CLARIFY || pending.requestId != requestId) return
|
||||
if (!expired && questionId != null && pending.questions.none { it.qid == questionId }) return
|
||||
if (!expired && questionId != null && pending.questions.any { it.qid == questionId }) {
|
||||
val updated = pending.withAnswers(pending.answers + (questionId to answer))
|
||||
if (updated.questions.any { it.qid !in updated.answers }) {
|
||||
pendingInteraction = updated
|
||||
return
|
||||
}
|
||||
}
|
||||
acknowledgeInteraction(GatewayAskExpiry(GatewayAsk.Kind.CLARIFY, requestId))
|
||||
}
|
||||
|
||||
@Synchronized internal fun acknowledgeClarifyOwner(
|
||||
requestId: String, questionId: String?, answer: String, expired: Boolean, owner: GatewayAskOwnership,
|
||||
) {
|
||||
if (pendingInteraction?.ownershipToken !== owner) return
|
||||
acknowledgeClarify(requestId, questionId, answer, expired)
|
||||
}
|
||||
|
||||
/** Retire only the ask whose explicit respond RPC reached server truth. */
|
||||
internal fun acknowledgeInteraction(expiry: GatewayAskExpiry) {
|
||||
@Synchronized internal fun acknowledgeInteraction(expiry: GatewayAskExpiry) {
|
||||
val pending = pendingInteraction ?: return
|
||||
if (pending.matches(expiry)) {
|
||||
pending.ownershipToken.retired.set(true)
|
||||
pendingInteraction = null
|
||||
drainDeferredTerminalEvent()
|
||||
}
|
||||
@@ -77,7 +124,7 @@ class GatewayEventMapper(
|
||||
*/
|
||||
private val generatingIdsByName = mutableMapOf<String, ArrayDeque<String>>()
|
||||
|
||||
fun onEvent(type: String, payload: JsonObject?) {
|
||||
@Synchronized fun onEvent(type: String, payload: JsonObject?) {
|
||||
if (turnEnded) return
|
||||
|
||||
interactionRequest(type, payload)?.let { ask ->
|
||||
@@ -88,6 +135,7 @@ class GatewayEventMapper(
|
||||
interactionExpiry(type, payload)?.let { expiry ->
|
||||
val pending = pendingInteraction
|
||||
if (pending != null && pending.matches(expiry)) {
|
||||
pending.ownershipToken.retired.set(true)
|
||||
pendingInteraction = null
|
||||
}
|
||||
callbacks.onInteractionExpired(expiry)
|
||||
@@ -503,26 +551,7 @@ class GatewayEventMapper(
|
||||
}
|
||||
|
||||
fun interactionRequest(type: String, payload: JsonObject?): GatewayAsk? = when (type) {
|
||||
"clarify.request" -> {
|
||||
val choices = (payload?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim() }
|
||||
?.filter { it.isNotEmpty() }
|
||||
?.distinct()
|
||||
?.take(MAX_CLARIFY_CHOICES)
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
GatewayAsk(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
requestId = payload.string("request_id"),
|
||||
text = payload.string("question") ?: "The agent needs clarification",
|
||||
choices = choices,
|
||||
multiSelect = payload.boolean("multi_select") == true && choices != null,
|
||||
// Current upstream owns expiry through clarify.expire and
|
||||
// does not advertise its configurable deadline. Never
|
||||
// invent a local deadline; consume future additive
|
||||
// metadata only when it is present and positive.
|
||||
timeoutSeconds = payload.int("timeout_seconds")?.coerceAtLeast(0) ?: 0,
|
||||
)
|
||||
}
|
||||
"clarify.request" -> clarifyRequest(payload)
|
||||
|
||||
"approval.request" -> GatewayAsk(
|
||||
kind = GatewayAsk.Kind.APPROVAL,
|
||||
@@ -555,6 +584,41 @@ class GatewayEventMapper(
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun clarifyRequest(payload: JsonObject?): GatewayAsk? {
|
||||
val rawQuestions = payload?.get("questions")
|
||||
if (rawQuestions != null && rawQuestions !is JsonArray) return null
|
||||
val questions = rawQuestions?.map { value ->
|
||||
val row = value as? JsonObject ?: return null
|
||||
val qid = (row["qid"] as? JsonPrimitive)?.takeIf { it.isString }
|
||||
?.contentOrNull?.takeIf(String::isNotBlank) ?: return null
|
||||
val text = row.string("question")?.takeIf(String::isNotBlank) ?: return null
|
||||
val choices = (row["choices"] as? JsonArray)?.mapNotNull {
|
||||
(it as? JsonPrimitive)?.takeIf { option -> option.isString }
|
||||
?.contentOrNull?.takeIf(String::isNotBlank)
|
||||
}.orEmpty().take(MAX_CLARIFY_CHOICES)
|
||||
GatewayClarifyQuestion(qid, text, choices, row.boolean("multi_select") == true && choices.isNotEmpty())
|
||||
}.orEmpty()
|
||||
if (questions.size > MAX_CLARIFY_QUESTIONS || questions.map { it.qid }.distinct().size != questions.size) return null
|
||||
val choices = (payload?.get("choices") as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim() }
|
||||
?.filter(String::isNotEmpty)?.distinct()?.take(MAX_CLARIFY_CHOICES)
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
return GatewayAsk(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
requestId = payload.string("request_id"),
|
||||
text = payload.string("question") ?: "The agent needs clarification",
|
||||
choices = choices,
|
||||
multiSelect = payload.boolean("multi_select") == true && choices != null,
|
||||
// Upstream owns its configurable deadline; only consume advertised metadata.
|
||||
timeoutSeconds = payload.int("timeout_seconds")?.coerceAtLeast(0) ?: 0,
|
||||
questions = questions,
|
||||
answers = (payload?.get("answers") as? JsonObject)?.mapNotNull { (qid, value) ->
|
||||
(value as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull
|
||||
?.takeIf { questions.any { q -> q.qid == qid } }?.let { qid to it }
|
||||
}?.toMap().orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
fun interactionExpiry(type: String, payload: JsonObject?): GatewayAskExpiry? = when (type) {
|
||||
"clarify.expire" -> GatewayAskExpiry(
|
||||
kind = GatewayAsk.Kind.CLARIFY,
|
||||
@@ -634,6 +698,7 @@ class GatewayEventMapper(
|
||||
// Upstream clarify tool accepts at most four choices. Sudo/secret retain fixed
|
||||
// `_block()` timeouts; clarify is configurable and expires authoritatively.
|
||||
private const val MAX_CLARIFY_CHOICES = 4
|
||||
private const val MAX_CLARIFY_QUESTIONS = 5
|
||||
private const val SUDO_TIMEOUT_SECONDS = 120
|
||||
private const val SECRET_TIMEOUT_SECONDS = 300
|
||||
|
||||
|
||||
@@ -2,11 +2,14 @@ package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.UsageInfo
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* Shared types for the Gateway chat transport — upstream hermes-agent's
|
||||
@@ -230,10 +233,35 @@ data class GatewayAsk(
|
||||
* authoritative `*.expire` event still retires the interaction.
|
||||
*/
|
||||
val timeoutSeconds: Int,
|
||||
val questions: List<GatewayClarifyQuestion> = emptyList(),
|
||||
val answers: Map<String, String> = emptyMap(),
|
||||
) {
|
||||
enum class Kind { CLARIFY, APPROVAL, SUDO, SECRET }
|
||||
val clarifyComplete: Boolean get() = questions.isNotEmpty() && questions.all { it.qid in answers }
|
||||
|
||||
/** In-memory request incarnation shared when a live ask moves between turn mappers. */
|
||||
internal var ownershipToken = GatewayAskOwnership(answers)
|
||||
private set
|
||||
|
||||
internal fun withAnswers(answers: Map<String, String>, owner: GatewayAsk = this): GatewayAsk =
|
||||
copy(answers = owner.ownershipToken.answers.updateAndGet { it + answers })
|
||||
.also { it.ownershipToken = owner.ownershipToken }
|
||||
}
|
||||
|
||||
/** A detached/reclaimed mapper shares confirmed progress with an RPC still owned by its predecessor. */
|
||||
internal class GatewayAskOwnership(answers: Map<String, String>) {
|
||||
val answers = AtomicReference(answers.toMap())
|
||||
val retired = AtomicBoolean(false)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class GatewayClarifyQuestion(
|
||||
val qid: String,
|
||||
val question: String,
|
||||
val choices: List<String> = emptyList(),
|
||||
val multiSelect: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Server-side expiry of one blocking gateway interaction. Sudo/secret asks
|
||||
* correlate by [requestId]; approvals remain session-scoped and therefore
|
||||
|
||||
@@ -351,14 +351,18 @@ internal class HermesRuntimeBinder(
|
||||
connection.activeConnectionId,
|
||||
connection.effectiveSessionProfileName,
|
||||
connection.lastSessionId,
|
||||
connection.activeEndpoint,
|
||||
) { ready, connectionId, profileName, sessionId, activeEndpoint ->
|
||||
// The session directory belongs to the standard Dashboard
|
||||
// route. connection.activeEndpoint is the optional Relay
|
||||
// socket's selected candidate and stays null on a valid
|
||||
// Dashboard-only LAN connection.
|
||||
connection.effectiveDashboardUrl,
|
||||
) { ready, connectionId, profileName, sessionId, dashboardUrl ->
|
||||
ProfileContextInputs(
|
||||
ready,
|
||||
connectionId,
|
||||
profileName,
|
||||
sessionId,
|
||||
dashboardRouteResolved = activeEndpoint != null,
|
||||
dashboardUrl = dashboardUrl,
|
||||
)
|
||||
}
|
||||
combine(
|
||||
@@ -374,7 +378,7 @@ internal class HermesRuntimeBinder(
|
||||
)
|
||||
}.collectLatest { inputs ->
|
||||
profileContextReady.value = false
|
||||
if (!shouldRefreshSessionDirectory(inputs.chatReady, inputs.dashboardRouteResolved)) {
|
||||
if (!shouldRefreshSessionDirectory(inputs.chatReady, inputs.dashboardUrl)) {
|
||||
return@collectLatest
|
||||
}
|
||||
if (!inputs.profileSelectionSettled) {
|
||||
@@ -600,7 +604,7 @@ internal class HermesRuntimeBinder(
|
||||
val connectionId: String?,
|
||||
val profileName: String?,
|
||||
val sessionId: String?,
|
||||
val dashboardRouteResolved: Boolean,
|
||||
val dashboardUrl: String,
|
||||
val profileSelectionSettled: Boolean = false,
|
||||
val profileLocked: Boolean = false,
|
||||
val hiddenSources: Set<String> = emptySet(),
|
||||
@@ -632,12 +636,13 @@ internal class HermesRuntimeBinder(
|
||||
/**
|
||||
* Session browsing is Dashboard HTTP state, not Gateway-socket state. API-only
|
||||
* connections still use chat readiness; Dashboard connections can refresh once
|
||||
* the resolver has selected a live route, after the profile-settle fence.
|
||||
* their persisted/resolved Dashboard origin publishes, after the profile-settle
|
||||
* fence. The optional Relay endpoint is deliberately not part of this decision.
|
||||
*/
|
||||
internal fun shouldRefreshSessionDirectory(
|
||||
chatReady: Boolean,
|
||||
dashboardRouteResolved: Boolean,
|
||||
): Boolean = chatReady || dashboardRouteResolved
|
||||
dashboardUrl: String,
|
||||
): Boolean = chatReady || dashboardUrl.isNotBlank()
|
||||
|
||||
internal fun assistantCanTransmitScreenContext(engineMode: VoiceEngineMode): Boolean =
|
||||
engineMode == VoiceEngineMode.HermesVoiceOutput
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.heading
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyBatch
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** One mobile question surface; confirmed qids advance without resubmitting earlier answers. */
|
||||
@Composable
|
||||
internal fun ClarifyBatchContent(
|
||||
batch: HermesCardClarifyBatch,
|
||||
expired: Boolean,
|
||||
onInputSubmit: (String, String) -> Unit,
|
||||
) {
|
||||
val answered = batch.questions.filter { it.answer != null }
|
||||
val activeIndex = batch.questions.indexOfFirst { it.answer == null }
|
||||
val active = batch.questions.getOrNull(activeIndex)
|
||||
var showAnswers by rememberSaveable { mutableStateOf(false) }
|
||||
val focusManager = LocalFocusManager.current
|
||||
LaunchedEffect(active?.key, expired) { focusManager.clearFocus() }
|
||||
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = when {
|
||||
expired -> stringResource(R.string.clarify_batch_expired)
|
||||
active == null -> stringResource(R.string.clarify_batch_complete)
|
||||
else -> stringResource(R.string.clarify_batch_progress, activeIndex + 1, batch.questions.size)
|
||||
},
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
|
||||
)
|
||||
if (batch.questions.size > 1) {
|
||||
LinearProgressIndicator(
|
||||
progress = { answered.size.toFloat() / batch.questions.size },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
if (active != null && !expired) {
|
||||
key(active.key) {
|
||||
Text(
|
||||
active.question,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.semantics { heading() },
|
||||
)
|
||||
CardInputSlot(
|
||||
input = active.input,
|
||||
onSubmit = { if (!active.submitting) onInputSubmit(active.key, it) },
|
||||
enabled = !active.submitting,
|
||||
stackedChoices = true,
|
||||
)
|
||||
if (active.submitting) {
|
||||
Text(stringResource(R.string.clarify_batch_sending), style = MaterialTheme.typography.labelMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (answered.isNotEmpty()) {
|
||||
if (active == null || expired) {
|
||||
Text(stringResource(R.string.clarify_batch_answered, answered.size), style = MaterialTheme.typography.labelLarge)
|
||||
} else {
|
||||
TextButton(onClick = { showAnswers = !showAnswers }) {
|
||||
Text(stringResource(R.string.clarify_batch_answered, answered.size))
|
||||
}
|
||||
}
|
||||
if (showAnswers || active == null || expired) {
|
||||
answered.forEach { question ->
|
||||
Text(question.question, style = MaterialTheme.typography.labelLarge)
|
||||
val answer = if (question.input.multiSelect) {
|
||||
runCatching { Json.decodeFromString<List<String>>(question.answer.orEmpty()).joinToString(", ") }
|
||||
.getOrDefault(question.answer.orEmpty())
|
||||
} else question.answer.orEmpty()
|
||||
Text(answer, style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3625,7 +3625,7 @@ internal fun ProfileDisplayManagerDialog(
|
||||
val isServerDefault = key == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
val profile = profiles.firstOrNull { it.name == key }
|
||||
val label = if (isServerDefault) {
|
||||
stringResource(R.string.conn_info_server_default)
|
||||
stringResource(R.string.profile_follow_server_default)
|
||||
} else {
|
||||
profile?.let(AgentDisplay::profileDisplayName)
|
||||
?: key.replaceFirstChar { it.uppercase() }
|
||||
|
||||
@@ -59,6 +59,7 @@ import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
@@ -145,7 +146,7 @@ fun HermesCardBubble(
|
||||
// Expiry clock for timed asks. Ticks once a second while the deadline
|
||||
// is ahead; freezes after. Keyed on the deadline so a re-used card id
|
||||
// with a fresh expiry restarts the loop.
|
||||
val expiresAt = card.input?.expiresAtMillis
|
||||
val expiresAt = card.input?.expiresAtMillis ?: card.clarifyBatch?.expiresAtMillis
|
||||
var nowMillis by remember(expiresAt) { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(expiresAt) {
|
||||
if (expiresAt == null) return@LaunchedEffect
|
||||
@@ -252,6 +253,14 @@ fun HermesCardBubble(
|
||||
// action button all collapse the same way.
|
||||
val input = card.input
|
||||
when {
|
||||
card.clarifyBatch != null -> {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
ClarifyBatchContent(
|
||||
batch = card.clarifyBatch,
|
||||
expired = expired || alreadyChosen?.actionValue == HermesCardDispatch.EXPIRED_STAMP,
|
||||
onInputSubmit = onInputSubmit,
|
||||
)
|
||||
}
|
||||
alreadyChosen != null -> {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val chosenAction = card.actions.firstOrNull {
|
||||
@@ -408,15 +417,18 @@ private fun ChoseRow(
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun CardInputSlot(
|
||||
internal fun CardInputSlot(
|
||||
input: HermesCardInput,
|
||||
onSubmit: (String) -> Unit,
|
||||
enabled: Boolean = true,
|
||||
stackedChoices: Boolean = false,
|
||||
) {
|
||||
// Deliberately remember, not rememberSaveable — a typed secret must
|
||||
// never be written into the saved-instance-state Bundle.
|
||||
var answerText by remember { mutableStateOf("") }
|
||||
// Batch drafts survive lazy-item disposal. Secrets never enter saved state.
|
||||
var answerText by if (stackedChoices && !input.masked) rememberSaveable { mutableStateOf("") }
|
||||
else remember { mutableStateOf("") }
|
||||
var reveal by remember { mutableStateOf(false) }
|
||||
var selectedChoices by remember(input.choices) { mutableStateOf(emptyList<String>()) }
|
||||
var selectedChoices by if (stackedChoices) rememberSaveable(input.choices) { mutableStateOf(emptyList<String>()) }
|
||||
else remember(input.choices) { mutableStateOf(emptyList<String>()) }
|
||||
val isMultiSelect = input.multiSelect && input.choices.isNotEmpty()
|
||||
|
||||
val showFreeText = !input.masked && (
|
||||
@@ -429,7 +441,7 @@ private fun CardInputSlot(
|
||||
|
||||
val submitFreeText = {
|
||||
val customAnswer = answerText.trim()
|
||||
if (customAnswer.isNotEmpty()) {
|
||||
if (enabled && customAnswer.isNotEmpty()) {
|
||||
onSubmit(
|
||||
if (isMultiSelect) {
|
||||
encodeClarifyMultiSelectAnswer(selectedChoices + customAnswer)
|
||||
@@ -443,14 +455,13 @@ private fun CardInputSlot(
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
// Choice chips
|
||||
if (input.choices.isNotEmpty()) {
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
val choices: @Composable () -> Unit = {
|
||||
input.choices.forEach { choice ->
|
||||
if (isMultiSelect) {
|
||||
val selected = choice in selectedChoices
|
||||
FilterChip(
|
||||
enabled = enabled,
|
||||
modifier = if (stackedChoices) Modifier.fillMaxWidth() else Modifier,
|
||||
selected = selected,
|
||||
onClick = {
|
||||
selectedChoices = if (selected) {
|
||||
@@ -459,7 +470,11 @@ private fun CardInputSlot(
|
||||
selectedChoices + choice
|
||||
}
|
||||
},
|
||||
label = { Text(choice, style = MaterialTheme.typography.labelMedium) },
|
||||
label = {
|
||||
Text(choice,
|
||||
style = if (stackedChoices) MaterialTheme.typography.bodyMedium else MaterialTheme.typography.labelMedium,
|
||||
modifier = if (stackedChoices) Modifier.padding(vertical = 8.dp) else Modifier)
|
||||
},
|
||||
leadingIcon = if (selected) {
|
||||
{
|
||||
Icon(
|
||||
@@ -477,9 +492,13 @@ private fun CardInputSlot(
|
||||
)
|
||||
} else {
|
||||
AssistChip(
|
||||
enabled = enabled,
|
||||
modifier = if (stackedChoices) Modifier.fillMaxWidth() else Modifier,
|
||||
onClick = { onSubmit(choice) },
|
||||
label = {
|
||||
Text(choice, style = MaterialTheme.typography.labelMedium)
|
||||
Text(choice,
|
||||
style = if (stackedChoices) MaterialTheme.typography.bodyMedium else MaterialTheme.typography.labelMedium,
|
||||
modifier = if (stackedChoices) Modifier.padding(vertical = 8.dp) else Modifier)
|
||||
},
|
||||
colors = AssistChipDefaults.assistChipColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
@@ -489,6 +508,11 @@ private fun CardInputSlot(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stackedChoices) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { choices() }
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { choices() }
|
||||
}
|
||||
}
|
||||
|
||||
// Masked secret field
|
||||
@@ -534,12 +558,13 @@ private fun CardInputSlot(
|
||||
else R.string.card_answer_placeholder,
|
||||
),
|
||||
onSubmit = submitFreeText,
|
||||
enabled = enabled,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!isMultiSelect) {
|
||||
IconButton(
|
||||
onClick = submitFreeText,
|
||||
enabled = answerText.isNotBlank(),
|
||||
enabled = enabled && answerText.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.Send,
|
||||
@@ -559,7 +584,7 @@ private fun CardInputSlot(
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Button(
|
||||
onClick = { onSubmit(encodeClarifyMultiSelectAnswer(answers)) },
|
||||
enabled = answers.isNotEmpty(),
|
||||
enabled = enabled && answers.isNotEmpty(),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.card_submit),
|
||||
@@ -615,6 +640,7 @@ private fun InlineAnswerField(
|
||||
placeholder: String,
|
||||
onSubmit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val shape = appearanceRoundedCornerShape(16.dp)
|
||||
Box(
|
||||
@@ -632,6 +658,7 @@ private fun InlineAnswerField(
|
||||
)
|
||||
}
|
||||
BasicTextField(
|
||||
enabled = enabled,
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(
|
||||
@@ -639,7 +666,7 @@ private fun InlineAnswerField(
|
||||
),
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||
keyboardActions = KeyboardActions(onSend = { onSubmit() }),
|
||||
keyboardActions = KeyboardActions(onSend = { onSubmit() }, onDone = { onSubmit() }),
|
||||
maxLines = 3,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
|
||||
@@ -23,14 +23,9 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||
|
||||
/**
|
||||
* Bottom-sheet audit of the exact extra context the agent is injected with on
|
||||
* the next turn — opened by tapping the chat [ContextMeterBar].
|
||||
*
|
||||
* Renders the SAME [ChatViewModel.InjectedContext] the send path builds (via
|
||||
* [ChatViewModel.previewInjectedContext] → `composeInjectedContext`), so it is
|
||||
* a faithful audit, not a re-derivation that could drift. Empty blocks show a
|
||||
* labeled note instead of vanishing, and the gateway's server-side persona is
|
||||
* explicitly called out as not-sent-from-this-device.
|
||||
* Transport-aware context preview, opened from the chat [ContextMeterBar].
|
||||
* Unsupported blocks are labeled rather than represented as delivered.
|
||||
* Server-reported configuration is separate from device-supplied context.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -53,7 +48,7 @@ fun InjectedContextSheet(
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.injected_context_subtitle, context.transport),
|
||||
text = stringResource(R.string.injected_context_subtitle),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -71,6 +66,7 @@ fun InjectedContextSheet(
|
||||
val mediaNoRelay = stringResource(R.string.injected_context_media_no_relay)
|
||||
val relayNotSet = stringResource(R.string.injected_context_relay_not_set)
|
||||
val turnNotSet = stringResource(R.string.injected_context_turn_not_set)
|
||||
val unsupported = stringResource(R.string.injected_context_gateway_unsupported)
|
||||
|
||||
ContextSection(
|
||||
title = personaTitle,
|
||||
@@ -84,7 +80,7 @@ fun InjectedContextSheet(
|
||||
ContextSection(
|
||||
title = phoneStatusTitle,
|
||||
body = context.appContext,
|
||||
emptyNote = phoneStatusNotSet,
|
||||
emptyNote = if (context.perTurnContextSupported) phoneStatusNotSet else unsupported,
|
||||
)
|
||||
ContextSection(
|
||||
title = mediaTitle,
|
||||
@@ -107,7 +103,7 @@ fun InjectedContextSheet(
|
||||
ContextSection(
|
||||
title = turnTitle,
|
||||
body = context.interfaceContext,
|
||||
emptyNote = turnNotSet,
|
||||
emptyNote = if (context.perTurnContextSupported) turnNotSet else unsupported,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.RectangleShape
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -214,7 +215,7 @@ fun MessageBubble(
|
||||
message.role == MessageRole.USER -> MaterialTheme.colorScheme.primary
|
||||
message.role == MessageRole.SYSTEM -> MaterialTheme.colorScheme.tertiaryContainer
|
||||
isActionBubble -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.45f)
|
||||
else -> MaterialTheme.colorScheme.surfaceVariant
|
||||
else -> MaterialTheme.colorScheme.surfaceContainerLow
|
||||
}
|
||||
|
||||
val textColor = when (message.role) {
|
||||
@@ -436,8 +437,8 @@ fun MessageBubble(
|
||||
// rows) would otherwise paint a bare timestamp-only chip between the
|
||||
// Thought-process block and the tool pill. The first-token working state
|
||||
// is rendered directly in the conversation
|
||||
// lane below, without an opaque bubble. Cards and attachments still own
|
||||
// a normal bubble even when response prose has not arrived yet.
|
||||
// lane below, without an opaque bubble. Standalone cards own their own
|
||||
// surface; wrapping those in another filled bubble duplicates the chrome.
|
||||
streamingStatusLabel?.takeIf { showWorkingStatus }?.let { streamingStatus ->
|
||||
StandaloneStreamingStatus(
|
||||
status = streamingStatus,
|
||||
@@ -454,6 +455,10 @@ fun MessageBubble(
|
||||
message.cards.isNotEmpty() ||
|
||||
message.attachments.isNotEmpty() ||
|
||||
inlineImages.isNotEmpty()
|
||||
val standaloneCards = !isUser && !isSystem &&
|
||||
visibleMessageContent.isBlank() && quoteEnvelope == null &&
|
||||
message.cards.isNotEmpty() && message.attachments.isEmpty() &&
|
||||
inlineImages.isEmpty() && !showImageGeneration
|
||||
if (showBubble) {
|
||||
Row(
|
||||
modifier = Modifier.widthIn(max = maxBubbleWidth),
|
||||
@@ -599,11 +604,11 @@ fun MessageBubble(
|
||||
),
|
||||
) {
|
||||
Surface(
|
||||
shape = bubbleShape,
|
||||
color = backgroundColor,
|
||||
shape = if (standaloneCards) RectangleShape else bubbleShape,
|
||||
color = if (standaloneCards) Color.Transparent else backgroundColor,
|
||||
modifier = Modifier
|
||||
.then(
|
||||
if (!isUser && !isSystem && isDarkTheme) {
|
||||
if (!isUser && !isSystem && isDarkTheme && !standaloneCards) {
|
||||
Modifier.leftEdgeGlow(
|
||||
alpha = 0.12f,
|
||||
width = 28.dp,
|
||||
@@ -651,7 +656,8 @@ fun MessageBubble(
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
modifier = if (standaloneCards) Modifier
|
||||
else Modifier.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
) {
|
||||
quoteEnvelope?.let { envelope ->
|
||||
ChatQuoteReferenceChip(
|
||||
@@ -741,7 +747,7 @@ fun MessageBubble(
|
||||
onInputSubmit = { key, value ->
|
||||
onCardInput(message.id, key, value)
|
||||
},
|
||||
maxWidth = maxBubbleWidth - 24.dp,
|
||||
maxWidth = if (standaloneCards) maxBubbleWidth else maxBubbleWidth - 24.dp,
|
||||
modifier = Modifier.padding(vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
@@ -823,6 +829,7 @@ fun MessageBubble(
|
||||
|
||||
val hasTokenUsage = showUsage && !isUser &&
|
||||
(message.inputTokens != null || message.outputTokens != null)
|
||||
val deliveryStatus = message.deliveryStatus?.takeIf { isUser }
|
||||
|
||||
// Timestamp — only on the LAST bubble of a same-author run so a
|
||||
// burst of fragments doesn't stack three near-touching time labels.
|
||||
@@ -831,13 +838,14 @@ fun MessageBubble(
|
||||
// This row is reserved from the first streaming frame. Completion
|
||||
// can reveal both timestamp and token usage without adding a new
|
||||
// footer line or changing the bubble's measured height.
|
||||
if (isLastInGroup && (showTimestamps || hasTokenUsage)) {
|
||||
if ((isLastInGroup && (showTimestamps || hasTokenUsage)) || deliveryStatus != null) {
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = if (standaloneCards) Modifier.padding(horizontal = 4.dp) else Modifier,
|
||||
) {
|
||||
if (showTimestamps) Text(
|
||||
if (isLastInGroup && showTimestamps) Text(
|
||||
text = timeFormat.format(Date(message.timestamp)),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = textColor.copy(alpha = if (message.isStreaming) 0f else 0.6f),
|
||||
@@ -847,33 +855,30 @@ fun MessageBubble(
|
||||
Modifier
|
||||
},
|
||||
)
|
||||
if (hasTokenUsage) {
|
||||
if (isLastInGroup && hasTokenUsage) {
|
||||
TokenDisplay(
|
||||
inputTokens = message.inputTokens,
|
||||
outputTokens = message.outputTokens,
|
||||
)
|
||||
}
|
||||
// Share the footer line, retaining the user bubble's contrasting foreground.
|
||||
deliveryStatus?.let { status ->
|
||||
MessageDeliveryIndicator(
|
||||
status = status,
|
||||
contentColor = textColor,
|
||||
text = MessageDeliveryIndicatorText(
|
||||
sending = stringResource(R.string.msg_bubble_sending),
|
||||
queued = stringResource(R.string.msg_bubble_queued),
|
||||
steered = stringResource(R.string.msg_bubble_steered),
|
||||
delivered = stringResource(R.string.msg_bubble_delivered),
|
||||
failed = stringResource(R.string.msg_bubble_not_sent),
|
||||
tapToRetry = stringResource(R.string.chat_retry),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delivery status for local user messages, including steering.
|
||||
// Use the bubble's foreground: accent-on-accent hides the label.
|
||||
message.deliveryStatus?.takeIf { isUser }?.let { status ->
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
MessageDeliveryIndicator(
|
||||
status = status,
|
||||
contentColor = textColor,
|
||||
text = MessageDeliveryIndicatorText(
|
||||
sending = stringResource(R.string.msg_bubble_sending),
|
||||
queued = stringResource(R.string.msg_bubble_queued),
|
||||
steered = stringResource(R.string.msg_bubble_steered),
|
||||
delivered = stringResource(R.string.msg_bubble_delivered),
|
||||
failed = stringResource(R.string.msg_bubble_not_sent),
|
||||
tapToRetry = stringResource(R.string.chat_retry),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Non-tail historical fragments have no reserved timestamp row.
|
||||
// Preserve their existing standalone token metadata layout.
|
||||
if (!isLastInGroup && hasTokenUsage) {
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
@@ -41,6 +42,8 @@ import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -80,9 +83,10 @@ object ProfileShelfPolicy {
|
||||
profiles: List<Profile>,
|
||||
presentation: ProfilePresentation,
|
||||
selectedProfileName: String?,
|
||||
serverDefaultProfileName: String? = null,
|
||||
): List<ProfileChoice> {
|
||||
val selectedKey = AgentDisplay.profileSessionKey(selectedProfileName)
|
||||
return ProfilePresentationPolicy
|
||||
val choices = ProfilePresentationPolicy
|
||||
.visibleKeys(profiles, presentation, selectedKey)
|
||||
.mapNotNull { key ->
|
||||
if (key == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY) {
|
||||
@@ -91,6 +95,17 @@ object ProfileShelfPolicy {
|
||||
profiles.firstOrNull { it.name == key }?.let { ProfileChoice(key, it) }
|
||||
}
|
||||
}
|
||||
// Group only exact upstream identities, never matching display labels.
|
||||
// Keep the selected choice's request/presentation key unchanged.
|
||||
val hasDefault = choices.any { it.isServerDefault }
|
||||
val hasResolved = choices.any { it.key == serverDefaultProfileName }
|
||||
if (!hasDefault || !hasResolved) return choices
|
||||
val omittedKey = if (selectedProfileName == serverDefaultProfileName) {
|
||||
AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
} else {
|
||||
serverDefaultProfileName
|
||||
}
|
||||
return choices.filterNot { it.key == omittedKey }
|
||||
}
|
||||
|
||||
fun canSwitch(isStreaming: Boolean, streamingEndpoint: String): Boolean =
|
||||
@@ -124,8 +139,9 @@ fun ProfileShelf(
|
||||
onHide: (String?) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val choices = remember(profiles, presentation, selectedProfile?.name) {
|
||||
ProfileShelfPolicy.choices(profiles, presentation, selectedProfile?.name)
|
||||
val serverDefaultProfile by connectionViewModel.serverDefaultDisplayProfile.collectAsState()
|
||||
val choices = remember(profiles, presentation, selectedProfile?.name, serverDefaultProfile) {
|
||||
ProfileShelfPolicy.choices(profiles, presentation, selectedProfile?.name, serverDefaultProfile?.name)
|
||||
}
|
||||
if (choices.size <= 1) return
|
||||
|
||||
@@ -157,7 +173,7 @@ fun ProfileShelf(
|
||||
val label = if (selected) {
|
||||
activeDisplayName
|
||||
} else {
|
||||
profileChoiceLabel(choice, resolvedProfile)
|
||||
profileChoiceLabel(choice, serverDefaultProfile)
|
||||
}
|
||||
if (selected) {
|
||||
val openPassportDescription = stringResource(R.string.profile_shelf_open_passport)
|
||||
@@ -191,7 +207,7 @@ fun ProfileShelf(
|
||||
ProfileChoiceAvatar(
|
||||
connectionViewModel,
|
||||
choice,
|
||||
resolvedProfile,
|
||||
serverDefaultProfile,
|
||||
label,
|
||||
36,
|
||||
)
|
||||
@@ -238,7 +254,7 @@ fun ProfileShelf(
|
||||
ProfileChoiceAvatar(
|
||||
connectionViewModel,
|
||||
choice,
|
||||
resolvedProfile,
|
||||
serverDefaultProfile,
|
||||
label,
|
||||
36,
|
||||
)
|
||||
@@ -275,8 +291,8 @@ fun ProfileShelf(
|
||||
|
||||
actionChoice?.let { choice ->
|
||||
val selected = ProfileShelfPolicy.isSelected(choice, selectedProfile?.name)
|
||||
val target = choice.profile ?: resolvedProfile
|
||||
val label = profileChoiceLabel(choice, resolvedProfile)
|
||||
val target = choice.profile ?: serverDefaultProfile
|
||||
val label = profileChoiceLabel(choice, serverDefaultProfile)
|
||||
ProfileShelfActionsDialog(
|
||||
label = label,
|
||||
canSwitch = switchEnabled && !isProfileLocked,
|
||||
@@ -319,10 +335,14 @@ fun ProfileSwitcherSheet(
|
||||
onManageDisplay: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val choices = remember(profiles, presentation, selectedProfile?.name) {
|
||||
ProfileShelfPolicy.choices(profiles, presentation, selectedProfile?.name)
|
||||
val serverDefaultProfile by connectionViewModel.serverDefaultDisplayProfile.collectAsState()
|
||||
val choices = remember(profiles, presentation, selectedProfile?.name, serverDefaultProfile) {
|
||||
ProfileShelfPolicy.choices(profiles, presentation, selectedProfile?.name, serverDefaultProfile?.name)
|
||||
}
|
||||
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = onDismiss,
|
||||
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -346,8 +366,15 @@ fun ProfileSwitcherSheet(
|
||||
}
|
||||
choices.forEach { choice ->
|
||||
val selected = ProfileShelfPolicy.isSelected(choice, selectedProfile?.name)
|
||||
val label = profileChoiceLabel(choice, resolvedProfile)
|
||||
val model = choice.profile?.model?.takeIf { it.isNotBlank() }
|
||||
val label = profileChoiceLabel(choice, serverDefaultProfile)
|
||||
val target = if (choice.isServerDefault) serverDefaultProfile else choice.profile
|
||||
val defaultGroup = serverDefaultProfile != null &&
|
||||
(choice.isServerDefault || choice.key == serverDefaultProfile?.name)
|
||||
val detail = listOfNotNull(
|
||||
stringResource(R.string.conn_info_server_default).takeIf { defaultGroup },
|
||||
target?.name?.takeIf { it != label },
|
||||
target?.model?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · ")
|
||||
ListItem(
|
||||
modifier = Modifier.selectable(
|
||||
selected = selected,
|
||||
@@ -361,13 +388,13 @@ fun ProfileSwitcherSheet(
|
||||
headlineContent = {
|
||||
Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
supportingContent = if (model != null) {
|
||||
{ Text(model, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
supportingContent = if (detail.isNotBlank()) {
|
||||
{ Text(detail, maxLines = 2, overflow = TextOverflow.Ellipsis) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
leadingContent = {
|
||||
ProfileChoiceAvatar(connectionViewModel, choice, resolvedProfile, label, 42)
|
||||
ProfileChoiceAvatar(connectionViewModel, choice, serverDefaultProfile, label, 42)
|
||||
},
|
||||
trailingContent = if (selected) {
|
||||
{ Icon(Icons.Filled.Check, contentDescription = null) }
|
||||
@@ -375,6 +402,27 @@ fun ProfileSwitcherSheet(
|
||||
null
|
||||
},
|
||||
)
|
||||
if (defaultGroup && selected) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)
|
||||
.toggleable(
|
||||
value = choice.isServerDefault,
|
||||
enabled = switchEnabled && !isProfileLocked,
|
||||
role = Role.Checkbox,
|
||||
onValueChange = {
|
||||
onSelect(if (choice.isServerDefault) serverDefaultProfile else null)
|
||||
onDismiss()
|
||||
},
|
||||
).padding(start = 64.dp, end = 24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = choice.isServerDefault, onCheckedChange = null,
|
||||
enabled = switchEnabled && !isProfileLocked)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text(stringResource(R.string.profile_follow_server_default),
|
||||
style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider(modifier = Modifier.padding(top = 8.dp))
|
||||
TextButton(
|
||||
@@ -518,7 +566,8 @@ private fun ProfileActionRow(
|
||||
@Composable
|
||||
private fun profileChoiceLabel(choice: ProfileChoice, resolvedProfile: Profile?): String =
|
||||
if (choice.isServerDefault) {
|
||||
stringResource(R.string.conn_info_server_default)
|
||||
AgentDisplay.profileDisplayName(resolvedProfile)
|
||||
?: stringResource(R.string.conn_info_server_default)
|
||||
} else {
|
||||
choice.profile?.let(AgentDisplay::profileDisplayName)
|
||||
?: choice.profile?.name?.replaceFirstChar { it.uppercase() }
|
||||
|
||||
@@ -463,6 +463,21 @@ internal fun shouldShowRetainedHistoryDashboardSignIn(
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired &&
|
||||
!apiReachable
|
||||
|
||||
/**
|
||||
* A foreground Gateway-owned Chat must be allowed to open its observation
|
||||
* socket before `gateway.ready` can make chatReady true. Authentication and
|
||||
* protocol failures are terminal; ordinary reachability failures remain
|
||||
* visible so the Gateway client's bounded retry policy can recover them.
|
||||
*/
|
||||
internal fun shouldOwnVisibleGateway(
|
||||
appForeground: Boolean,
|
||||
isGatewayTransport: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
): Boolean = appForeground &&
|
||||
isGatewayTransport &&
|
||||
gatewayAvailability != GatewayAvailability.SignInRequired &&
|
||||
gatewayAvailability != GatewayAvailability.Unsupported
|
||||
|
||||
internal fun shouldPresentChatFailureDuringDashboardSignIn(
|
||||
failure: ChatFailureNotice,
|
||||
dashboardSignInRequired: Boolean,
|
||||
@@ -997,6 +1012,7 @@ fun ChatScreen(
|
||||
// of available profiles itself now lives entirely inside the sheet.
|
||||
val selectedProfile by connectionViewModel.selectedProfile.collectAsState()
|
||||
val effectiveProfile by connectionViewModel.effectiveDisplayProfile.collectAsState()
|
||||
val serverDefaultDisplayProfile by connectionViewModel.serverDefaultDisplayProfile.collectAsState()
|
||||
val profilePresentation by connectionViewModel.profilePresentation.collectAsState()
|
||||
val isProfileLocked by connectionViewModel.isProfileLocked.collectAsState()
|
||||
val lockedProfileName by connectionViewModel.lockedProfileName.collectAsState()
|
||||
@@ -1212,8 +1228,12 @@ fun ChatScreen(
|
||||
// the foreground. setChatVisible owns that edge; an ordinary Gateway open
|
||||
// warms only the observation socket and never attaches a saved session.
|
||||
val appForeground by com.hermesandroid.relay.util.AppForegroundTracker.isForeground.collectAsState()
|
||||
LaunchedEffect(isGatewayTransport, appForeground, chatReady) {
|
||||
val visibleGatewayOwner = appForeground && chatReady && isGatewayTransport
|
||||
LaunchedEffect(isGatewayTransport, appForeground, chatGatewayAvailability) {
|
||||
val visibleGatewayOwner = shouldOwnVisibleGateway(
|
||||
appForeground = appForeground,
|
||||
isGatewayTransport = isGatewayTransport,
|
||||
gatewayAvailability = chatGatewayAvailability,
|
||||
)
|
||||
chatViewModel.setChatVisible(visibleGatewayOwner)
|
||||
// updateGatewayClient owns the one-time catalog/reasoning bootstrap for
|
||||
// a newly-ready socket. Repeating it here created a duplicate cold-open
|
||||
@@ -1653,65 +1673,53 @@ fun ChatScreen(
|
||||
voiceOutputConfig?.enabled
|
||||
}
|
||||
|
||||
val voiceSystemOverlayAvailable = BuildFlavor.isSideload
|
||||
val voiceSystemOverlayAvailable = BuildFlavor.voiceSystemOverlay
|
||||
val showVoiceSystemOverlay: () -> Unit = {
|
||||
if (!voiceSystemOverlayAvailable) {
|
||||
pendingVoiceOverlayPermission = false
|
||||
} else if (assistantSessionActive) {
|
||||
voiceOverlayHost.hide()
|
||||
} else if (!voiceOverlayHost.hasOverlayPermission()) {
|
||||
if (voiceSystemOverlayAvailable && !assistantSessionActive) {
|
||||
pendingVoiceOverlayPermission = true
|
||||
runCatching {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
|
||||
context.startActivity(intent)
|
||||
}
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(
|
||||
message = context.getString(R.string.chat_overlay_perm_enable),
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
pendingVoiceOverlayPermission = false
|
||||
val shown = voiceOverlayHost.show(
|
||||
VoiceOverlaySession(
|
||||
uiState = voiceViewModel.uiState,
|
||||
engineMode = voiceStats.voiceEngineMode,
|
||||
provider = activeVoiceProvider,
|
||||
model = activeVoiceModel,
|
||||
voice = activeVoiceName,
|
||||
profileName = AgentDisplay.profileDisplayName(effectiveProfile),
|
||||
configScope = activeVoiceScope,
|
||||
outputEnabled = activeVoiceEnabled,
|
||||
fallbackEnabled = voiceOutputConfig?.fallback_enabled,
|
||||
onStartListening = { voiceViewModel.startListening() },
|
||||
onStopListening = { voiceViewModel.stopListening() },
|
||||
onInterrupt = { voiceViewModel.interruptSpeaking() },
|
||||
onPauseAutoMode = { voiceViewModel.pauseContinuousMode() },
|
||||
onReturnToHermes = {
|
||||
openHermesFromOverlay(context)
|
||||
voiceOverlayHost.hide()
|
||||
},
|
||||
onDismissOverlay = { voiceOverlayHost.hide() },
|
||||
onExit = {
|
||||
voiceOverlayHost.hide()
|
||||
voiceViewModel.exitVoiceMode()
|
||||
},
|
||||
),
|
||||
)
|
||||
if (!shown) {
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(
|
||||
message = context.getString(R.string.chat_overlay_start_failed),
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pendingVoiceOverlayPermission && voiceUiState.voiceMode && !assistantSessionActive) {
|
||||
com.hermesandroid.relay.voice.VoiceOverlaySetupDialog(
|
||||
onDismiss = { pendingVoiceOverlayPermission = false },
|
||||
onBeforePermission = { voiceViewModel.pauseContinuousMode() },
|
||||
onStart = {
|
||||
pendingVoiceOverlayPermission = false
|
||||
val shown = voiceOverlayHost.show(
|
||||
VoiceOverlaySession(
|
||||
uiState = voiceViewModel.uiState,
|
||||
engineMode = voiceStats.voiceEngineMode,
|
||||
connectionLabel = activeConnection?.label,
|
||||
provider = activeVoiceProvider,
|
||||
model = activeVoiceModel,
|
||||
voice = activeVoiceName,
|
||||
profileName = AgentDisplay.profileDisplayName(effectiveProfile),
|
||||
configScope = activeVoiceScope,
|
||||
outputEnabled = activeVoiceEnabled,
|
||||
fallbackEnabled = voiceOutputConfig?.fallback_enabled,
|
||||
onStartListening = { voiceViewModel.startListening() },
|
||||
onStopListening = { voiceViewModel.stopListening() },
|
||||
onInterrupt = { voiceViewModel.interruptSpeaking() },
|
||||
onPauseAutoMode = { voiceViewModel.pauseContinuousMode() },
|
||||
onReturnToHermes = {
|
||||
if (!openHermesFromOverlay(context)) voiceOverlayHost.exitVoiceSession()
|
||||
},
|
||||
onDismissOverlay = { voiceOverlayHost.exitVoiceSession() },
|
||||
onExit = { voiceViewModel.exitVoiceMode() },
|
||||
),
|
||||
lifecycleOwner.lifecycle,
|
||||
)
|
||||
if (!shown) {
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(
|
||||
message = context.getString(R.string.chat_overlay_start_failed),
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(voiceUiState.voiceMode) {
|
||||
if (!voiceUiState.voiceMode) {
|
||||
@@ -1727,37 +1735,6 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
DisposableEffect(
|
||||
lifecycleOwner,
|
||||
pendingVoiceOverlayPermission,
|
||||
voiceUiState.voiceMode,
|
||||
voiceOutputConfig,
|
||||
realtimeAgentConfig,
|
||||
voiceStats.voiceEngineMode,
|
||||
) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME && pendingVoiceOverlayPermission) {
|
||||
when {
|
||||
voiceOverlayHost.hasOverlayPermission() && voiceUiState.voiceMode -> {
|
||||
showVoiceSystemOverlay()
|
||||
}
|
||||
!voiceOverlayHost.hasOverlayPermission() -> {
|
||||
pendingVoiceOverlayPermission = false
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(
|
||||
message = context.getString(R.string.chat_overlay_perm_denied),
|
||||
duration = SnackbarDuration.Short,
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> pendingVoiceOverlayPermission = false
|
||||
}
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
LaunchedEffect(voiceClient, voiceUiState.voiceMode, selectedProfile?.name) {
|
||||
if (!voiceUiState.voiceMode) return@LaunchedEffect
|
||||
val client = voiceClient ?: return@LaunchedEffect
|
||||
@@ -2460,11 +2437,12 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
val selectedProfileKey = AgentDisplay.profileSessionKey(selectedProfile?.name)
|
||||
val profileShelfAvailable = !supervised && ProfilePresentationPolicy.shouldShowShelf(
|
||||
val profileShelfAvailable = !supervised && com.hermesandroid.relay.ui.components.ProfileShelfPolicy.choices(
|
||||
profiles = agentProfiles,
|
||||
presentation = profilePresentation,
|
||||
selectedKey = selectedProfileKey,
|
||||
)
|
||||
selectedProfileName = selectedProfile?.name,
|
||||
serverDefaultProfileName = serverDefaultDisplayProfile?.name,
|
||||
).size > 1
|
||||
val profileSwitchEnabled = com.hermesandroid.relay.ui.components.ProfileShelfPolicy.canSwitch(
|
||||
isStreaming = isStreaming,
|
||||
streamingEndpoint = chatViewModel.streamingEndpoint,
|
||||
@@ -3237,8 +3215,8 @@ fun ChatScreen(
|
||||
)
|
||||
}
|
||||
if (!supervised && showContextSheet) {
|
||||
// Live audit of the exact extra context the agent will be
|
||||
// injected with on the next turn (transparency / auditability).
|
||||
// Snapshot of supported client context and separately reported
|
||||
// server configuration, not a delivery receipt.
|
||||
InjectedContextSheet(
|
||||
context = remember(showContextSheet) {
|
||||
chatViewModel.previewInjectedContext()
|
||||
|
||||
@@ -4475,7 +4475,8 @@ internal fun summarizeObjectItem(
|
||||
)
|
||||
}
|
||||
|
||||
val title = obj.stringField("name")
|
||||
val title = obj.stringField("display_name")?.takeIf(String::isNotBlank)
|
||||
?: obj.stringField("name")
|
||||
?: obj.stringField("id")
|
||||
?: obj.stringField("title")
|
||||
?: fallbackTitle
|
||||
|
||||
@@ -86,6 +86,10 @@ fun PermissionsStatusScreen(
|
||||
onBack: () -> Unit,
|
||||
onOpenBridge: () -> Unit = {},
|
||||
) {
|
||||
var showVoiceOverlaySetup by remember { mutableStateOf(false) }
|
||||
if (showVoiceOverlaySetup) com.hermesandroid.relay.voice.VoiceOverlaySetupDialog(
|
||||
onDismiss = { showVoiceOverlaySetup = false },
|
||||
)
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
var status by remember { mutableStateOf(AppPermissionStatusProbe.snapshot(context)) }
|
||||
@@ -209,6 +213,21 @@ fun PermissionsStatusScreen(
|
||||
)
|
||||
}
|
||||
|
||||
PermissionSection(
|
||||
title = stringResource(R.string.voice_overlay_setup_title),
|
||||
subtitle = stringResource(R.string.voice_overlay_settings_hint),
|
||||
) {
|
||||
PermissionStatusRow(
|
||||
icon = Icons.Filled.PictureInPicture,
|
||||
title = stringResource(R.string.perms_display_over_apps),
|
||||
subtitle = stringResource(R.string.voice_overlay_setup_body),
|
||||
badge = stringResource(R.string.perms_badge_optional),
|
||||
statusLabel = optionalStatus(context, status.overlayPermitted),
|
||||
granted = status.overlayPermitted,
|
||||
onClick = { showVoiceOverlaySetup = true },
|
||||
)
|
||||
}
|
||||
|
||||
if (BuildFlavor.isSideload) {
|
||||
SideloadPermissionsSection(
|
||||
status = status,
|
||||
|
||||
@@ -1287,7 +1287,7 @@ private fun ProfileLockDialog(
|
||||
HorizontalDivider()
|
||||
// Server default option.
|
||||
ProfileLockOptionRow(
|
||||
label = stringResource(R.string.settings_server_default),
|
||||
label = stringResource(R.string.profile_follow_server_default),
|
||||
secondary = stringResource(R.string.settings_use_default_profile),
|
||||
selected = lockedIsServerDefault,
|
||||
onSelect = { onLock(null) },
|
||||
|
||||
@@ -582,6 +582,7 @@ fun VoiceSettingsScreen(
|
||||
}
|
||||
|
||||
VoiceSettingsSection.Listening -> {
|
||||
com.hermesandroid.relay.voice.VoiceOverlaySettingsCard()
|
||||
GlobalVoiceControlsCard(
|
||||
voiceSettings = voiceSettings,
|
||||
prefsRepo = prefsRepo,
|
||||
|
||||
@@ -72,6 +72,9 @@ import com.hermesandroid.relay.network.upstream.ActiveTurnKeepAliveRegistry
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAsk
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAskExpiry
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAskResponse
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyBatch
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyQuestion
|
||||
import com.hermesandroid.relay.data.clarifyQuestionCardKey
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAgentNotice
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSession
|
||||
import com.hermesandroid.relay.network.upstream.GatewayActiveSessionStatus
|
||||
@@ -2987,9 +2990,10 @@ class ChatViewModel : ViewModel() {
|
||||
_reasoningDisplay.value = null
|
||||
}
|
||||
}
|
||||
if (changed && client != null && streamRecovery != null &&
|
||||
AppForegroundTracker.isForeground.value
|
||||
) {
|
||||
// Visibility can arrive before the runtime binder publishes its client.
|
||||
// Start the same socket-only warmup in either ordering; prewarmGateway
|
||||
// retains the directory barrier and exact-checkpoint ownership rules.
|
||||
if (changed && client != null && chatVisible) {
|
||||
prewarmGateway()
|
||||
}
|
||||
if (changed && client != null) requestSessionActivityRefresh()
|
||||
@@ -3651,7 +3655,7 @@ class ChatViewModel : ViewModel() {
|
||||
private val backgroundPendingInteractions =
|
||||
ConcurrentHashMap<TurnCheckpointKey, BackgroundPendingInteraction>()
|
||||
|
||||
/** Ask cardKeys with a respond RPC in flight — blocks double-taps until it settles. */
|
||||
/** Request-incarnation/card keys with a respond RPC in flight. */
|
||||
private val answeredAskIds = mutableSetOf<String>()
|
||||
|
||||
/**
|
||||
@@ -6773,7 +6777,18 @@ class ChatViewModel : ViewModel() {
|
||||
existing.ask.kind == ask.kind &&
|
||||
existing.ask.requestId == ask.requestId
|
||||
) {
|
||||
sessionId?.let { maybeNotifyInteraction(it, existing.ask) }
|
||||
if (ask.questions.isNotEmpty()) {
|
||||
val updated = existing.copy(ask = ask.copy(answers = existing.ask.answers + ask.answers))
|
||||
_pendingAsk.value = updated
|
||||
updateClarifyBatchCard(handler, updated)
|
||||
if (updated.ask.clarifyComplete) {
|
||||
_pendingAsk.value = null
|
||||
updated.sessionId?.let { cancelInteractionNotification(it, updated.ask) }
|
||||
activeTurnCheckpointKey()?.let { ActiveTurnKeepAliveRegistry.setWaiting(it.keepAliveKey(), false) }
|
||||
}
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
}
|
||||
_pendingAsk.value?.let { pending -> sessionId?.let { maybeNotifyInteraction(it, pending.ask) } }
|
||||
return
|
||||
}
|
||||
existing?.let { pending ->
|
||||
@@ -6786,8 +6801,11 @@ class ChatViewModel : ViewModel() {
|
||||
publishBackgroundSessionActivity()
|
||||
}
|
||||
val now = restored?.receivedAt ?: System.currentTimeMillis()
|
||||
val cardKey = restored?.cardKey ?: ask.requestId
|
||||
val proposedCardKey = restored?.cardKey ?: ask.requestId
|
||||
?: "approval-${handler.currentSessionId.value ?: "session"}-$now"
|
||||
val cardKey = if (restored == null && handler.messages.value.any { message ->
|
||||
message.cards.any { it.id == proposedCardKey }
|
||||
}) "$proposedCardKey-${java.util.UUID.randomUUID()}" else proposedCardKey
|
||||
val expiresAt = ask.timeoutSeconds.takeIf { it > 0 }?.let { now + it * 1_000L }
|
||||
val card = when (ask.kind) {
|
||||
GatewayAsk.Kind.APPROVAL -> HermesCard(
|
||||
@@ -6886,12 +6904,52 @@ class ChatViewModel : ViewModel() {
|
||||
contextKey = contextKey,
|
||||
sessionId = sessionId,
|
||||
receivedAt = now,
|
||||
ownerId = restored?.ownerId ?: java.util.UUID.randomUUID().toString(),
|
||||
)
|
||||
if (ask.questions.isNotEmpty()) updateClarifyBatchCard(handler, requireNotNull(_pendingAsk.value))
|
||||
if (ask.clarifyComplete) {
|
||||
_pendingAsk.value = null
|
||||
activeKey?.let { ActiveTurnKeepAliveRegistry.setWaiting(it.keepAliveKey(), false) }
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
return
|
||||
}
|
||||
activeKey?.let { ActiveTurnKeepAliveRegistry.setWaiting(it.keepAliveKey(), true) }
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
sessionId?.let { maybeNotifyInteraction(it, ask) }
|
||||
}
|
||||
|
||||
private fun updateClarifyBatchCard(handler: ChatHandler, pending: PendingAsk) {
|
||||
val ask = pending.ask
|
||||
if (ask.questions.isEmpty()) return
|
||||
handler.updateAskCardMessage(
|
||||
pending.messageId,
|
||||
HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_CLARIFY,
|
||||
title = appContext?.getString(R.string.chat_approval_clarify_title) ?: "Hermes needs clarification",
|
||||
accent = HermesCard.Accents.INFO,
|
||||
id = pending.cardKey,
|
||||
clarifyBatch = HermesCardClarifyBatch(
|
||||
questions = ask.questions.map { question ->
|
||||
val key = clarifyQuestionCardKey(pending.cardKey, question.qid)
|
||||
HermesCardClarifyQuestion(
|
||||
key = key,
|
||||
question = question.question,
|
||||
input = HermesCardInput(
|
||||
kind = if (question.choices.isEmpty()) HermesCardInput.Kinds.TEXT else HermesCardInput.Kinds.CHOICE,
|
||||
choices = question.choices,
|
||||
multiSelect = question.multiSelect,
|
||||
allowFreeText = true,
|
||||
),
|
||||
answer = ask.answers[question.qid],
|
||||
submitting = "${pending.ownerId}:$key" in answeredAskIds,
|
||||
)
|
||||
},
|
||||
expiresAtMillis = ask.timeoutSeconds.takeIf { it > 0 }?.let { pending.receivedAt + it * 1_000L },
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Supervised Chat never exposes approval, clarification, sudo, or secret
|
||||
* inputs. Settle the upstream interaction immediately with its safest
|
||||
@@ -6965,21 +7023,35 @@ class ChatViewModel : ViewModel() {
|
||||
fun answerAsk(messageId: String, cardKey: String, value: String) {
|
||||
val handler = chatHandler ?: return
|
||||
val pending = _pendingAsk.value
|
||||
val question = pending?.ask?.questions?.firstOrNull {
|
||||
clarifyQuestionCardKey(pending.cardKey, it.qid) == cardKey
|
||||
}
|
||||
if (pending == null ||
|
||||
pending.cardKey != cardKey ||
|
||||
pending.messageId != messageId ||
|
||||
(if (pending.ask.questions.isNotEmpty()) question == null else pending.cardKey != cardKey) ||
|
||||
pending.contextKey != activeProfileContextKey ||
|
||||
pending.sessionId != handler.currentSessionId.value
|
||||
) {
|
||||
handler.addSystemNotice("This request is no longer active.")
|
||||
return
|
||||
}
|
||||
if (pending.ask.kind == GatewayAsk.Kind.CLARIFY && value.isBlank()) return
|
||||
if (pending.ask.kind == GatewayAsk.Kind.CLARIFY && pending.ask.timeoutSeconds > 0 &&
|
||||
System.currentTimeMillis() >= pending.receivedAt + pending.ask.timeoutSeconds * 1_000L
|
||||
) {
|
||||
expirePendingAsk(GatewayAskExpiry(pending.ask.kind, pending.ask.requestId))
|
||||
return
|
||||
}
|
||||
if (question != null && question.qid in pending.ask.answers) return
|
||||
val gateway = gatewayClient
|
||||
if (gateway == null) {
|
||||
emitError(Exception("Gateway is not connected"), context = "send_message")
|
||||
return
|
||||
}
|
||||
// In-flight guard: one respond RPC per card at a time.
|
||||
if (!answeredAskIds.add(cardKey)) return
|
||||
// Include the request incarnation so a late completion cannot unlock a reused id.
|
||||
val flightKey = "${pending.ownerId}:$cardKey"
|
||||
if (!answeredAskIds.add(flightKey)) return
|
||||
updateClarifyBatchCard(handler, pending)
|
||||
val ask = pending.ask
|
||||
val stampValue = when (ask.kind) {
|
||||
// Empty sudo password = decline — stamp matches the Deny action
|
||||
@@ -6991,11 +7063,19 @@ class ChatViewModel : ViewModel() {
|
||||
else -> value
|
||||
}
|
||||
viewModelScope.launch {
|
||||
fun ownsResponse(): Boolean = chatHandler === handler && gatewayClient === gateway &&
|
||||
activeProfileContextKey == pending.contextKey &&
|
||||
handler.currentSessionId.value == pending.sessionId &&
|
||||
_pendingAsk.value?.ownerId == pending.ownerId
|
||||
if (!ownsResponse()) {
|
||||
answeredAskIds.remove(flightKey)
|
||||
return@launch
|
||||
}
|
||||
val requestId = ask.requestId
|
||||
val result = when (ask.kind) {
|
||||
GatewayAsk.Kind.APPROVAL -> gateway.respondApproval(choice = value)
|
||||
GatewayAsk.Kind.CLARIFY ->
|
||||
requestId?.let { gateway.respondClarify(it, value) }
|
||||
requestId?.let { gateway.respondClarify(it, value.trim(), question?.qid) }
|
||||
?: Result.failure(GatewayRpcException("ask has no request id"))
|
||||
GatewayAsk.Kind.SUDO ->
|
||||
requestId?.let { gateway.respondSudo(it, value) }
|
||||
@@ -7006,6 +7086,8 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
answeredAskIds.remove(flightKey)
|
||||
if (!ownsResponse()) return@fold
|
||||
if (response == GatewayAskResponse.EXPIRED) {
|
||||
expirePendingAsk(
|
||||
GatewayAskExpiry(
|
||||
@@ -7015,10 +7097,24 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
return@fold
|
||||
}
|
||||
if (question != null) {
|
||||
val current = requireNotNull(_pendingAsk.value)
|
||||
val updated = current.copy(ask = current.ask.copy(answers = current.ask.answers + (question.qid to value.trim())))
|
||||
updateClarifyBatchCard(handler, updated)
|
||||
if (updated.ask.questions.all { it.qid in updated.ask.answers }) {
|
||||
updated.sessionId?.let { cancelInteractionNotification(it, updated.ask) }
|
||||
_pendingAsk.value = null
|
||||
activeTurnCheckpointKey()?.let { ActiveTurnKeepAliveRegistry.setWaiting(it.keepAliveKey(), false) }
|
||||
} else {
|
||||
_pendingAsk.value = updated
|
||||
}
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
return@fold
|
||||
}
|
||||
// Collapse only after the server confirms — a failed RPC
|
||||
// must leave the card answerable for a retry.
|
||||
handler.recordCardDispatch(pending.messageId, cardKey, stampValue)
|
||||
if (_pendingAsk.value === pending) {
|
||||
if (ownsResponse()) {
|
||||
pending.sessionId?.let { cancelInteractionNotification(it, pending.ask) }
|
||||
_pendingAsk.value = null
|
||||
activeTurnCheckpointKey()?.let {
|
||||
@@ -7028,7 +7124,9 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
},
|
||||
onFailure = { e ->
|
||||
answeredAskIds.remove(cardKey)
|
||||
answeredAskIds.remove(flightKey)
|
||||
if (!ownsResponse()) return@fold
|
||||
updateClarifyBatchCard(handler, requireNotNull(_pendingAsk.value))
|
||||
emitError(e, context = "send_message")
|
||||
},
|
||||
)
|
||||
@@ -7053,7 +7151,6 @@ class ChatViewModel : ViewModel() {
|
||||
activeTurnCheckpointKey()?.let {
|
||||
ActiveTurnKeepAliveRegistry.setWaiting(it.keepAliveKey(), false)
|
||||
}
|
||||
answeredAskIds.remove(pending.cardKey)
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
chatHandler?.recordCardDispatch(
|
||||
pending.messageId,
|
||||
@@ -7076,7 +7173,9 @@ class ChatViewModel : ViewModel() {
|
||||
ActiveTurnKeepAliveRegistry.setWaiting(it.keepAliveKey(), false)
|
||||
}
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
if (pending.ask.kind == GatewayAsk.Kind.APPROVAL) {
|
||||
if (pending.ask.kind == GatewayAsk.Kind.CLARIFY) {
|
||||
chatHandler?.recordCardDispatch(pending.messageId, pending.cardKey, HermesCardDispatch.EXPIRED_STAMP)
|
||||
} else if (pending.ask.kind == GatewayAsk.Kind.APPROVAL) {
|
||||
chatHandler?.recordCardDispatch(pending.messageId, pending.cardKey, "deny")
|
||||
}
|
||||
}
|
||||
@@ -7684,6 +7783,9 @@ class ChatViewModel : ViewModel() {
|
||||
text = ask.ask.text,
|
||||
choices = ask.ask.choices,
|
||||
multiSelect = ask.ask.multiSelect,
|
||||
questions = ask.ask.questions,
|
||||
answers = ask.ask.answers,
|
||||
ownerId = ask.ownerId,
|
||||
smartDenied = ask.ask.smartDenied,
|
||||
envVar = ask.ask.envVar,
|
||||
timeoutSeconds = ask.ask.timeoutSeconds,
|
||||
@@ -7892,6 +7994,8 @@ class ChatViewModel : ViewModel() {
|
||||
text = saved.text,
|
||||
choices = saved.choices,
|
||||
multiSelect = saved.multiSelect,
|
||||
questions = saved.questions,
|
||||
answers = saved.answers,
|
||||
smartDenied = saved.smartDenied,
|
||||
envVar = saved.envVar,
|
||||
timeoutSeconds = saved.timeoutSeconds,
|
||||
@@ -9666,8 +9770,8 @@ class ChatViewModel : ViewModel() {
|
||||
* 0. **Gateway transport** — the server owns the persona end-to-end: the
|
||||
* session is bound to the selected profile (SOUL applied server-side) and
|
||||
* the personality overlay rides `config.set`/`ephemeral_system_prompt`.
|
||||
* The phone sends NO persona/profile prompt (only the phone-status block)
|
||||
* so it can't double-apply. Cases 1–3 are the SSE-fallback rules.
|
||||
* The phone sends no per-turn system context on Gateway.
|
||||
* Cases 1–3 are the explicit API-only transport rules.
|
||||
* 1. **Selected profile with a non-blank [Profile.systemMessage]** —
|
||||
* profile wins outright. Profile is a richer, newer concept than
|
||||
* personality: it bundles model + persona (from the profile's
|
||||
@@ -9682,15 +9786,12 @@ class ChatViewModel : ViewModel() {
|
||||
* configured default.
|
||||
*
|
||||
* The phone-status [appContextSettings] block is appended to whichever
|
||||
* of the above wins (or sent alone in case 3), so the LLM always sees
|
||||
* phone state regardless of persona source.
|
||||
* of the API-only cases above wins (or sent alone in case 3).
|
||||
*/
|
||||
/**
|
||||
* The exact `system_message` (`ephemeral_system_prompt`) injected for a
|
||||
* turn, split into labeled blocks. Single source of truth shared by
|
||||
* [startStream] (which sends [combinedSystemMessage]) and
|
||||
* [previewInjectedContext] (which renders it in the chat audit sheet) so
|
||||
* the preview can never drift from what is actually sent.
|
||||
* Context prepared for the selected transport, split into labeled blocks.
|
||||
* This is a preview, not a delivery receipt or the complete agent prompt.
|
||||
* Gateway has no general per-turn system-context slot.
|
||||
*/
|
||||
data class InjectedContext(
|
||||
val personaPrompt: String?,
|
||||
@@ -9721,6 +9822,8 @@ class ChatViewModel : ViewModel() {
|
||||
* audit UI labels that block "added server-side".
|
||||
*/
|
||||
val personaOwnedServerSide: Boolean,
|
||||
/** False on Gateway; unsupported blocks are excluded from the payload and preview. */
|
||||
val perTurnContextSupported: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -9756,11 +9859,14 @@ class ChatViewModel : ViewModel() {
|
||||
} else {
|
||||
_sseToolNames.value
|
||||
}
|
||||
val appContextRaw = buildPromptBlock(
|
||||
settings = appContextSettings,
|
||||
snapshot = capturePhoneSnapshot(),
|
||||
availableTools = availableTools,
|
||||
)
|
||||
val appContextRaw = if (!gateway && appContextSettings.master) {
|
||||
buildPromptBlock(
|
||||
settings = appContextSettings,
|
||||
snapshot = capturePhoneSnapshot(),
|
||||
availableTools = availableTools,
|
||||
)
|
||||
} else null
|
||||
val interfaceContext = interfaceContextPrompt?.takeIf { !gateway && it.isNotBlank() }
|
||||
// Gateway has no per-turn system slot. SSE carries the standard
|
||||
// Dashboard route first, then the optional Relay enhancement.
|
||||
val upstreamMediaAvailable = dashboardMediaClientProvider?.invoke() != null
|
||||
@@ -9772,25 +9878,26 @@ class ChatViewModel : ViewModel() {
|
||||
// block (a stable environment fact, like phone status) and before the
|
||||
// per-turn interface context. The per-block fields below null out blanks
|
||||
// only for display.
|
||||
val combined = listOfNotNull(personaPrompt, appContextRaw, mediaCapability, interfaceContextPrompt)
|
||||
val combined = listOfNotNull(personaPrompt, appContextRaw, mediaCapability, interfaceContext)
|
||||
.joinToString("\n\n")
|
||||
.ifBlank { null }
|
||||
return InjectedContext(
|
||||
personaPrompt = personaPrompt,
|
||||
appContext = appContextRaw?.takeIf { it.isNotBlank() },
|
||||
interfaceContext = interfaceContextPrompt?.takeIf { it.isNotBlank() },
|
||||
interfaceContext = interfaceContext,
|
||||
mediaCapability = mediaCapability,
|
||||
relayServerBlocks = relayServerBlocks,
|
||||
relayMediaAvailable = relayMediaAvailable,
|
||||
combinedSystemMessage = combined,
|
||||
transport = streamingEndpoint,
|
||||
personaOwnedServerSide = gateway,
|
||||
perTurnContextSupported = !gateway,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Live audit snapshot of what the agent will be injected with on the next
|
||||
* turn — rendered by the chat context sheet. Per-turn voice context is null
|
||||
* Preview of context supported by the selected transport, plus separately
|
||||
* reported Relay configuration. Per-turn voice context is null
|
||||
* here (it's set only on a spoken turn); the UI notes that.
|
||||
*/
|
||||
fun previewInjectedContext(): InjectedContext {
|
||||
@@ -11842,6 +11949,7 @@ data class PendingAsk(
|
||||
/** Stored session id within [contextKey]; approvals are session-scoped upstream. */
|
||||
val sessionId: String?,
|
||||
val receivedAt: Long = System.currentTimeMillis(),
|
||||
val ownerId: String = java.util.UUID.randomUUID().toString(),
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -2357,6 +2357,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
get() = profileController.effectiveSessionProfileName
|
||||
val effectiveDisplayProfile: StateFlow<Profile?>
|
||||
get() = profileController.effectiveDisplayProfile
|
||||
val serverDefaultDisplayProfile: StateFlow<Profile?>
|
||||
get() = profileController.serverDefaultDisplayProfile
|
||||
|
||||
fun refreshDashboardProfiles() = profileController.refreshDashboardProfiles()
|
||||
fun refreshDeferredProfileMetadata() = profileController.refreshDeferredProfileMetadata()
|
||||
|
||||
@@ -193,6 +193,13 @@ class ProfileController(
|
||||
private val _serverDefaultProfileScope = MutableStateFlow<DashboardProfileScope?>(null)
|
||||
val serverDefaultProfileScope: StateFlow<DashboardProfileScope?> =
|
||||
_serverDefaultProfileScope.asStateFlow()
|
||||
/** Default identity independent of the explicit selection; never a routing override. */
|
||||
val serverDefaultDisplayProfile: StateFlow<Profile?> = combine(
|
||||
agentProfiles,
|
||||
serverDefaultProfileScope,
|
||||
) { profiles, serverDefault ->
|
||||
AgentDisplay.effectiveDisplayProfile(null, profiles, serverDefault?.active)
|
||||
}.stateIn(scope, SharingStarted.Eagerly, null)
|
||||
private val _serverDefaultProfileSettled = MutableStateFlow(false)
|
||||
|
||||
private fun pendingProfileNameForActiveConnection(): String? {
|
||||
@@ -361,12 +368,8 @@ class ProfileController(
|
||||
activeConnectionId,
|
||||
selectedProfile,
|
||||
serverDefaultProfileScope,
|
||||
_gatewayProfiles,
|
||||
) { connectionId, selected, serverDefault, gatewayProfiles ->
|
||||
connectionId to (
|
||||
selected?.name ?: serverDefault?.active
|
||||
?: gatewayProfiles.firstOrNull(Profile::isDefault)?.name
|
||||
)
|
||||
) { connectionId, selected, serverDefault ->
|
||||
connectionId to (selected?.name ?: serverDefault?.active)
|
||||
}
|
||||
|
||||
/** Cached bytes fetched from Hermes; always preferred over the local fallback. */
|
||||
@@ -398,12 +401,8 @@ class ProfileController(
|
||||
fun profileIconFlow(profileName: String?): Flow<String?> = combine(
|
||||
activeConnectionId,
|
||||
serverDefaultProfileScope,
|
||||
_gatewayProfiles,
|
||||
) { connectionId, serverDefault, gatewayProfiles ->
|
||||
connectionId to (
|
||||
profileName ?: serverDefault?.active
|
||||
?: gatewayProfiles.firstOrNull(Profile::isDefault)?.name
|
||||
)
|
||||
) { connectionId, serverDefault ->
|
||||
connectionId to (profileName ?: serverDefault?.active)
|
||||
}
|
||||
.flatMapLatest { (connectionId, serverProfileName) ->
|
||||
if (connectionId == null) return@flatMapLatest flowOf(null)
|
||||
@@ -1282,7 +1281,6 @@ class ProfileController(
|
||||
|
||||
private fun resolveSharedAssetProfileName(): String? =
|
||||
resolveSessionProfileName()
|
||||
?: _gatewayProfiles.value.firstOrNull(Profile::isDefault)?.name
|
||||
|
||||
private companion object {
|
||||
const val LOCAL_PROFILE_ICON_MAX_BYTES = 8_000_000
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.hermesandroid.relay.voice
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
/** Permissions do not grant permission to start a session: a resumed UI action is also required. */
|
||||
data class VoiceOverlayAccess(
|
||||
val microphone: Boolean,
|
||||
val notifications: Boolean,
|
||||
val overlay: Boolean,
|
||||
val unlocked: Boolean,
|
||||
) {
|
||||
val ready: Boolean get() = microphone && notifications && overlay && unlocked
|
||||
|
||||
companion object {
|
||||
fun read(context: Context): VoiceOverlayAccess {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
val channelEnabled = Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
|
||||
manager?.getNotificationChannel(VoiceOverlayForegroundService.CHANNEL_ID)?.importance !=
|
||||
NotificationManager.IMPORTANCE_NONE
|
||||
return VoiceOverlayAccess(
|
||||
microphone = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==
|
||||
PackageManager.PERMISSION_GRANTED,
|
||||
notifications = NotificationManagerCompat.from(context).areNotificationsEnabled() && channelEnabled,
|
||||
overlay = Settings.canDrawOverlays(context),
|
||||
unlocked = context.getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == false &&
|
||||
context.getSystemService(PowerManager::class.java)?.isInteractive == true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,13 @@ import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
@@ -27,31 +31,84 @@ import com.hermesandroid.relay.R
|
||||
* execution state Android requires once [MainActivity] is backgrounded.
|
||||
*/
|
||||
class VoiceOverlayForegroundService : Service() {
|
||||
private var activeSessionId: Long? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val accessMonitor = object : Runnable {
|
||||
override fun run() {
|
||||
val id = activeSessionId ?: return
|
||||
if (VoiceOverlayHost.peek()?.canContinue(id) != true) {
|
||||
endSession()
|
||||
} else {
|
||||
// Notification channels can be disabled without a runtime-permission event.
|
||||
handler.postDelayed(this, 1_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
private val screenOffReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
if (intent?.action == Intent.ACTION_SCREEN_OFF) endSession()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
ContextCompat.registerReceiver(this, screenOffReceiver, IntentFilter(Intent.ACTION_SCREEN_OFF),
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
startForegroundNotification()
|
||||
val id = intent?.getLongExtra(EXTRA_SESSION_ID, -1L) ?: -1L
|
||||
val host = VoiceOverlayHost.peek()
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
Log.i(TAG, "Notification stop requested")
|
||||
VoiceOverlayHost.peek()?.exitVoiceSession()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
if (id == activeSessionId) endSession()
|
||||
else if (activeSessionId == null && host?.sessionId == null) stopSelfResult(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
// No sticky restart, unowned Intent, or stale callback can start a microphone session.
|
||||
if (intent?.action != ACTION_START || host?.canStart(id) != true) {
|
||||
if (host?.sessionId == id) host.exitVoiceSession(id)
|
||||
if (activeSessionId == null) stopSelfResult(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
activeSessionId = id
|
||||
if (!startForegroundNotification() || !host.onServiceReady(id)) {
|
||||
endSession()
|
||||
} else {
|
||||
handler.removeCallbacks(accessMonitor)
|
||||
handler.post(accessMonitor)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
super.onTaskRemoved(rootIntent)
|
||||
Log.i(TAG, "App task removed; closing voice overlay")
|
||||
VoiceOverlayHost.peek()?.exitVoiceSession()
|
||||
endSession()
|
||||
}
|
||||
|
||||
private fun endSession() {
|
||||
val id = activeSessionId
|
||||
activeSessionId = null
|
||||
handler.removeCallbacks(accessMonitor)
|
||||
if (id != null) VoiceOverlayHost.peek()?.exitVoiceSession(id)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
val id = activeSessionId
|
||||
activeSessionId = null
|
||||
handler.removeCallbacks(accessMonitor)
|
||||
unregisterReceiver(screenOffReceiver)
|
||||
if (id != null) VoiceOverlayHost.peek()?.exitVoiceSession(id)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@SuppressLint("ForegroundServiceType")
|
||||
private fun startForegroundNotification() {
|
||||
ensureChannel()
|
||||
private fun startForegroundNotification(): Boolean {
|
||||
try {
|
||||
ensureChannel()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
@@ -63,9 +120,9 @@ class VoiceOverlayForegroundService : Service() {
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "Could not foreground voice overlay microphone service", t)
|
||||
VoiceOverlayHost.peek()?.hide()
|
||||
stopSelf()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
@@ -76,8 +133,10 @@ class VoiceOverlayForegroundService : Service() {
|
||||
val openPending = PendingIntent.getActivity(this, 0, openIntent, pendingFlags)
|
||||
val stopPending = PendingIntent.getService(
|
||||
this,
|
||||
1,
|
||||
Intent(this, VoiceOverlayForegroundService::class.java).setAction(ACTION_STOP),
|
||||
activeSessionId?.toInt() ?: 0,
|
||||
Intent(this, VoiceOverlayForegroundService::class.java).setAction(ACTION_STOP)
|
||||
.setData(android.net.Uri.parse("hermes-voice-overlay:stop/$activeSessionId"))
|
||||
.putExtra(EXTRA_SESSION_ID, activeSessionId ?: -1L),
|
||||
pendingFlags,
|
||||
)
|
||||
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
@@ -93,6 +152,7 @@ class VoiceOverlayForegroundService : Service() {
|
||||
.setOnlyAlertOnce(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
.addAction(
|
||||
0,
|
||||
getString(R.string.voice_overlay_notification_stop),
|
||||
@@ -123,14 +183,15 @@ class VoiceOverlayForegroundService : Service() {
|
||||
const val NOTIFICATION_ID = 4715
|
||||
const val ACTION_START = "com.hermesandroid.relay.voice.OVERLAY_MIC_START"
|
||||
const val ACTION_STOP = "com.hermesandroid.relay.voice.OVERLAY_MIC_STOP"
|
||||
const val EXTRA_SESSION_ID = "voice_overlay_session_id"
|
||||
|
||||
fun start(context: Context): Boolean {
|
||||
fun start(context: Context, sessionId: Long): Boolean {
|
||||
val appContext = context.applicationContext
|
||||
return runCatching {
|
||||
ContextCompat.startForegroundService(
|
||||
appContext,
|
||||
Intent(appContext, VoiceOverlayForegroundService::class.java)
|
||||
.setAction(ACTION_START),
|
||||
.setAction(ACTION_START).putExtra(EXTRA_SESSION_ID, sessionId),
|
||||
)
|
||||
true
|
||||
}.getOrElse { error ->
|
||||
|
||||
@@ -22,6 +22,8 @@ import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -31,6 +33,7 @@ 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.width
|
||||
@@ -81,6 +84,7 @@ import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.lifecycle.ViewModelStore
|
||||
import androidx.lifecycle.ViewModelStoreOwner
|
||||
@@ -153,21 +157,78 @@ class VoiceOverlayHost(context: Context) {
|
||||
private var overlayView: View? = null
|
||||
private var overlayOwner: VoiceOverlayLifecycleOwner? = null
|
||||
private var overlayParams: WindowManager.LayoutParams? = null
|
||||
private var generation = android.os.SystemClock.elapsedRealtimeNanos()
|
||||
internal var sessionId: Long? = null
|
||||
private set
|
||||
private var callerLifecycle: Lifecycle? = null
|
||||
private val callerObserver = LifecycleEventObserver { _, event ->
|
||||
when (event) {
|
||||
// Keep microphone protection until the real Activity is foreground again.
|
||||
Lifecycle.Event.ON_RESUME -> if (overlayView != null) handoffToApp()
|
||||
Lifecycle.Event.ON_DESTROY -> exitVoiceSession()
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
fun hasOverlayPermission(): Boolean = Settings.canDrawOverlays(appContext)
|
||||
|
||||
fun show(session: VoiceOverlaySession, lifecycle: Lifecycle): Boolean {
|
||||
if (!com.hermesandroid.relay.data.BuildFlavor.voiceSystemOverlay ||
|
||||
!lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) ||
|
||||
!VoiceOverlayAccess.read(appContext).ready || !session.uiState.value.voiceMode
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (sessionId != null) return true
|
||||
val id = ++generation
|
||||
sessionId = id
|
||||
fun guarded(action: () -> Unit): () -> Unit = {
|
||||
if (canContinue(id)) action() else exitVoiceSession(id)
|
||||
}
|
||||
sessionState.value = session.copy(
|
||||
onStartListening = guarded(session.onStartListening),
|
||||
onStopListening = guarded(session.onStopListening),
|
||||
onInterrupt = guarded(session.onInterrupt),
|
||||
onPauseAutoMode = guarded(session.onPauseAutoMode),
|
||||
onReturnToHermes = guarded {
|
||||
session.onReturnToHermes()
|
||||
// Already foreground: no lifecycle transition is needed for a safe handoff.
|
||||
if (sessionId == id &&
|
||||
callerLifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) == true
|
||||
) handoffToApp()
|
||||
},
|
||||
onExit = { exitVoiceSession(id) },
|
||||
onDismissOverlay = { exitVoiceSession(id) },
|
||||
onResetPosition = guarded { moveTo(24, 96) },
|
||||
)
|
||||
exitCallback = session.onExit
|
||||
callerLifecycle = lifecycle
|
||||
lifecycle.addObserver(callerObserver)
|
||||
if (!VoiceOverlayForegroundService.start(appContext, id)) {
|
||||
exitVoiceSession(id)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private var exitCallback: (() -> Unit)? = null
|
||||
|
||||
private fun handoffToApp() {
|
||||
val id = sessionId ?: return
|
||||
// A fast return from Android Settings must not bypass revocation teardown.
|
||||
if (canContinue(id)) hide() else exitVoiceSession(id)
|
||||
}
|
||||
|
||||
internal fun canStart(id: Long): Boolean = sessionId == id &&
|
||||
callerLifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) == true && canContinue(id)
|
||||
|
||||
internal fun canContinue(id: Long): Boolean = sessionId == id &&
|
||||
sessionState.value?.uiState?.value?.voiceMode == true && VoiceOverlayAccess.read(appContext).ready
|
||||
|
||||
/** Called only after startForeground succeeds; a queued service start is not readiness. */
|
||||
@SuppressLint("InflateParams")
|
||||
fun show(session: VoiceOverlaySession): Boolean {
|
||||
sessionState.value = session
|
||||
if (!hasOverlayPermission()) {
|
||||
Log.w(TAG, "show: SYSTEM_ALERT_WINDOW not granted")
|
||||
return false
|
||||
}
|
||||
if (!VoiceOverlayForegroundService.start(appContext)) {
|
||||
Log.w(TAG, "show: microphone foreground service could not start")
|
||||
sessionState.value = null
|
||||
return false
|
||||
}
|
||||
internal fun onServiceReady(id: Long): Boolean {
|
||||
if (!canStart(id)) return false
|
||||
if (overlayView != null) return true
|
||||
|
||||
val compose = ComposeView(appContext).apply {
|
||||
@@ -191,9 +252,7 @@ class VoiceOverlayHost(context: Context) {
|
||||
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
overlayType(),
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
|
||||
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
|
||||
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
|
||||
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
|
||||
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
|
||||
PixelFormat.TRANSLUCENT,
|
||||
).apply {
|
||||
gravity = Gravity.TOP or Gravity.START
|
||||
@@ -205,8 +264,6 @@ class VoiceOverlayHost(context: Context) {
|
||||
.onFailure { Log.w(TAG, "addView(voice overlay) failed", it) }
|
||||
.isSuccess
|
||||
if (!added) {
|
||||
sessionState.value = null
|
||||
VoiceOverlayForegroundService.stop(appContext)
|
||||
overlayOwner?.stop()
|
||||
overlayOwner = null
|
||||
return false
|
||||
@@ -214,10 +271,17 @@ class VoiceOverlayHost(context: Context) {
|
||||
|
||||
overlayView = compose
|
||||
overlayParams = params
|
||||
compose.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
|
||||
moveTo(params.x, params.y)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun hide() {
|
||||
sessionId = null
|
||||
exitCallback = null
|
||||
callerLifecycle?.removeObserver(callerObserver)
|
||||
callerLifecycle = null
|
||||
val view = overlayView
|
||||
overlayView = null
|
||||
overlayParams = null
|
||||
@@ -231,17 +295,29 @@ class VoiceOverlayHost(context: Context) {
|
||||
VoiceOverlayForegroundService.stop(appContext)
|
||||
}
|
||||
|
||||
fun exitVoiceSession() {
|
||||
val onExit = sessionState.value?.onExit
|
||||
fun exitVoiceSession(expectedId: Long? = sessionId) {
|
||||
if (expectedId == null || sessionId != expectedId) return
|
||||
val onExit = exitCallback
|
||||
hide()
|
||||
onExit?.invoke()
|
||||
}
|
||||
|
||||
private fun moveBy(dx: Float, dy: Float) {
|
||||
val params = overlayParams ?: return
|
||||
moveTo(params.x + dx.roundToInt(), params.y + dy.roundToInt())
|
||||
}
|
||||
|
||||
private fun moveTo(x: Int, y: Int) {
|
||||
val view = overlayView ?: return
|
||||
val params = overlayParams ?: return
|
||||
params.x = (params.x + dx.roundToInt()).coerceAtLeast(0)
|
||||
params.y = (params.y + dy.roundToInt()).coerceAtLeast(0)
|
||||
val size = android.graphics.Point()
|
||||
@Suppress("DEPRECATION")
|
||||
wm.defaultDisplay.getSize(size)
|
||||
val nextX = x.coerceIn(0, (size.x - view.width).coerceAtLeast(0))
|
||||
val nextY = y.coerceIn(0, (size.y - view.height).coerceAtLeast(0))
|
||||
if (params.x == nextX && params.y == nextY) return
|
||||
params.x = nextX
|
||||
params.y = nextY
|
||||
runCatching { wm.updateViewLayout(view, params) }
|
||||
.onFailure { Log.w(TAG, "updateViewLayout(voice overlay) failed", it) }
|
||||
}
|
||||
@@ -280,10 +356,12 @@ data class VoiceOverlaySession(
|
||||
val onReturnToHermes: () -> Unit,
|
||||
val onDismissOverlay: () -> Unit,
|
||||
val onExit: () -> Unit,
|
||||
val onResetPosition: () -> Unit = {},
|
||||
val connectionLabel: String? = null,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun VoiceFloatingOverlayPill(
|
||||
internal fun VoiceFloatingOverlayPill(
|
||||
session: VoiceOverlaySession,
|
||||
onDragBy: (Float, Float) -> Unit,
|
||||
) {
|
||||
@@ -301,20 +379,31 @@ private fun VoiceFloatingOverlayPill(
|
||||
?: stringResource(R.string.voice_overlay_label_default_profile)
|
||||
val stateText = voiceOverlayStateLabel(uiState.state)
|
||||
val overlayWidth = (LocalConfiguration.current.screenWidthDp - 24)
|
||||
.coerceIn(280, 368)
|
||||
.coerceIn(200, 368)
|
||||
.dp
|
||||
|
||||
if (minimized) {
|
||||
VoiceFloatingOverlayBubble(
|
||||
uiState = uiState,
|
||||
stateText = stateText,
|
||||
onExpand = { minimized = false },
|
||||
onStartListening = session.onStartListening,
|
||||
onStopListening = session.onStopListening,
|
||||
onInterrupt = session.onInterrupt,
|
||||
onPauseAutoMode = session.onPauseAutoMode,
|
||||
onDragBy = onDragBy,
|
||||
)
|
||||
Surface(
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
VoiceFloatingOverlayBubble(
|
||||
uiState = uiState,
|
||||
stateText = stateText,
|
||||
onExpand = { minimized = false },
|
||||
onStartListening = session.onStartListening,
|
||||
onStopListening = session.onStopListening,
|
||||
onInterrupt = session.onInterrupt,
|
||||
onPauseAutoMode = session.onPauseAutoMode,
|
||||
onDragBy = onDragBy,
|
||||
)
|
||||
TextButton(onClick = session.onExit) {
|
||||
Text(stringResource(R.string.voice_overlay_notification_stop))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -329,6 +418,7 @@ private fun VoiceFloatingOverlayPill(
|
||||
},
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh.copy(alpha = 0.98f),
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp,
|
||||
shadowElevation = 10.dp,
|
||||
) {
|
||||
@@ -382,7 +472,9 @@ private fun VoiceOverlayHeader(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Box(modifier = Modifier.size(50.dp), contentAlignment = Alignment.Center) {
|
||||
if (LocalConfiguration.current.screenWidthDp >= 360) Box(
|
||||
modifier = Modifier.size(50.dp), contentAlignment = Alignment.Center,
|
||||
) {
|
||||
OverlayCircularWaveformRing(
|
||||
amplitude = uiState.amplitude,
|
||||
state = uiState.state,
|
||||
@@ -396,21 +488,28 @@ private fun VoiceOverlayHeader(
|
||||
)
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = listOfNotNull(session.connectionLabel, session.profileName).joinToString(" · "),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = stateText,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
text = overlayPrimaryText(uiState, stateText),
|
||||
val primaryText = overlayPrimaryText(uiState, stateText)
|
||||
if (primaryText != stateText) Text(
|
||||
text = primaryText,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onToggleExpanded, modifier = Modifier.size(38.dp)) {
|
||||
IconButton(onClick = onToggleExpanded, modifier = Modifier.size(48.dp)) {
|
||||
Icon(
|
||||
imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
|
||||
contentDescription = stringResource(
|
||||
@@ -426,6 +525,9 @@ private fun VoiceOverlayHeader(
|
||||
onPauseAutoMode = session.onPauseAutoMode,
|
||||
size = 50.dp,
|
||||
)
|
||||
IconButton(onClick = session.onExit, modifier = Modifier.size(48.dp)) {
|
||||
Icon(Icons.Filled.Close, stringResource(R.string.voice_overlay_notification_stop))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,7 +541,10 @@ private fun ExpandedVoiceOverlayBody(
|
||||
session: VoiceOverlaySession,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
modifier = Modifier
|
||||
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 120).coerceAtLeast(100).dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(bottom = 8.dp),
|
||||
) {
|
||||
OverlayLinearWaveform(
|
||||
amplitude = uiState.amplitude,
|
||||
@@ -502,31 +607,36 @@ private fun ExpandedVoiceOverlayBody(
|
||||
}
|
||||
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.62f))
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val actions: @Composable (Modifier) -> Unit = { actionModifier ->
|
||||
VoiceOverlayAction(
|
||||
icon = Icons.Filled.ExpandMore,
|
||||
label = stringResource(R.string.voice_overlay_minimize),
|
||||
onClick = onMinimize,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = actionModifier,
|
||||
)
|
||||
VoiceOverlayAction(
|
||||
icon = Icons.Filled.VisibilityOff,
|
||||
label = stringResource(R.string.voice_overlay_hide),
|
||||
onClick = session.onDismissOverlay,
|
||||
modifier = Modifier.weight(1f),
|
||||
icon = Icons.Filled.GraphicEq,
|
||||
label = stringResource(R.string.voice_overlay_reset_position),
|
||||
onClick = session.onResetPosition,
|
||||
modifier = actionModifier,
|
||||
)
|
||||
VoiceOverlayAction(
|
||||
icon = Icons.AutoMirrored.Filled.OpenInNew,
|
||||
label = stringResource(R.string.voice_overlay_open_hermes),
|
||||
onClick = session.onReturnToHermes,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = actionModifier,
|
||||
)
|
||||
}
|
||||
val actionContainer = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 2.dp)
|
||||
val stackActions = androidx.compose.ui.platform.LocalDensity.current.fontScale > 1.2f &&
|
||||
LocalConfiguration.current.screenWidthDp < 360
|
||||
if (stackActions) {
|
||||
Column(modifier = actionContainer) { actions(Modifier.fillMaxWidth()) }
|
||||
} else {
|
||||
Row(modifier = actionContainer, verticalAlignment = Alignment.CenterVertically) {
|
||||
actions(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -570,7 +680,7 @@ private fun VoiceOverlayAction(
|
||||
) {
|
||||
TextButton(
|
||||
onClick = onClick,
|
||||
modifier = modifier.height(54.dp),
|
||||
modifier = modifier.heightIn(min = 72.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
@@ -584,7 +694,7 @@ private fun VoiceOverlayAction(
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
@@ -1049,7 +1159,7 @@ private fun voiceEngineLabel(engineMode: String?): String = when (engineMode) {
|
||||
.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
|
||||
}
|
||||
|
||||
fun openHermesFromOverlay(context: Context) {
|
||||
fun openHermesFromOverlay(context: Context): Boolean {
|
||||
val appContext = context.applicationContext
|
||||
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
|
||||
?: Intent().setPackage(appContext.packageName)
|
||||
@@ -1057,8 +1167,9 @@ fun openHermesFromOverlay(context: Context) {
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
runCatching { appContext.startActivity(launchIntent) }
|
||||
return runCatching { appContext.startActivity(launchIntent) }
|
||||
.onFailure { Log.w("VoiceOverlayHost", "return to Hermes failed", it) }
|
||||
.isSuccess
|
||||
}
|
||||
|
||||
private class VoiceOverlayLifecycleOwner :
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.hermesandroid.relay.voice
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import com.hermesandroid.relay.R
|
||||
|
||||
/** Settings and Voice Focus share the explanation; only Voice Focus supplies a start action. */
|
||||
@Composable
|
||||
fun VoiceOverlaySetupDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onStart: (() -> Unit)? = null,
|
||||
onBeforePermission: () -> Unit = {},
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
var access by remember { mutableStateOf(VoiceOverlayAccess.read(context)) }
|
||||
var requestedMicrophone by remember { mutableStateOf(false) }
|
||||
var requestedNotifications by remember { mutableStateOf(false) }
|
||||
var failed by remember { mutableStateOf(false) }
|
||||
val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
access = VoiceOverlayAccess.read(context)
|
||||
}
|
||||
DisposableEffect(lifecycle) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) access = VoiceOverlayAccess.read(context)
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
fun open(intent: Intent) {
|
||||
onBeforePermission()
|
||||
failed = runCatching { context.startActivity(intent) }.isFailure
|
||||
}
|
||||
VoiceOverlaySetupContent(
|
||||
access = access,
|
||||
failed = failed,
|
||||
onDismiss = onDismiss,
|
||||
onStart = onStart?.let { start -> {
|
||||
access = VoiceOverlayAccess.read(context)
|
||||
if (access.ready && lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) start()
|
||||
} },
|
||||
onMicrophone = {
|
||||
if (access.microphone || requestedMicrophone) {
|
||||
open(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))
|
||||
} else {
|
||||
onBeforePermission()
|
||||
requestedMicrophone = true
|
||||
permission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
},
|
||||
onNotifications = {
|
||||
if (Build.VERSION.SDK_INT >= 33 && !requestedNotifications &&
|
||||
androidx.core.content.ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
onBeforePermission()
|
||||
requestedNotifications = true
|
||||
permission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
open(Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName))
|
||||
}
|
||||
},
|
||||
onOverlay = {
|
||||
open(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun VoiceOverlaySetupContent(
|
||||
access: VoiceOverlayAccess,
|
||||
failed: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onStart: (() -> Unit)?,
|
||||
onMicrophone: () -> Unit,
|
||||
onNotifications: () -> Unit,
|
||||
onOverlay: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.voice_overlay_setup_title)) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.voice_overlay_setup_body))
|
||||
AccessButton(R.string.perms_microphone, access.microphone, onMicrophone)
|
||||
AccessButton(R.string.perms_app_notifications, access.notifications, onNotifications)
|
||||
AccessButton(R.string.perms_display_over_apps, access.overlay, onOverlay)
|
||||
if (onStart == null) Text(stringResource(R.string.voice_overlay_settings_hint))
|
||||
if (failed) Text(stringResource(R.string.chat_overlay_start_failed), color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
if (onStart != null) TextButton(onClick = onStart, enabled = access.ready) {
|
||||
Text(stringResource(R.string.voice_overlay_setup_start))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cw_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccessButton(@androidx.annotation.StringRes label: Int, granted: Boolean, onClick: () -> Unit) {
|
||||
TextButton(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(label) + " · " + stringResource(
|
||||
if (granted) R.string.ncs_access_granted else R.string.chat_open_settings,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun VoiceOverlaySettingsCard() {
|
||||
var show by remember { mutableStateOf(false) }
|
||||
Card {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.voice_overlay_setup_title), style = MaterialTheme.typography.titleMedium)
|
||||
Text(stringResource(R.string.voice_overlay_settings_hint))
|
||||
TextButton(onClick = { show = true }) { Text(stringResource(R.string.onboarding_review_optional_permissions)) }
|
||||
}
|
||||
}
|
||||
if (show) VoiceOverlaySetupDialog(onDismiss = { show = false })
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">Pergunta %1$d de %2$d</string>
|
||||
<string name="clarify_batch_complete">Todas as perguntas respondidas</string>
|
||||
<string name="clarify_batch_expired">Esta solicitação terminou</string>
|
||||
<string name="clarify_batch_sending">Enviando resposta…</string>
|
||||
<string name="clarify_batch_answered">Perguntas respondidas (%1$d)</string>
|
||||
<string name="app_name">Hermes-Relay</string>
|
||||
<string name="app_title">Hermes-Relay</string>
|
||||
<string name="agent_interface">interface do agente</string>
|
||||
@@ -757,7 +762,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">Alertas de chat em segundo plano</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Notifique quando o Hermes precisar de uma resposta ou terminar em segundo plano</string>
|
||||
<string name="chat_settings_share_phone_status">Compartilhar o status do celular com o agente</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Inclua uma breve mensagem do sistema sobre o app e o celular em cada turno do chat</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Incluir contexto do app e do telefone em chats apenas por API. Não é enviado nos chats padrão do Gateway.</string>
|
||||
<string name="chat_settings_bridge_permissions">Bridge + permissões</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">Se acessibilidade, captura de tela, sobreposição e notificações foram concedidas</string>
|
||||
<string name="chat_settings_foreground_app">App em primeiro plano</string>
|
||||
@@ -766,7 +771,7 @@
|
||||
<string name="chat_settings_battery_level_desc">Porcentagem atual da bateria. Desativado por padrão.</string>
|
||||
<string name="chat_settings_safety_rails">Proteções de segurança</string>
|
||||
<string name="chat_settings_safety_rails_desc">Quantidade de itens bloqueados, quantidade de verbos destrutivos e temporizador de desativação automática</string>
|
||||
<string name="chat_settings_preview">Prévia</string>
|
||||
<string name="chat_settings_preview">Exemplo de chat apenas por API</string>
|
||||
<string name="chat_settings_no_system_message">(nenhuma mensagem do sistema será enviada)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">Analisar anotações de ferramentas</string>
|
||||
<string name="chat_settings_experimental">Experimental</string>
|
||||
@@ -3196,10 +3201,10 @@
|
||||
<string name="injected_context_phone_status_title">Status do celular</string>
|
||||
<string name="injected_context_relay_not_set">Nenhum relay configurado</string>
|
||||
<string name="injected_context_relay_title">Relay</string>
|
||||
<string name="injected_context_subtitle">Contexto enviado com a próxima mensagem</string>
|
||||
<string name="injected_context_subtitle">Prévia deste chat. O contexto do servidor é configurado separadamente.</string>
|
||||
<string name="injected_context_title">Contexto injetado</string>
|
||||
<string name="injected_context_turn_not_set">Não definido</string>
|
||||
<string name="injected_context_turn_title">Modo de detecção de turno</string>
|
||||
<string name="injected_context_turn_title">Contexto do turno</string>
|
||||
<string name="model_picker_cd_clear">Limpar</string>
|
||||
<string name="model_picker_count">%d modelos</string>
|
||||
<string name="power_feature_back_desc">Voltar</string>
|
||||
@@ -4439,4 +4444,13 @@
|
||||
<string name="tool_progress_status_dispatched">Enviado</string>
|
||||
<string name="chat_activity_history_notice">Atividade registrada. As atualizações de progresso não são mantidas; o histórico disponível dos subagentes pode ser aberto somente para leitura.</string>
|
||||
<string name="chat_activity_output_unavailable">A saída não está mais disponível. Este registro preserva o estado registrado do processo.</string>
|
||||
<string name="profile_follow_server_default">Seguir o perfil padrão do servidor</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">Voz sobre outros apps</string>
|
||||
<string name="voice_overlay_setup_body">Mantenha os controles de voz visíveis sobre outro app. O áudio vai para o servidor Hermes configurado. Isso não permite ler a tela nem controlar o telefone. Permita a exibição sobre outros apps nas configurações do Android e volte aqui. É necessária uma notificação do microfone com Parar voz. Fechar a sobreposição ou bloquear a tela encerra a sessão de voz.</string>
|
||||
<string name="voice_overlay_setup_start">Iniciar sobreposição de voz</string>
|
||||
<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>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">问题 %1$d / %2$d</string>
|
||||
<string name="clarify_batch_complete">所有问题均已回答</string>
|
||||
<string name="clarify_batch_expired">此请求已结束</string>
|
||||
<string name="clarify_batch_sending">正在发送回答…</string>
|
||||
<string name="clarify_batch_answered">已回答的问题(%1$d)</string>
|
||||
<string name="app_name">Hermes-Relay</string>
|
||||
<string name="app_title">Hermes-Relay</string>
|
||||
<string name="agent_interface">代理界面</string>
|
||||
@@ -796,7 +801,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">后台聊天提醒</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Hermes 在后台需要输入或完成回复时通知</string>
|
||||
<string name="chat_settings_share_phone_status">与代理分享手机状态</string>
|
||||
<string name="chat_settings_share_phone_status_desc">每轮聊天附带一条关于应用和手机的简短系统消息</string>
|
||||
<string name="chat_settings_share_phone_status_desc">在仅使用 API 的聊天中包含应用和手机上下文。标准 Gateway 聊天不会发送此内容。</string>
|
||||
<string name="chat_settings_bridge_permissions">Bridge + 权限</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">无障碍、屏幕捕获、悬浮窗、通知是否已授权</string>
|
||||
<string name="chat_settings_foreground_app">前台应用</string>
|
||||
@@ -805,7 +810,7 @@
|
||||
<string name="chat_settings_battery_level_desc">当前电池百分比。默认关闭。</string>
|
||||
<string name="chat_settings_safety_rails">安全护栏</string>
|
||||
<string name="chat_settings_safety_rails_desc">黑名单数量、破坏性动词数量和自动禁用计时器</string>
|
||||
<string name="chat_settings_preview">预览</string>
|
||||
<string name="chat_settings_preview">仅使用 API 的聊天示例</string>
|
||||
<string name="chat_settings_no_system_message">(不会发送系统消息)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">解析工具标注</string>
|
||||
<string name="chat_settings_experimental">实验性</string>
|
||||
@@ -3295,10 +3300,10 @@
|
||||
<string name="injected_context_phone_status_title">手机状态</string>
|
||||
<string name="injected_context_relay_not_set">未配置 Relay</string>
|
||||
<string name="injected_context_relay_title">Relay</string>
|
||||
<string name="injected_context_subtitle">随下一条消息发送的上下文</string>
|
||||
<string name="injected_context_subtitle">此聊天的预览。服务器端上下文单独配置。</string>
|
||||
<string name="injected_context_title">注入上下文</string>
|
||||
<string name="injected_context_turn_not_set">未设置</string>
|
||||
<string name="injected_context_turn_title">轮换检测模式</string>
|
||||
<string name="injected_context_turn_title">本轮上下文</string>
|
||||
<string name="model_picker_cd_clear">清空</string>
|
||||
<string name="model_picker_count">%d 个模型</string>
|
||||
<string name="power_feature_back_desc">返回</string>
|
||||
@@ -4520,4 +4525,13 @@
|
||||
<string name="tool_progress_status_dispatched">已分派</string>
|
||||
<string name="chat_activity_history_notice">已记录的活动。进度更新不会保留;可用的子代理历史记录可以以只读方式打开。</string>
|
||||
<string name="chat_activity_output_unavailable">输出已不可用。此条目保留了记录的进程状态。</string>
|
||||
<string name="profile_follow_server_default">跟随服务器默认配置</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">在其他应用上使用语音</string>
|
||||
<string name="voice_overlay_setup_body">在其他应用上保持语音控件可见。音频会发送到你配置的 Hermes 服务器。这不会授权读取屏幕或控制手机。请在 Android 设置中允许显示在其他应用上层,然后返回此处。必须启用带有停止操作的麦克风通知。关闭悬浮窗或锁定屏幕会结束语音会话。</string>
|
||||
<string name="voice_overlay_setup_start">启动语音悬浮窗</string>
|
||||
<string name="voice_overlay_settings_hint">两个版本均可选择使用。在聊天的语音专注模式中选择悬浮窗。仅授予权限不会开始监听。</string>
|
||||
<string name="voice_overlay_reset_position">重置位置</string>
|
||||
<string name="injected_context_gateway_unsupported">Gateway 聊天不会发送此内容。此连接不支持每轮附加上下文。</string>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">Frage %1$d von %2$d</string>
|
||||
<string name="clarify_batch_complete">Alle Fragen beantwortet</string>
|
||||
<string name="clarify_batch_expired">Diese Anfrage ist beendet</string>
|
||||
<string name="clarify_batch_sending">Antwort wird gesendet…</string>
|
||||
<string name="clarify_batch_answered">Beantwortete Fragen (%1$d)</string>
|
||||
<string name="app_name">Hermes-Relay</string>
|
||||
<string name="app_title">Hermes-Relay</string>
|
||||
<string name="agent_interface">Agentenoberfläche</string>
|
||||
@@ -799,7 +804,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">Chat-Benachrichtigungen im Hintergrund</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Benachrichtigen, wenn Hermes Eingaben benötigt oder im Hintergrund fertig wird</string>
|
||||
<string name="chat_settings_share_phone_status">Smartphone-Status mit Agent teilen</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Bei jedem Chatdurchlauf eine kurze Systemnachricht über App und Smartphone einfügen</string>
|
||||
<string name="chat_settings_share_phone_status_desc">App- und Smartphone-Kontext in reinen API-Chats mitsenden. Wird in Standard-Gateway-Chats nicht gesendet.</string>
|
||||
<string name="chat_settings_bridge_permissions">Bridge + Berechtigungen</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">Ob Bedienungshilfe, Bildschirmaufnahme, Overlay und Benachrichtigungen erlaubt sind</string>
|
||||
<string name="chat_settings_foreground_app">App im Vordergrund</string>
|
||||
@@ -808,7 +813,7 @@
|
||||
<string name="chat_settings_battery_level_desc">Aktueller Akkustand in Prozent. Standardmäßig aus.</string>
|
||||
<string name="chat_settings_safety_rails">Schutzmechanismen</string>
|
||||
<string name="chat_settings_safety_rails_desc">Anzahl gesperrter Einträge und destruktiver Verben sowie Timer zur automatischen Deaktivierung</string>
|
||||
<string name="chat_settings_preview">Vorschau</string>
|
||||
<string name="chat_settings_preview">Beispiel für einen reinen API-Chat</string>
|
||||
<string name="chat_settings_no_system_message">(es wird keine Systemnachricht gesendet)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">Werkzeughinweise auswerten</string>
|
||||
<string name="chat_settings_experimental">Experimentell</string>
|
||||
@@ -3364,10 +3369,10 @@
|
||||
<string name="injected_context_phone_status_title">Smartphone-Status</string>
|
||||
<string name="injected_context_relay_not_set">Kein Relay konfiguriert</string>
|
||||
<string name="injected_context_relay_title">Relay</string>
|
||||
<string name="injected_context_subtitle">Kontext, der mit der nächsten Nachricht gesendet wird</string>
|
||||
<string name="injected_context_subtitle">Vorschau für diesen Chat. Serverseitiger Kontext wird separat konfiguriert.</string>
|
||||
<string name="injected_context_title">Eingefügter Kontext</string>
|
||||
<string name="injected_context_turn_not_set">Nicht festgelegt</string>
|
||||
<string name="injected_context_turn_title">Modus zur Durchlauferkennung</string>
|
||||
<string name="injected_context_turn_title">Nachrichtenkontext</string>
|
||||
<string name="model_picker_cd_clear">Leeren</string>
|
||||
<string name="model_picker_count">%d Modelle</string>
|
||||
<string name="power_feature_back_desc">Zurück</string>
|
||||
@@ -4596,4 +4601,13 @@
|
||||
<string name="tool_progress_status_dispatched">Übergeben</string>
|
||||
<string name="chat_activity_history_notice">Gespeicherte Aktivität. Fortschrittsmeldungen werden nicht gespeichert; der verfügbare Verlauf der Unteragenten kann schreibgeschützt geöffnet werden.</string>
|
||||
<string name="chat_activity_output_unavailable">Die Ausgabe ist nicht mehr verfügbar. Dieser Eintrag enthält den gespeicherten Prozessstatus.</string>
|
||||
<string name="profile_follow_server_default">Serverstandard folgen</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">Sprache über anderen Apps</string>
|
||||
<string name="voice_overlay_setup_body">Sprachsteuerung bleibt über anderen Apps sichtbar. Audio geht an deinen konfigurierten Hermes-Server. Dies erlaubt weder Bildschirmlesen noch Telefonsteuerung. Erlaube die Anzeige über anderen Apps in den Android-Einstellungen und kehre zurück. Eine Mikrofonbenachrichtigung mit Stopp-Aktion ist erforderlich. Schließen des Overlays oder Sperren des Bildschirms beendet die Sprachsitzung.</string>
|
||||
<string name="voice_overlay_setup_start">Sprach-Overlay starten</string>
|
||||
<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>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">Pregunta %1$d de %2$d</string>
|
||||
<string name="clarify_batch_complete">Todas las preguntas respondidas</string>
|
||||
<string name="clarify_batch_expired">Esta solicitud ha finalizado</string>
|
||||
<string name="clarify_batch_sending">Enviando respuesta…</string>
|
||||
<string name="clarify_batch_answered">Preguntas respondidas (%1$d)</string>
|
||||
<string name="app_name">Hermes-Relay</string>
|
||||
<string name="app_title">Hermes-Relay</string>
|
||||
<string name="agent_interface">interfaz del agente</string>
|
||||
@@ -724,7 +729,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">Alertas de chat en segundo plano</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Notificar cuando Hermes necesite información o termine en segundo plano</string>
|
||||
<string name="chat_settings_share_phone_status">Compartir el estado del teléfono con el agente</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Incluya un breve mensaje del sistema sobre la aplicación y el teléfono en cada turno de chat.</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Incluir contexto de la app y el teléfono en chats solo por API. No se envía en los chats estándar de Gateway.</string>
|
||||
<string name="chat_settings_bridge_permissions">Bridge + permisos</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">Si se concede accesibilidad, captura de pantalla, superposición o notificaciones</string>
|
||||
<string name="chat_settings_foreground_app">Aplicación en primer plano</string>
|
||||
@@ -733,7 +738,7 @@
|
||||
<string name="chat_settings_battery_level_desc">Porcentaje de batería actual. Desactivado de forma predeterminada.</string>
|
||||
<string name="chat_settings_safety_rails">Barandillas de seguridad</string>
|
||||
<string name="chat_settings_safety_rails_desc">Recuento de listas de bloqueo, recuento de verbos destructivos y temporizador de desactivación automática</string>
|
||||
<string name="chat_settings_preview">Avance</string>
|
||||
<string name="chat_settings_preview">Ejemplo de chat solo por API</string>
|
||||
<string name="chat_settings_no_system_message">(no se enviará ningún mensaje del sistema)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">Anotaciones de la herramienta de análisis</string>
|
||||
<string name="chat_settings_experimental">Experimental</string>
|
||||
@@ -3028,10 +3033,10 @@
|
||||
<string name="injected_context_phone_status_title">Estado del teléfono</string>
|
||||
<string name="injected_context_relay_not_set">Ningún relay configurado</string>
|
||||
<string name="injected_context_relay_title">Relay</string>
|
||||
<string name="injected_context_subtitle">Contexto enviado con el siguiente mensaje.</string>
|
||||
<string name="injected_context_subtitle">Vista previa de este chat. El contexto del servidor se configura por separado.</string>
|
||||
<string name="injected_context_title">Contexto inyectado</string>
|
||||
<string name="injected_context_turn_not_set">No establecido</string>
|
||||
<string name="injected_context_turn_title">Modo de detección de giro</string>
|
||||
<string name="injected_context_turn_title">Contexto del turno</string>
|
||||
<string name="model_picker_cd_clear">Borrar</string>
|
||||
<string name="model_picker_count">Modelos %d</string>
|
||||
<string name="power_feature_back_desc">Atrás</string>
|
||||
@@ -4287,4 +4292,13 @@
|
||||
<string name="tool_progress_status_dispatched">Enviado</string>
|
||||
<string name="chat_activity_history_notice">Actividad registrada. No se conservan las actualizaciones de progreso; el historial disponible de los subagentes se puede abrir en modo de solo lectura.</string>
|
||||
<string name="chat_activity_output_unavailable">La salida ya no está disponible. Esta entrada conserva el estado registrado del proceso.</string>
|
||||
<string name="profile_follow_server_default">Seguir el perfil predeterminado del servidor</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">Voz sobre otras apps</string>
|
||||
<string name="voice_overlay_setup_body">Mantén los controles de voz visibles sobre otra app. El audio se envía a tu servidor Hermes configurado. Esto no permite leer la pantalla ni controlar el teléfono. Permite mostrar sobre otras apps en los ajustes de Android y vuelve aquí. Se requiere una notificación del micrófono con Detener voz. Cerrar la ventana o bloquear la pantalla termina la sesión de voz.</string>
|
||||
<string name="voice_overlay_setup_start">Iniciar ventana de voz</string>
|
||||
<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>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">質問 %1$d / %2$d</string>
|
||||
<string name="clarify_batch_complete">すべての質問に回答しました</string>
|
||||
<string name="clarify_batch_expired">このリクエストは終了しました</string>
|
||||
<string name="clarify_batch_sending">回答を送信中…</string>
|
||||
<string name="clarify_batch_answered">回答済みの質問(%1$d)</string>
|
||||
<string name="app_name">Hermes-Relay</string>
|
||||
<string name="app_title">Hermes-Relay</string>
|
||||
<string name="agent_interface">エージェントインターフェース</string>
|
||||
@@ -796,7 +801,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">バックグラウンドのチャット通知</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">バックグラウンドで Hermes が入力を必要としたとき、または完了したときに通知します</string>
|
||||
<string name="chat_settings_share_phone_status">電話のステータスをエージェントと共有する</string>
|
||||
<string name="chat_settings_share_phone_status_desc">すべてのチャット ターンにアプリと電話に関する短いシステム メッセージを含めます</string>
|
||||
<string name="chat_settings_share_phone_status_desc">API のみのチャットにアプリと端末のコンテキストを含めます。標準の Gateway チャットでは送信されません。</string>
|
||||
<string name="chat_settings_bridge_permissions">Bridge + 権限</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">アクセシビリティ、画面キャプチャ、オーバーレイ、通知が許可されているかどうか</string>
|
||||
<string name="chat_settings_foreground_app">フォアグラウンドアプリ</string>
|
||||
@@ -805,7 +810,7 @@
|
||||
<string name="chat_settings_battery_level_desc">現在のバッテリーのパーセント。デフォルトではオフです。</string>
|
||||
<string name="chat_settings_safety_rails">安全レール</string>
|
||||
<string name="chat_settings_safety_rails_desc">ブロックリストの数、破壊的な動詞の数、および自動無効化タイマー</string>
|
||||
<string name="chat_settings_preview">プレビュー</string>
|
||||
<string name="chat_settings_preview">API のみのチャットの例</string>
|
||||
<string name="chat_settings_no_system_message">(システムメッセージは送信されません)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">解析ツールの注釈</string>
|
||||
<string name="chat_settings_experimental">実験的</string>
|
||||
@@ -3371,10 +3376,10 @@
|
||||
<string name="injected_context_phone_status_title">電話のステータス</string>
|
||||
<string name="injected_context_relay_not_set">Relayが設定されていません</string>
|
||||
<string name="injected_context_relay_title">Relay</string>
|
||||
<string name="injected_context_subtitle">次のメッセージで送信されるコンテキスト</string>
|
||||
<string name="injected_context_subtitle">このチャットのプレビューです。サーバー側のコンテキストは別途設定されます。</string>
|
||||
<string name="injected_context_title">挿入されたコンテキスト</string>
|
||||
<string name="injected_context_turn_not_set">未設定</string>
|
||||
<string name="injected_context_turn_title">回転検出モード</string>
|
||||
<string name="injected_context_turn_title">ターンのコンテキスト</string>
|
||||
<string name="model_picker_cd_clear">クリア</string>
|
||||
<string name="model_picker_count">%d モデル</string>
|
||||
<string name="power_feature_back_desc">戻る</string>
|
||||
@@ -4591,4 +4596,13 @@
|
||||
<string name="tool_progress_status_dispatched">ディスパッチ済み</string>
|
||||
<string name="chat_activity_history_notice">記録されたアクティビティです。進捗の更新は保存されません。利用可能なサブエージェントの履歴は読み取り専用で開けます。</string>
|
||||
<string name="chat_activity_output_unavailable">出力は利用できなくなりました。この項目には記録されたプロセスの状態が残っています。</string>
|
||||
<string name="profile_follow_server_default">サーバーのデフォルトに従う</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">他のアプリ上で音声を使用</string>
|
||||
<string name="voice_overlay_setup_body">他のアプリ上に音声操作を表示します。音声は設定したHermesサーバーに送信されます。画面の読み取りや端末操作は許可されません。Androidの設定で他のアプリ上への表示を許可し、ここに戻ってください。停止操作付きのマイク通知が必要です。表示を閉じるか画面をロックすると音声セッションは終了します。</string>
|
||||
<string name="voice_overlay_setup_start">音声オーバーレイを開始</string>
|
||||
<string name="voice_overlay_settings_hint">両方のビルドで任意に利用できます。チャットの音声フォーカスでオーバーレイを選択します。権限の付与だけで録音は始まりません。</string>
|
||||
<string name="voice_overlay_reset_position">位置をリセット</string>
|
||||
<string name="injected_context_gateway_unsupported">Gateway チャットでは送信されません。この接続はターンごとの追加コンテキストに対応していません。</string>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">Вопрос %1$d из %2$d</string>
|
||||
<string name="clarify_batch_complete">Все вопросы отвечены</string>
|
||||
<string name="clarify_batch_expired">Этот запрос завершён</string>
|
||||
<string name="clarify_batch_sending">Отправка ответа…</string>
|
||||
<string name="clarify_batch_answered">Отвеченные вопросы (%1$d)</string>
|
||||
<string name="app_name">Hermes-Relay</string>
|
||||
<string name="app_title">Hermes-Relay</string>
|
||||
<string name="agent_interface">интерфейс агента</string>
|
||||
@@ -773,7 +778,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">Уведомления о фоновом чате</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Уведомлять, когда Гермес требует ввода или заканчивает работу, когда приложение находится в фоновом режиме</string>
|
||||
<string name="chat_settings_share_phone_status">Поделиться статусом телефона с агентом</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Включите короткое системное сообщение о приложении и телефоне в каждом обороте чата</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Добавлять контекст приложения и телефона в чаты только через API. В стандартных чатах Gateway он не отправляется.</string>
|
||||
<string name="chat_settings_bridge_permissions">Мост + разрешения</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">Разрешения на доступность, захват экрана, наложение, уведомления</string>
|
||||
<string name="chat_settings_foreground_app">Приложение на переднем плане</string>
|
||||
@@ -782,7 +787,7 @@
|
||||
<string name="chat_settings_battery_level_desc">Текущий процент заряда батареи. По умолчанию выключено.</string>
|
||||
<string name="chat_settings_safety_rails">Ограждения безопасности</string>
|
||||
<string name="chat_settings_safety_rails_desc">Количество в черном списке, количество деструктивных глаголов и таймер автоматического отключения</string>
|
||||
<string name="chat_settings_preview">Предпросмотр</string>
|
||||
<string name="chat_settings_preview">Пример чата только через API</string>
|
||||
<string name="chat_settings_no_system_message">(системное сообщение не будет отправлено)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">Анализ аннотаций инструментов</string>
|
||||
<string name="chat_settings_experimental">Экспериментальные</string>
|
||||
@@ -3234,10 +3239,10 @@
|
||||
<string name="injected_context_phone_status_title">Статус телефона</string>
|
||||
<string name="injected_context_relay_not_set">плагин Relay не настроен</string>
|
||||
<string name="injected_context_relay_title">плагин Relay</string>
|
||||
<string name="injected_context_subtitle">Контекст отправляется с следующим сообщением</string>
|
||||
<string name="injected_context_subtitle">Предпросмотр для этого чата. Контекст на стороне сервера настраивается отдельно.</string>
|
||||
<string name="injected_context_title">Внедренный контекст</string>
|
||||
<string name="injected_context_turn_not_set">Не установлено</string>
|
||||
<string name="injected_context_turn_title">Режим обнаружения Turn</string>
|
||||
<string name="injected_context_turn_title">Контекст хода</string>
|
||||
<string name="model_picker_cd_clear">Очистить</string>
|
||||
<string name="model_picker_count">%d моделей</string>
|
||||
<string name="power_feature_back_desc">Назад</string>
|
||||
@@ -4335,4 +4340,13 @@
|
||||
<string name="tool_progress_status_dispatched">Отправлено</string>
|
||||
<string name="chat_activity_history_notice">Сохранённая активность. Обновления хода работы не сохраняются; доступную историю субагентов можно открыть только для чтения.</string>
|
||||
<string name="chat_activity_output_unavailable">Вывод больше недоступен. Эта запись сохраняет зафиксированное состояние процесса.</string>
|
||||
<string name="profile_follow_server_default">Следовать профилю сервера по умолчанию</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">Голос поверх других приложений</string>
|
||||
<string name="voice_overlay_setup_body">Голосовые элементы управления видны поверх другого приложения. Аудио отправляется на настроенный сервер Hermes. Это не разрешает чтение экрана или управление телефоном. Разрешите показ поверх приложений в настройках Android и вернитесь сюда. Требуется уведомление микрофона с кнопкой остановки. Закрытие окна или блокировка экрана завершает голосовой сеанс.</string>
|
||||
<string name="voice_overlay_setup_start">Начать голосовой оверлей</string>
|
||||
<string name="voice_overlay_settings_hint">Необязательно в обеих сборках. Откройте голосовой фокус в чате и выберите оверлей. Одни разрешения никогда не включают прослушивание.</string>
|
||||
<string name="voice_overlay_reset_position">Сбросить положение</string>
|
||||
<string name="injected_context_gateway_unsupported">Не отправляется в чате Gateway. Это подключение не поддерживает дополнительный контекст для каждого хода.</string>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="clarify_batch_progress">Question %1$d of %2$d</string>
|
||||
<string name="clarify_batch_complete">All questions answered</string>
|
||||
<string name="clarify_batch_expired">This request has ended</string>
|
||||
<string name="clarify_batch_sending">Sending answer…</string>
|
||||
<string name="clarify_batch_answered">Answered questions (%1$d)</string>
|
||||
<string name="chat_debug_title" translatable="false">Session diagnostics</string>
|
||||
<string name="chat_debug_open" translatable="false">Open session diagnostics</string>
|
||||
<string name="chat_debug_close" translatable="false">Close session diagnostics</string>
|
||||
@@ -882,7 +887,7 @@
|
||||
<string name="chat_settings_notify_when_finishes">Background chat alerts</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Notify when Hermes needs input or finishes while the app is in the background</string>
|
||||
<string name="chat_settings_share_phone_status">Share phone status with agent</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Include a short system message about the app and phone on every chat turn</string>
|
||||
<string name="chat_settings_share_phone_status_desc">Include app and phone context in API-only chats. Not sent in standard Gateway chats.</string>
|
||||
<string name="chat_settings_bridge_permissions">Bridge + permissions</string>
|
||||
<string name="chat_settings_bridge_permissions_desc">Whether accessibility, screen capture, overlay, notifications are granted</string>
|
||||
<string name="chat_settings_foreground_app">Foreground app</string>
|
||||
@@ -891,7 +896,7 @@
|
||||
<string name="chat_settings_battery_level_desc">Current battery percent. Off by default.</string>
|
||||
<string name="chat_settings_safety_rails">Safety rails</string>
|
||||
<string name="chat_settings_safety_rails_desc">Blocklist count, destructive-verb count, and auto-disable timer</string>
|
||||
<string name="chat_settings_preview">Preview</string>
|
||||
<string name="chat_settings_preview">Example for API-only chat</string>
|
||||
<string name="chat_settings_no_system_message">(no system message will be sent)</string>
|
||||
<string name="chat_settings_parse_tool_annotations">Parse tool annotations</string>
|
||||
<string name="chat_settings_experimental">Experimental</string>
|
||||
@@ -3764,10 +3769,10 @@
|
||||
<string name="injected_context_phone_status_title">Phone status</string>
|
||||
<string name="injected_context_relay_not_set">No relay configured</string>
|
||||
<string name="injected_context_relay_title">Relay</string>
|
||||
<string name="injected_context_subtitle">Context sent with next message</string>
|
||||
<string name="injected_context_subtitle">Preview for this chat. Server-side context is configured separately.</string>
|
||||
<string name="injected_context_title">Injected context</string>
|
||||
<string name="injected_context_turn_not_set">Not set</string>
|
||||
<string name="injected_context_turn_title">Turn detection mode</string>
|
||||
<string name="injected_context_turn_title">Turn context</string>
|
||||
<string name="model_picker_cd_clear">Clear</string>
|
||||
<string name="model_picker_count">%d models</string>
|
||||
<string name="power_feature_back_desc">Back</string>
|
||||
@@ -4654,4 +4659,13 @@
|
||||
<string name="dev_message_retry_result" translatable="false">Preview retry selected — no request sent.</string>
|
||||
<string name="dev_message_clear" translatable="false">Clear previews</string>
|
||||
<string name="dev_message_clear_desc" translatable="false">Dismiss only these samples; real app messages are preserved.</string>
|
||||
<string name="profile_follow_server_default">Follow server default</string>
|
||||
|
||||
<!-- User-started voice overlay, independent of Device Control. -->
|
||||
<string name="voice_overlay_setup_title">Voice over other apps</string>
|
||||
<string name="voice_overlay_setup_body">Keep voice controls visible while using another app. Audio goes to your configured Hermes server. This does not grant screen reading or phone control. Allow display over other apps in Android Settings, then return here. A microphone notification with Stop voice is required. Closing the overlay or locking the screen ends this voice session.</string>
|
||||
<string name="voice_overlay_setup_start">Start voice overlay</string>
|
||||
<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>
|
||||
</resources>
|
||||
|
||||
@@ -17,11 +17,10 @@
|
||||
<!--
|
||||
Tier C (C1-C4) sideload-only permissions.
|
||||
|
||||
These are deliberately NOT declared in the main manifest: Google Play
|
||||
policy forbids CALL_PHONE / SEND_SMS / READ_CONTACTS without a default-
|
||||
dialer / default-SMS-app justification, and ACCESS_FINE_LOCATION is
|
||||
flagged alongside auto-dial on the `googlePlay` track. The `sideload`
|
||||
flavor is the only track that ships them.
|
||||
These are deliberately kept outside Play's voice-only capability surface.
|
||||
SMS permissions require an eligible default-handler/approved use on Play;
|
||||
contacts, foreground location and CALL_PHONE have distinct requirements.
|
||||
Their omission here is a product boundary, not a blanket permission ban.
|
||||
|
||||
Each of the four `android_*` tools (location, search_contacts, call,
|
||||
send_sms) runtime-checks the corresponding permission in
|
||||
|
||||
@@ -43,13 +43,13 @@ class AgentDisplayTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun effectiveDisplayProfile_usesDefaultProfileForDisplayOnly() {
|
||||
fun effectiveDisplayProfile_doesNotAssumeRootWhenScopeIsUnknown() {
|
||||
val effective = AgentDisplay.effectiveDisplayProfile(
|
||||
selectedProfile = null,
|
||||
profiles = listOf(mizu, defaultProfile),
|
||||
)
|
||||
|
||||
assertEquals(defaultProfile, effective)
|
||||
assertNull(effective)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,7 +86,7 @@ class AgentDisplayTest {
|
||||
fun agentName_usesProfileNameNotVerboseDescription() {
|
||||
// The name slot shows the NAME, even when a (verbose) description exists.
|
||||
assertEquals(
|
||||
"Mizu",
|
||||
"mizu",
|
||||
AgentDisplay.agentName(
|
||||
profile = mizu.copy(description = "Builds and maintains the codebase"),
|
||||
selectedPersonality = "friendly",
|
||||
@@ -96,7 +96,7 @@ class AgentDisplayTest {
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"Coder",
|
||||
"coder",
|
||||
AgentDisplay.agentName(
|
||||
profile = mizu.copy(name = "coder", description = ""),
|
||||
selectedPersonality = "friendly",
|
||||
@@ -107,11 +107,11 @@ class AgentDisplayTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun agentName_usesConciseDefaultDescriptionNotVerboseSummary() {
|
||||
fun agentName_usesDisplayNameAndNeverInfersIdentityFromDescription() {
|
||||
assertEquals(
|
||||
"Victor",
|
||||
AgentDisplay.agentName(
|
||||
profile = defaultProfile.copy(description = "victor"),
|
||||
profile = defaultProfile.copy(displayName = "Victor", description = "Summary"),
|
||||
selectedPersonality = "default",
|
||||
defaultPersonality = "",
|
||||
connectionLabel = "Lab",
|
||||
@@ -119,7 +119,7 @@ class AgentDisplayTest {
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"Lab",
|
||||
"default",
|
||||
AgentDisplay.agentName(
|
||||
profile = defaultProfile.copy(description = "Builds and maintains the codebase."),
|
||||
selectedPersonality = "default",
|
||||
@@ -175,7 +175,7 @@ class AgentDisplayTest {
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"Lab",
|
||||
"Hermes",
|
||||
AgentDisplay.agentName(
|
||||
profile = null,
|
||||
selectedPersonality = "default",
|
||||
@@ -218,7 +218,7 @@ class AgentDisplayTest {
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"Lab",
|
||||
"Hermes",
|
||||
AgentDisplay.agentName(
|
||||
profile = null,
|
||||
selectedPersonality = "none",
|
||||
@@ -255,6 +255,18 @@ class AgentDisplayTest {
|
||||
assertNull(AgentDisplay.effectiveSessionProfileName(null, null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmedDefaultKeepsItsNameWhileRosterLoadsAndDoesNotBorrowRootMetadata() {
|
||||
val effective = AgentDisplay.effectiveDisplayProfile(null, listOf(defaultProfile), "victor")
|
||||
assertEquals("victor", effective?.name)
|
||||
assertEquals("victor", AgentDisplay.profileDisplayName(effective))
|
||||
assertEquals("default", AgentDisplay.profileDisplayName(defaultProfile))
|
||||
val victor = Profile("victor", "", displayName = "Victor")
|
||||
assertEquals("Victor", AgentDisplay.profileDisplayName(
|
||||
AgentDisplay.effectiveDisplayProfile(null, listOf(defaultProfile, victor), "victor")))
|
||||
assertEquals(defaultProfile, AgentDisplay.effectiveDisplayProfile(defaultProfile, listOf(victor), "victor"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun displayModelName_hidesGenericApiAlias() {
|
||||
assertNull(AgentDisplay.displayModelName("hermes-agent"))
|
||||
|
||||
@@ -56,6 +56,21 @@ class ChatTurnCheckpointStoreTest {
|
||||
assertEquals(checkpoint, store.read())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun partialClarifyBatch_roundTripsWithExactQuestionOwnership() = runTest {
|
||||
val checkpoint = sampleCheckpoint().copy(pendingAsk = ChatTurnAskCheckpoint(
|
||||
kind = "CLARIFY", requestId = "batch", text = "", timeoutSeconds = 0,
|
||||
messageId = "ask-batch", cardKey = "batch", receivedAt = now,
|
||||
questions = listOf(
|
||||
com.hermesandroid.relay.network.upstream.GatewayClarifyQuestion("route/a", "Which route?", listOf("Canary")),
|
||||
com.hermesandroid.relay.network.upstream.GatewayClarifyQuestion("environment:b", "Which environments?", listOf("Stage", "Production"), true),
|
||||
), answers = mapOf("route/a" to "Canary"),
|
||||
))
|
||||
store.write(checkpoint)
|
||||
assertEquals(checkpoint, store.read())
|
||||
assertEquals(mapOf("route/a" to "Canary"), store.read()?.pendingAsk?.answers)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corruptJson_isDiscarded() = runTest {
|
||||
dataStore.edit { preferences ->
|
||||
|
||||
@@ -21,6 +21,22 @@ import kotlinx.coroutines.sync.withLock
|
||||
* raw DataStore shape that its Context constructor resolves in production.
|
||||
*/
|
||||
class ProfileSelectionStoreTest {
|
||||
@Test
|
||||
fun restartedStoreRetainsIndependentDefaultAndNamedChoicesAcrossConnections() = runBlocking {
|
||||
val data = InMemoryPreferencesDataStore()
|
||||
val first = ProfileSelectionStore(data)
|
||||
first.setSelectedProfile("a", AgentDisplay.SERVER_DEFAULT_PROFILE_KEY)
|
||||
first.setSelectedProfile("b", "default")
|
||||
first.setSelectedProfile("c", "victor")
|
||||
val restarted = ProfileSelectionStore(data)
|
||||
assertEquals(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, restarted.selectedProfileFlow("a").first())
|
||||
assertEquals("default", restarted.selectedProfileFlow("b").first())
|
||||
assertEquals("victor", restarted.selectedProfileFlow("c").first())
|
||||
restarted.setSelectedProfile("a", "victor")
|
||||
assertEquals("default", restarted.selectedProfileFlow("b").first())
|
||||
assertEquals("victor", restarted.selectedProfileFlow("c").first())
|
||||
}
|
||||
|
||||
|
||||
private val store = ProfileSelectionStore(InMemoryPreferencesDataStore())
|
||||
|
||||
|
||||
@@ -477,6 +477,151 @@ class EndpointResolverTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearCache_handlesConcurrentProbeCompletions_withoutThrowingOrPublishingStaleState() = runTest {
|
||||
val candidateCount = 24
|
||||
val staleRequestsStarted = CountDownLatch(candidateCount)
|
||||
val releaseStaleRequests = CountDownLatch(1)
|
||||
val staleRequestsFinished = CountDownLatch(candidateCount)
|
||||
val raceGate = CountDownLatch(1)
|
||||
val requestSequence = AtomicInteger(0)
|
||||
val blockingClient = fastClient.newBuilder()
|
||||
.addInterceptor { chain ->
|
||||
if (requestSequence.incrementAndGet() <= candidateCount) {
|
||||
staleRequestsStarted.countDown()
|
||||
try {
|
||||
releaseStaleRequests.await(5, TimeUnit.SECONDS)
|
||||
} finally {
|
||||
staleRequestsFinished.countDown()
|
||||
}
|
||||
throw InterruptedIOException("concurrent invalidation test probe")
|
||||
}
|
||||
chain.proceed(chain.request())
|
||||
}
|
||||
.build()
|
||||
val resolver = EndpointResolver(blockingClient, clock = { clockMillis.get() })
|
||||
val candidates = (1..candidateCount).map { index ->
|
||||
candidate("concurrent-clear-$index", priority = 0, server = reachableServer)
|
||||
}
|
||||
|
||||
try {
|
||||
val staleResolve = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
resolver.resolve(candidates, EndpointSurface.Api)
|
||||
}
|
||||
assertTrue(
|
||||
"every physical probe must be active before the completion/invalidation race",
|
||||
staleRequestsStarted.await(5, TimeUnit.SECONDS),
|
||||
)
|
||||
|
||||
val invalidation = async(Dispatchers.Default) {
|
||||
raceGate.await(5, TimeUnit.SECONDS)
|
||||
resolver.clearCache()
|
||||
}
|
||||
val completions = async(Dispatchers.Default) {
|
||||
raceGate.await(5, TimeUnit.SECONDS)
|
||||
releaseStaleRequests.countDown()
|
||||
}
|
||||
raceGate.countDown()
|
||||
|
||||
withContext(Dispatchers.Default.limitedParallelism(1)) {
|
||||
withTimeout(2_000L) {
|
||||
invalidation.await()
|
||||
completions.await()
|
||||
staleResolve.await()
|
||||
}
|
||||
}
|
||||
assertTrue(staleRequestsFinished.await(5, TimeUnit.SECONDS))
|
||||
assertTrue(resolver.cacheSnapshot().isEmpty())
|
||||
|
||||
resolver.clearCache()
|
||||
val freshWinner = withContext(Dispatchers.Default.limitedParallelism(1)) {
|
||||
withTimeout(2_000L) {
|
||||
resolver.resolve(listOf(candidates.first()), EndpointSurface.Api)
|
||||
}
|
||||
}
|
||||
assertEquals(candidates.first(), freshWinner)
|
||||
assertTrue(
|
||||
"a completion racing invalidation must not overwrite the fresh generation",
|
||||
resolver.probeOutcomes.value.getValue(
|
||||
EndpointResolver.cacheKey(candidates.first(), EndpointSurface.Api),
|
||||
).reachable,
|
||||
)
|
||||
} finally {
|
||||
raceGate.countDown()
|
||||
releaseStaleRequests.countDown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidatedProbeCompletion_cannotRemoveFreshReplacement() = runTest {
|
||||
val staleRequestStarted = CountDownLatch(1)
|
||||
val releaseStaleRequest = CountDownLatch(1)
|
||||
val staleRequestFinished = CountDownLatch(1)
|
||||
val freshRequestStarted = CountDownLatch(1)
|
||||
val releaseFreshRequest = CountDownLatch(1)
|
||||
val requestSequence = AtomicInteger(0)
|
||||
val blockingClient = fastClient.newBuilder()
|
||||
.addInterceptor { chain ->
|
||||
when (requestSequence.incrementAndGet()) {
|
||||
1 -> {
|
||||
staleRequestStarted.countDown()
|
||||
try {
|
||||
releaseStaleRequest.await(5, TimeUnit.SECONDS)
|
||||
} finally {
|
||||
staleRequestFinished.countDown()
|
||||
}
|
||||
throw InterruptedIOException("invalidated identity test probe")
|
||||
}
|
||||
2 -> {
|
||||
freshRequestStarted.countDown()
|
||||
releaseFreshRequest.await(5, TimeUnit.SECONDS)
|
||||
chain.proceed(chain.request())
|
||||
}
|
||||
else -> chain.proceed(chain.request())
|
||||
}
|
||||
}
|
||||
.build()
|
||||
val resolver = EndpointResolver(blockingClient, clock = { clockMillis.get() })
|
||||
val candidate = candidate("replacement-identity-test", priority = 0, server = reachableServer)
|
||||
|
||||
try {
|
||||
val staleResolve = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
resolver.resolve(listOf(candidate), EndpointSurface.Api)
|
||||
}
|
||||
assertTrue(staleRequestStarted.await(5, TimeUnit.SECONDS))
|
||||
resolver.clearCache()
|
||||
|
||||
val freshResolve = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
resolver.resolve(listOf(candidate), EndpointSurface.Api)
|
||||
}
|
||||
assertTrue(freshRequestStarted.await(5, TimeUnit.SECONDS))
|
||||
|
||||
releaseStaleRequest.countDown()
|
||||
assertTrue(staleRequestFinished.await(5, TimeUnit.SECONDS))
|
||||
withContext(Dispatchers.Default.limitedParallelism(1)) {
|
||||
withTimeout(1_000L) { staleResolve.await() }
|
||||
}
|
||||
|
||||
val joiningResolve = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
resolver.resolve(listOf(candidate), EndpointSurface.Api)
|
||||
}
|
||||
releaseFreshRequest.countDown()
|
||||
|
||||
withContext(Dispatchers.Default.limitedParallelism(1)) {
|
||||
assertEquals(candidate, withTimeout(2_000L) { freshResolve.await() })
|
||||
assertEquals(candidate, withTimeout(2_000L) { joiningResolve.await() })
|
||||
}
|
||||
assertEquals(
|
||||
"the late stale completion must leave the fresh shared probe registered",
|
||||
2,
|
||||
requestSequence.get(),
|
||||
)
|
||||
} finally {
|
||||
releaseStaleRequest.countDown()
|
||||
releaseFreshRequest.countDown()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// Test 6 — cached-reachable result is re-probed after TTL
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
@@ -12,6 +12,7 @@ import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
@@ -659,6 +660,40 @@ class DashboardApiClientTest {
|
||||
assertEquals("basic", session.provider)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passwordLogin_stripsOnlyBrowserForbiddenLineBreaksFromCredentials() = runTest {
|
||||
val preservedCredential = " \t\u00A0påss\u200B "
|
||||
val cases = listOf(
|
||||
listOf("user", "line\rbreak", "user", "linebreak"),
|
||||
listOf("user", "line\nbreak", "user", "linebreak"),
|
||||
listOf("user", "line\r\nbreak", "user", "linebreak"),
|
||||
listOf("us\r\ner", "secret", "user", "secret"),
|
||||
listOf(
|
||||
preservedCredential,
|
||||
preservedCredential,
|
||||
preservedCredential,
|
||||
preservedCredential,
|
||||
),
|
||||
)
|
||||
repeat(cases.size) {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody("""{"ok": true, "next": "/"}"""),
|
||||
)
|
||||
}
|
||||
|
||||
val client = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
cases.forEach { (username, password, expectedUsername, expectedPassword) ->
|
||||
client.loginPassword(username = username, password = password).getOrThrow()
|
||||
|
||||
val body = Json.parseToJsonElement(server.takeRequest().body.readUtf8()).jsonObject
|
||||
assertEquals(expectedUsername, body["username"]?.jsonPrimitive?.content)
|
||||
assertEquals(expectedPassword, body["password"]?.jsonPrimitive?.content)
|
||||
}
|
||||
}
|
||||
|
||||
private fun storedCookie(
|
||||
name: String,
|
||||
value: String,
|
||||
@@ -1035,6 +1070,18 @@ class DashboardApiClientTest {
|
||||
assertEquals("claude-opus-4-8", profiles[1].model)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listProfiles_keepsDisplayIdentitySeparateAndAcceptsUnconfiguredRoot() = runTest {
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"profiles":[{"name":"default","model":null,"is_default":true},
|
||||
{"name":"guide","model":"model","display_name":"Guide","description":"Summary"}]}"""))
|
||||
val profiles = DashboardApiClient(baseUrl = server.url("/").toString()).listProfiles().getOrThrow()
|
||||
assertEquals(listOf("default", "guide"), profiles.map { it.name })
|
||||
assertEquals("", profiles[0].model)
|
||||
assertEquals("Guide", profiles[1].displayName)
|
||||
assertEquals("Summary", profiles[1].description)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listProfiles_parsesObjectMapShapeWithInjectedName() = runTest {
|
||||
server.enqueue(
|
||||
|
||||
@@ -74,6 +74,8 @@ class GatewayClientHarness(
|
||||
|
||||
@Volatile
|
||||
var recoveryRunning = false
|
||||
@Volatile
|
||||
var recoveryClarify: JsonObject? = null
|
||||
|
||||
@Volatile
|
||||
var recoveryAssistant = ""
|
||||
@@ -197,6 +199,7 @@ class GatewayClientHarness(
|
||||
put("model", "gpt-5.6")
|
||||
put("provider", "openai")
|
||||
put("description", "Android operator")
|
||||
put("display_name", "Guide")
|
||||
put("skill_count", 3)
|
||||
put("has_avatar", true)
|
||||
put("ui_meta", buildJsonObject { put("accent", "#ff5500") })
|
||||
@@ -585,6 +588,7 @@ class GatewayClientHarness(
|
||||
private val autoRespondEnabled = autoRespond
|
||||
|
||||
private fun recoveryPayload(sessionId: String, requestedProfile: String? = null): JsonObject = buildJsonObject {
|
||||
recoveryClarify?.let { put("pending_clarify", it) }
|
||||
put("session_id", sessionId)
|
||||
put("running", recoveryRunning)
|
||||
put("status", if (recoveryRunning) "streaming" else "idle")
|
||||
@@ -1009,6 +1013,7 @@ class GatewayChatClientTest {
|
||||
|
||||
assertEquals(1, profiles.size)
|
||||
assertEquals("operator", profiles.single().name)
|
||||
assertEquals("Guide", profiles.single().displayName)
|
||||
assertEquals("openai", profiles.single().provider)
|
||||
assertTrue(profiles.single().hasAvatar)
|
||||
assertEquals("#ff5500", (profiles.single().uiMeta["accent"] as JsonPrimitive).content)
|
||||
@@ -3163,6 +3168,75 @@ class GatewayChatClientTest {
|
||||
|
||||
// --- Ask responders ---
|
||||
|
||||
@Test
|
||||
fun `batch clarify reconnect adopts server answered qids without resubmitting`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "hi", null, r.callbacks) { r.preflightFailures += it }
|
||||
val socket = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
harness.recoveryRunning = true
|
||||
harness.recoveryClarify = harness.json.parseToJsonElement("""{
|
||||
"request_id":"batch","questions":[{"qid":"q0","question":"First?"},{"qid":"q1","question":"Second?"}],
|
||||
"answers":{"q0":"accepted before disconnect"}}
|
||||
""") as JsonObject
|
||||
socket.close(1001, "fixture reconnect")
|
||||
val replacement = harness.awaitServerSocket()
|
||||
harness.awaitRpc("session.activate")
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (r.interactions.isEmpty() && System.nanoTime() < deadline) Thread.sleep(10)
|
||||
assertEquals(mapOf("q0" to "accepted before disconnect"), r.interactions.last().answers)
|
||||
assertTrue(harness.rpcLog.none { it.first == "clarify.respond" })
|
||||
assertTrue(runBlocking { client.respondClarify("batch", "second", "q1") }.isSuccess)
|
||||
replacement.send(harness.eventFrame("message.complete", buildJsonObject { put("text", "done") }, "live-1"))
|
||||
assertTrue(r.completeLatch.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `batch clarify responds with exact question id and JSON array answer`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "hi", null, r.callbacks) { r.preflightFailures += it }
|
||||
val socket = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
socket.send(harness.eventFrame("clarify.request", harness.json.parseToJsonElement("""
|
||||
{"request_id":"batch","questions":[{"qid":"env:b","question":"Which environments?","choices":["Stage","Production"],"multi_select":true}]}
|
||||
""") as JsonObject, "live-1"))
|
||||
awaitCondition { r.interactions.isNotEmpty() }
|
||||
val answer = "[\"Stage\",\"Production\"]"
|
||||
assertTrue(runBlocking { client.respondClarify("batch", answer, "env:b") }.isSuccess)
|
||||
val respond = harness.awaitRpc("clarify.respond")
|
||||
assertEquals("batch", (respond["request_id"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals("env:b", (respond["question_id"] as? JsonPrimitive)?.contentOrNull)
|
||||
assertEquals(answer, (respond["answer"] as? JsonPrimitive)?.contentOrNull)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `batch answer waits for reconnect replay and refuses an already answered qid`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "hi", null, r.callbacks) { r.preflightFailures += it }
|
||||
val socket = harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
val request = harness.json.parseToJsonElement("""{"request_id":"batch","questions":[
|
||||
{"qid":"q0","question":"First?"},{"qid":"q1","question":"Second?"}]}""") as JsonObject
|
||||
socket.send(harness.eventFrame("clarify.request", request, "live-1"))
|
||||
awaitCondition { r.interactions.isNotEmpty() }
|
||||
harness.recoveryRunning = true
|
||||
harness.suppressAckMethods += "session.activate"
|
||||
socket.close(1001, "fixture lost acknowledgement")
|
||||
harness.awaitServerSocket()
|
||||
val activation = harness.awaitPendingAck()
|
||||
assertEquals("session.activate", activation.method)
|
||||
assertTrue(runBlocking { client.respondClarify("batch", "retry", "q0") }.isFailure)
|
||||
assertTrue(harness.rpcLog.none { it.first == "clarify.respond" })
|
||||
harness.releaseAck(activation, buildJsonObject {
|
||||
put("session_id", "live-1")
|
||||
put("running", true)
|
||||
put("pending_clarify", JsonObject(request + ("answers" to buildJsonObject { put("q0", "accepted") })))
|
||||
})
|
||||
awaitCondition { r.interactions.last().answers["q0"] == "accepted" }
|
||||
assertTrue(runBlocking { client.respondClarify("batch", "overwrite", "q0") }.isFailure)
|
||||
assertTrue(harness.rpcLog.none { it.first == "clarify.respond" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `clarify respond carries request id and answer`() {
|
||||
val r = Recorder()
|
||||
|
||||
@@ -16,6 +16,103 @@ import org.junit.Test
|
||||
*/
|
||||
class GatewayEventMapperTest {
|
||||
|
||||
@Test
|
||||
fun `acknowledgement before reclaim remains in the shared request snapshot`() {
|
||||
val original = mapperWith(Recorder())
|
||||
original.onEvent("clarify.request", obj("""{"request_id":"batch","questions":[
|
||||
{"qid":"q0","question":"First?"},{"qid":"q1","question":"Second?"}]}"""))
|
||||
val detachedSnapshot = requireNotNull(original.currentInteraction)
|
||||
original.acknowledgeClarify("batch", "q0", "first", false)
|
||||
val recovered = mapperWith(Recorder())
|
||||
recovered.restoreInteraction(detachedSnapshot)
|
||||
assertEquals(mapOf("q0" to "first"), recovered.currentInteraction?.answers)
|
||||
recovered.onEvent("message.complete", obj("""{"text":"done"}"""))
|
||||
recovered.acknowledgeClarify("batch", "q1", "second", false)
|
||||
assertTrue(recovered.turnEnded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `expired detached snapshot cannot become pending again`() {
|
||||
val original = mapperWith(Recorder())
|
||||
original.onEvent("clarify.request", obj("""{"request_id":"batch","questions":[{"qid":"q0","question":"First?"}]}"""))
|
||||
val snapshot = requireNotNull(original.currentInteraction)
|
||||
original.acknowledgeClarify("batch", "q0", "ignored", true)
|
||||
val r = Recorder()
|
||||
val recovered = mapperWith(r)
|
||||
recovered.restoreInteraction(snapshot)
|
||||
assertNull(recovered.currentInteraction)
|
||||
assertTrue(r.interactions.isEmpty())
|
||||
assertEquals("batch", r.interactionExpiries.single().requestId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `forwarded acknowledgement cannot touch a newer request incarnation`() {
|
||||
val mapper = mapperWith(Recorder())
|
||||
val request = obj("""{"request_id":"batch","questions":[{"qid":"q0","question":"First?"}]}""")
|
||||
mapper.onEvent("clarify.request", request)
|
||||
val oldOwner = requireNotNull(mapper.currentInteraction).ownershipToken
|
||||
mapper.onEvent("clarify.expire", obj("""{"request_id":"batch"}"""))
|
||||
mapper.onEvent("clarify.request", request)
|
||||
mapper.acknowledgeClarifyOwner("batch", "q0", "stale", true, oldOwner)
|
||||
assertTrue(requireNotNull(mapper.currentInteraction).answers.isEmpty())
|
||||
assertFalse(mapper.turnEnded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `partial acknowledgement holds terminal and merges replay without resurrecting an answer`() {
|
||||
val r = Recorder()
|
||||
val mapper = mapperWith(r)
|
||||
val request = obj("""{"request_id":"batch","questions":[
|
||||
{"qid":"q0","question":"First?"},{"qid":"q1","question":"Second?"}]}""")
|
||||
mapper.onEvent("clarify.request", request)
|
||||
mapper.onEvent("message.complete", obj("""{"text":"done"}"""))
|
||||
mapper.acknowledgeClarify("batch", "q0", "first", false)
|
||||
assertFalse(mapper.turnEnded)
|
||||
assertEquals(mapOf("q0" to "first"), mapper.currentInteraction?.answers)
|
||||
mapper.onEvent("clarify.request", request)
|
||||
assertEquals(mapOf("q0" to "first"), mapper.currentInteraction?.answers)
|
||||
mapper.acknowledgeClarify("old-batch", "q1", "stale", true)
|
||||
assertFalse(mapper.turnEnded)
|
||||
mapper.acknowledgeClarify("batch", "q1", "second", false)
|
||||
assertNull(mapper.currentInteraction)
|
||||
assertTrue(mapper.turnEnded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `batch expiry retires partial progress only for exact request`() {
|
||||
val r = Recorder()
|
||||
val mapper = mapperWith(r)
|
||||
mapper.onEvent("clarify.request", obj("""{"request_id":"batch","questions":[
|
||||
{"qid":"q0","question":"First?"},{"qid":"q1","question":"Second?"}],"answers":{"q0":"done"}}"""))
|
||||
mapper.onEvent("clarify.expire", obj("""{"request_id":"other"}"""))
|
||||
assertEquals("done", mapper.currentInteraction?.answers?.get("q0"))
|
||||
mapper.onEvent("clarify.expire", obj("""{"request_id":"batch"}"""))
|
||||
assertNull(mapper.currentInteraction)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `batch clarify preserves exact qids question order choices and replayed answers`() {
|
||||
val ask = GatewayEventMapper.interactionRequest("clarify.request", obj("""
|
||||
{"request_id":"batch","questions":[
|
||||
{"qid":"choice/a","question":"Which deployment?","choices":["Canary","Immediate"],"multi_select":false},
|
||||
{"qid":"env:b","question":"Which environments?","choices":["Stage","Production"],"multi_select":true}
|
||||
],"answers":{"choice/a":"Canary","foreign":"ignored"}}
|
||||
"""))!!
|
||||
assertEquals(listOf("choice/a", "env:b"), ask.questions.map { it.qid })
|
||||
assertEquals("Which deployment?", ask.questions[0].question)
|
||||
assertEquals(listOf("Stage", "Production"), ask.questions[1].choices)
|
||||
assertTrue(ask.questions[1].multiSelect)
|
||||
assertEquals(mapOf("choice/a" to "Canary"), ask.answers)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `one entry normalized clarify keeps its qid`() {
|
||||
val ask = GatewayEventMapper.interactionRequest("clarify.request", obj("""
|
||||
{"request_id":"one","questions":[{"qid":"q0","question":"Which file?","choices":null}]}
|
||||
"""))!!
|
||||
assertEquals(listOf("q0"), ask.questions.map { it.qid })
|
||||
}
|
||||
|
||||
private class Recorder {
|
||||
val textDeltas = mutableListOf<String>()
|
||||
val interimMessages = mutableListOf<Pair<String, Boolean>>()
|
||||
|
||||
@@ -6,23 +6,29 @@ import org.junit.Test
|
||||
|
||||
class HermesRuntimeBinderSessionDirectoryPolicyTest {
|
||||
@Test
|
||||
fun `session directory can refresh from either standard route owner`() {
|
||||
fun `session directory starts from dashboard publication before Gateway readiness`() {
|
||||
assertTrue(
|
||||
shouldRefreshSessionDirectory(
|
||||
chatReady = true,
|
||||
dashboardRouteResolved = false,
|
||||
dashboardUrl = "",
|
||||
),
|
||||
)
|
||||
assertTrue(
|
||||
shouldRefreshSessionDirectory(
|
||||
chatReady = false,
|
||||
dashboardRouteResolved = true,
|
||||
dashboardUrl = "https://dashboard.example.test",
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
shouldRefreshSessionDirectory(
|
||||
chatReady = false,
|
||||
dashboardRouteResolved = false,
|
||||
dashboardUrl = "",
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
shouldRefreshSessionDirectory(
|
||||
chatReady = false,
|
||||
dashboardUrl = " ",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.semantics.SemanticsActions
|
||||
import androidx.compose.ui.test.hasScrollAction
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performSemanticsAction
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.test.swipeUp
|
||||
import androidx.compose.ui.text.TextLayoutResult
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyBatch
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyQuestion
|
||||
import com.hermesandroid.relay.data.HermesCardInput
|
||||
import com.hermesandroid.relay.data.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.ui.components.MessageBubble
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class ChatBubblePolishScreenshotTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test @Config(qualifiers = "w360dp-h800dp-xhdpi")
|
||||
fun darkConversation() = capture("dark-conversation", "dark", 1f)
|
||||
|
||||
@Test @Config(qualifiers = "w360dp-h800dp-xhdpi")
|
||||
fun lightConversation() = capture("light-conversation", "light", 1f)
|
||||
|
||||
@Test @Config(qualifiers = "w320dp-h568dp-xhdpi")
|
||||
fun narrowLargeText() = capture("narrow-large-text", "dark", 1.5f)
|
||||
|
||||
@Test @Config(qualifiers = "w720dp-h360dp-xhdpi")
|
||||
fun landscape() = capture("landscape", "dark", 1f)
|
||||
|
||||
@Test @Config(qualifiers = "w360dp-h800dp-xhdpi")
|
||||
fun correctionAndTimeShareOneLine() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
MessageBubble(correction(), animationEnabled = false)
|
||||
}
|
||||
}
|
||||
val time = SimpleDateFormat("h:mm a", Locale.US).format(Date(TIMESTAMP))
|
||||
val timeBounds = compose.onNodeWithText(time, useUnmergedTree = true).fetchSemanticsNode().boundsInRoot
|
||||
val status = compose.onNodeWithText("Correction sent", useUnmergedTree = true)
|
||||
val statusBounds = status.fetchSemanticsNode().boundsInRoot
|
||||
assertTrue("Time and correction should share a footer row", kotlin.math.abs(timeBounds.center.y - statusBounds.center.y) <= 2f)
|
||||
val layouts = mutableListOf<TextLayoutResult>()
|
||||
status.performSemanticsAction(SemanticsActions.GetTextLayoutResult) { it(layouts) }
|
||||
assertEquals(1, layouts.single().lineCount)
|
||||
}
|
||||
|
||||
private fun capture(name: String, theme: String, scale: Float) {
|
||||
val card = HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_CLARIFY,
|
||||
title = "Hermes needs clarification",
|
||||
id = "clarify",
|
||||
clarifyBatch = HermesCardClarifyBatch(listOf(
|
||||
HermesCardClarifyQuestion("q0", "Which accent color?", HermesCardInput(HermesCardInput.Kinds.TEXT), "Orange"),
|
||||
HermesCardClarifyQuestion("q1", "Which sections?", HermesCardInput(HermesCardInput.Kinds.CHOICE, multiSelect = true), "[\"Calendar\",\"Tasks\"]"),
|
||||
)),
|
||||
)
|
||||
val messages = listOf(
|
||||
ChatMessage(id = "ask", role = MessageRole.ASSISTANT, content = "", timestamp = TIMESTAMP, cards = listOf(card), clientOnly = true),
|
||||
ChatMessage(id = "reply", role = MessageRole.ASSISTANT, content = "Got both responses in one batch:\n\n- Accent: **Orange**\n- Sections: **Calendar and Tasks**", timestamp = TIMESTAMP),
|
||||
correction(),
|
||||
)
|
||||
compose.setContent {
|
||||
val density = LocalDensity.current
|
||||
CompositionLocalProvider(LocalDensity provides Density(density.density, scale)) {
|
||||
HermesRelayTheme(themePreference = theme) {
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
items(messages.size, key = { messages[it].id }) { index ->
|
||||
MessageBubble(messages[index], showAgentIdentity = false, isFirstInGroup = index == 0 || index == 2,
|
||||
isLastInGroup = index != 0, animationEnabled = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val directory = File("build/ui-evidence/bubble-polish").apply { mkdirs() }
|
||||
compose.onRoot().captureRoboImage(File(directory, "$name-top.png").path)
|
||||
repeat(3) { compose.onNode(hasScrollAction()).performTouchInput { swipeUp() } }
|
||||
compose.onRoot().captureRoboImage(File(directory, "$name-bottom.png").path)
|
||||
}
|
||||
|
||||
private fun correction() = ChatMessage(id = "correction", role = MessageRole.USER, content = "Test", timestamp = TIMESTAMP,
|
||||
deliveryStatus = MessageDeliveryStatus.STEERED)
|
||||
|
||||
companion object { private const val TIMESTAMP = 1_700_000_000_000L }
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.test.hasScrollAction
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.test.swipeUp
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyBatch
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyQuestion
|
||||
import com.hermesandroid.relay.data.HermesCardInput
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.ui.components.MessageBubble
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import java.io.File
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class ClarifyBatchScreenshotTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test @Config(qualifiers = "w320dp-h568dp-xhdpi")
|
||||
fun compactDark() = capture("compact-dark")
|
||||
|
||||
@Test @Config(qualifiers = "w320dp-h568dp-xhdpi")
|
||||
fun compactLightLargeText() = capture("compact-light-font-1_5", theme = "light", scale = 1.5f)
|
||||
|
||||
@Test @Config(qualifiers = "w720dp-h360dp-xhdpi")
|
||||
fun landscape() = capture("landscape", width = 540)
|
||||
|
||||
@Test @Config(qualifiers = "w330dp-h720dp-xhdpi")
|
||||
fun narrowFoldable() = capture("foldable-pane", scale = 1.5f)
|
||||
|
||||
@Test @Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
fun partialProgress() = capture("partial", answered = 1)
|
||||
|
||||
@Test @Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
fun sending() = capture("sending", answered = 1, submitting = true)
|
||||
|
||||
@Test @Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
fun completed() = capture("completed", answered = 2)
|
||||
|
||||
@Test @Config(qualifiers = "w320dp-h568dp-xhdpi")
|
||||
fun expiredPartial() = capture("expired-partial", answered = 1, expired = true)
|
||||
|
||||
private fun capture(
|
||||
name: String, theme: String = "dark", scale: Float = 1f, width: Int = 300,
|
||||
answered: Int = 0, submitting: Boolean = false, expired: Boolean = false,
|
||||
) {
|
||||
val options = listOf(
|
||||
"Keep both systems running while traffic moves in measured stages (Recommended)",
|
||||
"Migrate everything immediately and accept a short maintenance window",
|
||||
"Pause until every downstream consumer has been verified",
|
||||
"Use a reversible canary rollout with automatic rollback thresholds",
|
||||
)
|
||||
val questions = listOf(
|
||||
HermesCardClarifyQuestion("q0", "Which deployment approach should I use for the migration, given the existing clients and the rollback requirements?",
|
||||
HermesCardInput(HermesCardInput.Kinds.CHOICE, options, allowFreeText = true),
|
||||
answer = options[0].takeIf { answered > 0 }),
|
||||
HermesCardClarifyQuestion("q1", "Which environments should receive this change?",
|
||||
HermesCardInput(HermesCardInput.Kinds.CHOICE, listOf("Staging", "Production"), multiSelect = true, allowFreeText = true),
|
||||
answer = "[\"Staging\",\"Production\"]".takeIf { answered > 1 }, submitting = submitting),
|
||||
)
|
||||
val card = HermesCard(type = HermesCard.BuiltInTypes.ASK_CLARIFY, title = "Hermes needs clarification",
|
||||
id = "batch", clarifyBatch = HermesCardClarifyBatch(questions, expiresAtMillis = if (expired) 1L else null))
|
||||
compose.setContent {
|
||||
val density = LocalDensity.current
|
||||
CompositionLocalProvider(LocalDensity provides Density(density.density, scale)) {
|
||||
HermesRelayTheme(themePreference = theme) {
|
||||
LazyColumn(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(10.dp)) {
|
||||
item {
|
||||
MessageBubble(
|
||||
message = ChatMessage(id = "batch-message", role = MessageRole.ASSISTANT, content = "",
|
||||
timestamp = 0L, cards = listOf(card), clientOnly = true),
|
||||
maxBubbleWidth = width.dp, showTimestamps = false, animationEnabled = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val directory = File("build/ui-evidence/clarify-batch").apply { mkdirs() }
|
||||
compose.onRoot().captureRoboImage(File(directory, "$name-top.png").path)
|
||||
repeat(4) { compose.onNode(hasScrollAction()).performTouchInput { swipeUp() } }
|
||||
compose.onRoot().captureRoboImage(File(directory, "$name-bottom.png").path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.ui.components.InjectedContextSheet
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [34], qualifiers = "w360dp-h720dp-xhdpi")
|
||||
class InjectedContextSheetTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun gatewayPreviewLabelsUnsupportedContextWithoutShowingPhonePreamble() {
|
||||
showPreview("gateway")
|
||||
compose.onAllNodesWithText(
|
||||
"Not sent in Gateway chat. This connection does not support extra per-turn context.",
|
||||
).assertCountEquals(2)
|
||||
compose.onNodeWithText("Hermes-Relay Android app", substring = true).assertDoesNotExist()
|
||||
compose.onNodeWithText("Server-side persona").assertExists()
|
||||
compose.onRoot().captureRoboImage("build/ui-regression/injected-context-gateway.png")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun apiOnlyPreviewShowsThePreparedMobileContext() {
|
||||
showPreview("sessions")
|
||||
compose.onNodeWithText("Hermes-Relay Android app", substring = true).assertExists()
|
||||
compose.onNodeWithText("Not sent in Gateway chat", substring = true).assertDoesNotExist()
|
||||
compose.onRoot().captureRoboImage("build/ui-regression/injected-context-api.png")
|
||||
}
|
||||
|
||||
private fun showPreview(endpoint: String) {
|
||||
val preview = ChatViewModel().apply { streamingEndpoint = endpoint }.previewInjectedContext()
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
InjectedContextSheet(context = preview, onDismiss = {})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsOn
|
||||
import androidx.compose.ui.test.assertIsOff
|
||||
import androidx.compose.ui.test.assertIsSelected
|
||||
import androidx.compose.ui.test.assertHeightIsAtLeast
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.junit.Assert.assertEquals
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.ProfilePresentation
|
||||
import com.hermesandroid.relay.ui.components.ProfileSwitcherSheet
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import java.io.File
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
class ProfileIdentityScreenshotTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test fun profileSwitcher() = render("profile-switcher")
|
||||
|
||||
@Test fun enlargedText() = render("profile-switcher-large-text", fontScale = 1.5f)
|
||||
|
||||
@Test fun longName() = render("profile-switcher-long-name", fontScale = 1.5f,
|
||||
displayName = "Research and planning assistant for the whole team")
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w720dp-h360dp-xhdpi")
|
||||
fun landscape() = render("profile-switcher-landscape")
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w840dp-h720dp-xhdpi")
|
||||
fun expanded() = render("profile-switcher-expanded")
|
||||
|
||||
private fun render(file: String, fontScale: Float = 1f, displayName: String = "Guide") {
|
||||
RuntimeEnvironment.setFontScale(fontScale)
|
||||
val agent = Profile(name = "guide", model = "example-model", displayName = displayName)
|
||||
val vm = mockk<ConnectionViewModel>(relaxed = true)
|
||||
every { vm.profileIconFlow(any()) } returns MutableStateFlow(null)
|
||||
every { vm.serverDefaultDisplayProfile } returns MutableStateFlow(agent)
|
||||
val selected = mutableStateOf<Profile?>(null)
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(LocalDensity provides Density(LocalDensity.current.density, fontScale)) {
|
||||
ProfileSwitcherSheet(vm, listOf(Profile("default", "root-model"), agent), selected.value,
|
||||
selected.value ?: agent, ProfilePresentation(), false, true, { selected.value = it }, {}, {})
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onAllNodesWithText(displayName, substring = false).assertCountEquals(1)
|
||||
compose.onNodeWithText("Follow server default").assertIsDisplayed().assertIsOn()
|
||||
.assertHeightIsAtLeast(48.dp)
|
||||
val output = File("build/ui-evidence/$file.png")
|
||||
output.parentFile?.mkdirs()
|
||||
compose.onRoot().captureRoboImage(output.absolutePath)
|
||||
compose.onNodeWithText("Follow server default").performClick()
|
||||
compose.runOnIdle { assertEquals("guide", selected.value?.name) }
|
||||
compose.onNodeWithText("Follow server default").assertIsOff()
|
||||
compose.onNodeWithText("Follow server default").performClick()
|
||||
compose.runOnIdle { assertEquals(null, selected.value) }
|
||||
// Scrollable even in landscape or at enlarged text sizes.
|
||||
compose.onNodeWithText("default", substring = false).performScrollTo().performClick()
|
||||
compose.runOnIdle { assertEquals("default", selected.value?.name) }
|
||||
compose.onNodeWithText("default", substring = false).assertIsSelected()
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@ import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.RelayEndpoint
|
||||
import com.hermesandroid.relay.data.VoicePresentationMode
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.viewmodel.ChatRuntimeStatus
|
||||
import com.hermesandroid.relay.ui.screens.shouldOwnVisibleGateway
|
||||
import com.hermesandroid.relay.viewmodel.ChatConnectState
|
||||
import com.hermesandroid.relay.viewmodel.ChatRuntimeStatus
|
||||
import com.hermesandroid.relay.viewmodel.ChatTransportPath
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.viewmodel.resolveChatConnectState
|
||||
@@ -196,6 +197,50 @@ class RelayAppStatusTest {
|
||||
assertEquals(ChatRuntimeStatus.Connecting, status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreground Gateway owns cold observation before gateway ready`() {
|
||||
assertTrue(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = true,
|
||||
isGatewayTransport = true,
|
||||
gatewayAvailability = GatewayAvailability.Unknown,
|
||||
),
|
||||
)
|
||||
assertTrue(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = true,
|
||||
isGatewayTransport = true,
|
||||
gatewayAvailability = GatewayAvailability.Unreachable,
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = false,
|
||||
isGatewayTransport = true,
|
||||
gatewayAvailability = GatewayAvailability.Unknown,
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = true,
|
||||
isGatewayTransport = false,
|
||||
gatewayAvailability = GatewayAvailability.Unknown,
|
||||
),
|
||||
)
|
||||
listOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unsupported,
|
||||
).forEach { terminal ->
|
||||
assertFalse(
|
||||
shouldOwnVisibleGateway(
|
||||
appForeground = true,
|
||||
isGatewayTransport = true,
|
||||
gatewayAvailability = terminal,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `dashboard sign-out is not masked by a reachable sibling API`() {
|
||||
val status = resolveAppChatRuntimeStatus(
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.assertIsSelected
|
||||
import androidx.compose.ui.test.assertIsFocused
|
||||
import androidx.compose.ui.test.junit4.StateRestorationTester
|
||||
import androidx.compose.ui.test.performKeyInput
|
||||
import androidx.compose.ui.test.performSemanticsAction
|
||||
import androidx.compose.ui.test.pressKey
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.input.InputModeManager
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.semantics.SemanticsActions
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performImeAction
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyBatch
|
||||
import com.hermesandroid.relay.data.HermesCardClarifyQuestion
|
||||
import com.hermesandroid.relay.data.HermesCardInput
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
class ClarifyBatchInteractionTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test fun draftsAndSelectionSurviveSavedStateAndFocusFollowsQuestionOrder() {
|
||||
val restoration = StateRestorationTester(compose)
|
||||
lateinit var inputMode: InputModeManager
|
||||
restoration.setContent {
|
||||
inputMode = LocalInputModeManager.current
|
||||
MaterialTheme {
|
||||
HermesCardBubble(card().copy(clarifyBatch = HermesCardClarifyBatch(listOf(question))),
|
||||
"batch", emptyList(), { _, _ -> }, { _, _ -> })
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Stage").performClick()
|
||||
compose.onNodeWithContentDescription("Other (type your answer)…").performTextInput("Keep rollback")
|
||||
restoration.emulateSavedInstanceStateRestore()
|
||||
compose.onNodeWithText("Stage").assertIsSelected()
|
||||
compose.onNodeWithText("Keep rollback").assertExists()
|
||||
compose.runOnIdle { inputMode.requestInputMode(InputMode.Keyboard) }
|
||||
compose.onNodeWithText("Stage").performSemanticsAction(SemanticsActions.RequestFocus) { it() }
|
||||
compose.onNodeWithText("Stage").assertIsFocused()
|
||||
compose.onNodeWithText("Stage").performKeyInput { pressKey(Key.Tab) }
|
||||
compose.onNodeWithText("Production").assertIsFocused()
|
||||
}
|
||||
|
||||
@Test fun multiSelectImeRetryKeepsChoicesAndDraftAndDisablesDuplicateActions() {
|
||||
var submitting by mutableStateOf(false)
|
||||
val answers = mutableListOf<Pair<String, String>>()
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
HermesCardBubble(
|
||||
card = card().copy(clarifyBatch = HermesCardClarifyBatch(listOf(question.copy(submitting = submitting)))),
|
||||
cardKey = "batch", dispatches = emptyList(), onActionTap = { _, _ -> },
|
||||
onInputSubmit = { key, value -> answers += key to value; submitting = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Submit").assertIsNotEnabled()
|
||||
compose.onNodeWithContentDescription("Other (type your answer)…").apply {
|
||||
performTextInput(" ")
|
||||
performImeAction()
|
||||
}
|
||||
compose.runOnIdle { assertEquals(0, answers.size) }
|
||||
compose.onNodeWithText("Stage").performClick().assertIsSelected()
|
||||
compose.onNodeWithContentDescription("Other (type your answer)…").apply {
|
||||
performTextInput("custom")
|
||||
performImeAction()
|
||||
}
|
||||
compose.onNodeWithText("Stage").assertIsNotEnabled()
|
||||
compose.onNodeWithText("Submit").assertIsNotEnabled()
|
||||
compose.runOnIdle {
|
||||
assertEquals(listOf("qid-key" to "[\"Stage\",\"custom\"]"), answers)
|
||||
submitting = false
|
||||
}
|
||||
compose.onNodeWithText("Stage").assertIsSelected()
|
||||
compose.onNodeWithText("Submit").performClick()
|
||||
compose.runOnIdle { assertEquals(answers[0], answers[1]) }
|
||||
}
|
||||
|
||||
@Test fun confirmedQuestionAdvancesAndExpiredBatchRetainsAnswersWithoutInputs() {
|
||||
var batch by mutableStateOf(HermesCardClarifyBatch(listOf(question,
|
||||
question.copy(key = "second", question = "Anything else?", input = HermesCardInput(HermesCardInput.Kinds.TEXT, allowFreeText = true)))))
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
HermesCardBubble(card().copy(clarifyBatch = batch), "batch", emptyList(), { _, _ -> }, { _, _ -> })
|
||||
}
|
||||
}
|
||||
compose.runOnIdle { batch = batch.copy(questions = batch.questions.map { if (it.key == "qid-key") it.copy(answer = "[\"Stage\"]") else it }) }
|
||||
compose.onNodeWithText("Question 2 of 2").assertExists()
|
||||
compose.onNodeWithText("Anything else?").assertExists()
|
||||
compose.onNodeWithText("Stage").assertDoesNotExist()
|
||||
compose.runOnIdle { batch = batch.copy(expiresAtMillis = 1L) }
|
||||
compose.onNodeWithText("This request has ended").assertExists()
|
||||
compose.onNodeWithText("Stage").assertExists()
|
||||
compose.onNodeWithContentDescription("Type an answer…").assertDoesNotExist()
|
||||
}
|
||||
|
||||
private val question = HermesCardClarifyQuestion("qid-key", "Which environments?",
|
||||
HermesCardInput(HermesCardInput.Kinds.CHOICE, listOf("Stage", "Production"), multiSelect = true, allowFreeText = true))
|
||||
private fun card() = HermesCard(HermesCard.BuiltInTypes.ASK_CLARIFY, title = "Hermes needs clarification")
|
||||
}
|
||||
@@ -9,6 +9,30 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ProfileShelfPolicyTest {
|
||||
@Test
|
||||
fun resolvedDefaultGroupsOnlyExactIdentityAndRetainsSelectedRequestKey() {
|
||||
val victor = Profile("victor", "", displayName = "Victor")
|
||||
val duplicate = Profile("other", "", displayName = "Victor")
|
||||
val roster = listOf(Profile("default", ""), victor, duplicate)
|
||||
for (selected in listOf(null, "victor", "default", "other")) {
|
||||
val choices = ProfileShelfPolicy.choices(roster, ProfilePresentation(), selected, "victor")
|
||||
assertEquals(3, choices.size)
|
||||
assertTrue(choices.any { ProfileShelfPolicy.isSelected(it, selected) })
|
||||
assertTrue(choices.any { it.key == "default" })
|
||||
assertTrue(choices.any { it.key == "other" })
|
||||
val grouped = choices.first { it.isServerDefault || it.key == "victor" }
|
||||
assertEquals(if (selected == "victor") "victor" else null, grouped.profile?.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownDefaultNeverCollapsesRootOrNamesWithMatchingLabels() {
|
||||
val roster = listOf(Profile("default", ""), Profile("one", "", displayName = "Same"),
|
||||
Profile("two", "", displayName = "Same"))
|
||||
assertEquals(4, ProfileShelfPolicy.choices(roster, ProfilePresentation(), null).size)
|
||||
assertEquals(4, ProfileShelfPolicy.choices(roster, ProfilePresentation(), null, "missing").size)
|
||||
}
|
||||
|
||||
private val profiles = listOf(
|
||||
Profile(name = "default", model = "root"),
|
||||
Profile(name = "alpha", model = "a"),
|
||||
|
||||
@@ -182,6 +182,55 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coldGatewayClientBeforeVisibilityOpensObservationWithoutControlRpc() {
|
||||
viewModel.setChatVisible(false)
|
||||
replaceGatewayClient(ticketTimeoutMs = 5_000L)
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"prompt.submit",
|
||||
"session.interrupt",
|
||||
)
|
||||
val baseline = controlMethods.associateWith { method ->
|
||||
gatewayHarness.rpcLog.count { it.first == method }
|
||||
}
|
||||
val ticketMintsBefore = gatewayHarness.ticketMints.get()
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
|
||||
awaitCondition { gatewayClient.connectionState.value == GatewayConnectionState.Ready }
|
||||
assertEquals(ticketMintsBefore + 1, gatewayHarness.ticketMints.get())
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(baseline.getValue(method), gatewayHarness.rpcLog.count { it.first == method })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coldGatewayVisibilityBeforeClientBindingOpensObservationWithoutControlRpc() {
|
||||
viewModel.setChatVisible(false)
|
||||
replaceGatewayClient(ticketTimeoutMs = 5_000L, bind = false)
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"prompt.submit",
|
||||
"session.interrupt",
|
||||
)
|
||||
val baseline = controlMethods.associateWith { method ->
|
||||
gatewayHarness.rpcLog.count { it.first == method }
|
||||
}
|
||||
val ticketMintsBefore = gatewayHarness.ticketMints.get()
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
awaitCondition { gatewayClient.connectionState.value == GatewayConnectionState.Ready }
|
||||
assertEquals(ticketMintsBefore + 1, gatewayHarness.ticketMints.get())
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(baseline.getValue(method), gatewayHarness.rpcLog.count { it.first == method })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun offlineGatewaySendPublishesRetryableFailureAndKeepsPrompt() {
|
||||
DiagnosticsLog.clear()
|
||||
@@ -1687,6 +1736,24 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals(false, gatewayClient.sessionModelProvider()?.fast)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun injectedContextPreviewMatchesBareGatewayPayload() {
|
||||
viewModel.appContextSettings = com.hermesandroid.relay.util.AppContextSettings(
|
||||
master = true, battery = true, currentApp = true,
|
||||
)
|
||||
val preview = viewModel.previewInjectedContext()
|
||||
assertFalse(preview.perTurnContextSupported)
|
||||
assertNull(preview.combinedSystemMessage)
|
||||
|
||||
viewModel.sendMessage("Keep this message unchanged")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
val submitted = gatewayHarness.rpcLog.last { it.first == "prompt.submit" }.second
|
||||
assertEquals(JsonPrimitive("Keep this message unchanged"), submitted["text"])
|
||||
assertFalse(submitted.containsKey("system_message"))
|
||||
assertFalse(submitted.containsKey("surface"))
|
||||
assertEquals(0, apiCompletionsRequestCount.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dashboardOnlyConnectionCanSendWithoutApiClient() {
|
||||
viewModel.updateGatewayClient(null)
|
||||
@@ -2680,6 +2747,121 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition { viewModel.pendingAsk.value == null }
|
||||
}
|
||||
|
||||
private fun presentBatchClarify(requestId: String = "batch") {
|
||||
serverWs.send(gatewayHarness.eventFrame("clarify.request",
|
||||
gatewayHarness.json.parseToJsonElement("""{"request_id":"$requestId","questions":[
|
||||
{"qid":"route/a","question":"Which deployment?","choices":["Canary","Immediate"]},
|
||||
{"qid":"environment:b","question":"Which environments?","choices":["Stage","Production"],"multi_select":true}
|
||||
]}""") as kotlinx.serialization.json.JsonObject, "live-resumed"))
|
||||
awaitCondition { viewModel.pendingAsk.value?.ask?.requestId == requestId }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun batchClarifyInFlightAnswerSurvivesSessionRoundTripWithoutDuplicateRpc() {
|
||||
val contextKey = AgentDisplay.profileContextKey("connection-a", null)
|
||||
val store = MemoryCheckpointStore()
|
||||
viewModel.setChatTurnCheckpointStore(store)
|
||||
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
|
||||
viewModel.sendMessage("Ask before continuing")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
presentBatchClarify()
|
||||
val pending = requireNotNull(viewModel.pendingAsk.value)
|
||||
val key = com.hermesandroid.relay.data.clarifyQuestionCardKey(pending.cardKey, "route/a")
|
||||
gatewayHarness.suppressAckMethods += "clarify.respond"
|
||||
viewModel.answerAsk(pending.messageId, key, "Canary")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
val ack = gatewayHarness.awaitPendingAck()
|
||||
viewModel.switchSession("other-session")
|
||||
awaitCondition { handler.currentSessionId.value == "other-session" && store.checkpoint?.pendingAsk != null }
|
||||
gatewayHarness.recoveryRunning = true
|
||||
viewModel.switchSession(STORED_SESSION_ID)
|
||||
awaitCondition { viewModel.pendingAsk.value != null && handler.currentSessionId.value == STORED_SESSION_ID }
|
||||
val restored = requireNotNull(viewModel.pendingAsk.value)
|
||||
assertEquals(pending.ownerId, restored.ownerId)
|
||||
viewModel.answerAsk(restored.messageId, key, "Canary")
|
||||
gatewayHarness.releaseAck(ack)
|
||||
awaitCondition { viewModel.pendingAsk.value?.ask?.answers?.get("route/a") == "Canary" }
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "clarify.respond" })
|
||||
gatewayHarness.suppressAckMethods -= "clarify.respond"
|
||||
viewModel.answerAsk(restored.messageId,
|
||||
com.hermesandroid.relay.data.clarifyQuestionCardKey(restored.cardKey, "environment:b"), "[\"Stage\"]")
|
||||
awaitCondition { viewModel.pendingAsk.value == null }
|
||||
serverWs.send(gatewayHarness.eventFrame("message.complete", buildJsonObject { put("text", "All answers received") }, "live-resumed"))
|
||||
awaitCondition { !handler.isStreaming.value && !gatewayClient.hasActiveTurn() }
|
||||
assertEquals(2, gatewayHarness.rpcLog.count { it.first == "clarify.respond" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun batchClarifyKeepsPartialProgressRejectsDuplicateAndNeverSendsChatAnswers() {
|
||||
viewModel.sendMessage("Ask a batch")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
presentBatchClarify()
|
||||
val pending = requireNotNull(viewModel.pendingAsk.value)
|
||||
val key = com.hermesandroid.relay.data.clarifyQuestionCardKey(pending.cardKey, "route/a")
|
||||
gatewayHarness.suppressAckMethods += "clarify.respond"
|
||||
viewModel.answerAsk(pending.messageId, key, "Canary")
|
||||
viewModel.answerAsk(pending.messageId, key, "Canary")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
val ack = gatewayHarness.awaitPendingAck()
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "clarify.respond" })
|
||||
gatewayHarness.releaseAck(ack)
|
||||
awaitCondition { viewModel.pendingAsk.value?.ask?.answers?.get("route/a") == "Canary" }
|
||||
presentBatchClarify()
|
||||
viewModel.answerAsk(pending.messageId, key, "Immediate")
|
||||
assertEquals("Canary", viewModel.pendingAsk.value?.ask?.answers?.get("route/a"))
|
||||
gatewayHarness.suppressAckMethods -= "clarify.respond"
|
||||
val secondKey = com.hermesandroid.relay.data.clarifyQuestionCardKey(pending.cardKey, "environment:b")
|
||||
viewModel.answerAsk(pending.messageId, secondKey, "[\"Stage\",\"Production\"]")
|
||||
awaitCondition { viewModel.pendingAsk.value == null }
|
||||
val responses = gatewayHarness.rpcLog.filter { it.first == "clarify.respond" }.map { it.second }
|
||||
assertEquals(listOf(JsonPrimitive("route/a"), JsonPrimitive("environment:b")), responses.map { it["question_id"] })
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "prompt.submit" })
|
||||
val card = handler.messages.value.single { it.id == pending.messageId }.cards.single()
|
||||
assertEquals(listOf("Canary", "[\"Stage\",\"Production\"]"), card.clarifyBatch?.questions?.map { it.answer })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun batchClarifyFailedRpcCanRetryAndWhitespaceCannotSubmit() {
|
||||
viewModel.sendMessage("Ask a batch")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
presentBatchClarify()
|
||||
val pending = requireNotNull(viewModel.pendingAsk.value)
|
||||
val key = com.hermesandroid.relay.data.clarifyQuestionCardKey(pending.cardKey, "route/a")
|
||||
viewModel.answerAsk(pending.messageId, key, " ")
|
||||
assertTrue(gatewayHarness.rpcLog.none { it.first == "clarify.respond" })
|
||||
gatewayHarness.rpcErrors["clarify.respond"] = 5030 to "Try again"
|
||||
viewModel.answerAsk(pending.messageId, key, "Canary")
|
||||
awaitCondition { gatewayHarness.rpcLog.any { it.first == "clarify.respond" } &&
|
||||
handler.messages.value.single { it.id == pending.messageId }.cards.single().clarifyBatch?.questions?.first()?.submitting == false }
|
||||
assertTrue(requireNotNull(viewModel.pendingAsk.value).ask.answers.isEmpty())
|
||||
gatewayHarness.rpcErrors.remove("clarify.respond")
|
||||
viewModel.answerAsk(pending.messageId, key, " custom route ")
|
||||
awaitCondition { viewModel.pendingAsk.value?.ask?.answers?.get("route/a") == "custom route" }
|
||||
assertEquals(2, gatewayHarness.rpcLog.count { it.first == "clarify.respond" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staleExpiredBatchResponseCannotRetireReusedRequestId() {
|
||||
viewModel.sendMessage("Ask a batch")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
presentBatchClarify()
|
||||
val pending = requireNotNull(viewModel.pendingAsk.value)
|
||||
gatewayHarness.suppressAckMethods += "clarify.respond"
|
||||
viewModel.answerAsk(pending.messageId, com.hermesandroid.relay.data.clarifyQuestionCardKey(pending.cardKey, "route/a"), "Canary")
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
val ack = gatewayHarness.awaitPendingAck()
|
||||
serverWs.send(gatewayHarness.eventFrame("clarify.expire", buildJsonObject { put("request_id", "batch") }, "live-resumed"))
|
||||
awaitCondition { viewModel.pendingAsk.value == null }
|
||||
presentBatchClarify()
|
||||
val newOwner = requireNotNull(viewModel.pendingAsk.value).ownerId
|
||||
gatewayHarness.releaseAck(ack, buildJsonObject { put("status", "expired") })
|
||||
gatewayHarness.suppressAckMethods -= "clarify.respond"
|
||||
val current = requireNotNull(viewModel.pendingAsk.value)
|
||||
viewModel.answerAsk(current.messageId, com.hermesandroid.relay.data.clarifyQuestionCardKey(current.cardKey, "route/a"), "Immediate")
|
||||
awaitCondition { viewModel.pendingAsk.value?.ask?.answers?.get("route/a") == "Immediate" }
|
||||
assertEquals(newOwner, viewModel.pendingAsk.value?.ownerId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun authoritativeClarifyExpiryCollapsesCardAndRejectsLateAction() {
|
||||
viewModel.sendMessage("Ask a question")
|
||||
@@ -4322,7 +4504,10 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
),
|
||||
)
|
||||
|
||||
private fun replaceGatewayClient(ticketTimeoutMs: Long): GatewayChatClient {
|
||||
private fun replaceGatewayClient(
|
||||
ticketTimeoutMs: Long,
|
||||
bind: Boolean = true,
|
||||
): GatewayChatClient {
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
@@ -4340,7 +4525,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { Math.nextDown(1.0) },
|
||||
)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
if (bind) viewModel.updateGatewayClient(gatewayClient)
|
||||
return gatewayClient
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.util.AppContextSettings
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class InjectedContextTest {
|
||||
@Test
|
||||
fun gatewayPreviewExcludesPhoneContextEvenWhenSharingIsEnabled() {
|
||||
val viewModel = ChatViewModel().apply {
|
||||
streamingEndpoint = "gateway"
|
||||
appContextSettings = AppContextSettings(master = true, battery = true, currentApp = true)
|
||||
setSelectedProfileProvider { Profile(name = "writer", model = "test-model", systemMessage = "Profile persona") }
|
||||
}
|
||||
|
||||
val preview = viewModel.previewInjectedContext()
|
||||
|
||||
assertFalse(preview.perTurnContextSupported)
|
||||
assertTrue(preview.personaOwnedServerSide)
|
||||
assertNull(preview.personaPrompt)
|
||||
assertNull(preview.appContext)
|
||||
assertNull(preview.interfaceContext)
|
||||
assertNull(preview.mediaCapability)
|
||||
assertNull(preview.combinedSystemMessage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun apiOnlyTransportsRetainOptedInPhoneContextAndMasterOffRemovesIt() {
|
||||
for (endpoint in listOf("sessions", "runs", "completions")) {
|
||||
val viewModel = ChatViewModel().apply { streamingEndpoint = endpoint }
|
||||
val enabled = viewModel.previewInjectedContext()
|
||||
assertTrue(enabled.perTurnContextSupported)
|
||||
assertFalse(enabled.personaOwnedServerSide)
|
||||
assertTrue(enabled.appContext!!.contains("Hermes-Relay Android app"))
|
||||
assertEquals(enabled.appContext, enabled.combinedSystemMessage)
|
||||
|
||||
viewModel.appContextSettings = AppContextSettings(master = false, battery = true, currentApp = true)
|
||||
val disabled = viewModel.previewInjectedContext()
|
||||
assertNull(disabled.appContext)
|
||||
assertNull(disabled.combinedSystemMessage)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun changingTransportRebuildsPreviewWithoutChangingSharingPreference() {
|
||||
val viewModel = ChatViewModel().apply { streamingEndpoint = "sessions" }
|
||||
val apiPreview = viewModel.previewInjectedContext()
|
||||
viewModel.streamingEndpoint = "gateway"
|
||||
assertNull(viewModel.previewInjectedContext().appContext)
|
||||
assertTrue(viewModel.appContextSettings.master)
|
||||
viewModel.streamingEndpoint = "sessions"
|
||||
assertEquals(apiPreview.appContext, viewModel.previewInjectedContext().appContext)
|
||||
}
|
||||
}
|
||||
@@ -250,6 +250,48 @@ class ProfileControllerLockTest {
|
||||
Thread.sleep(100)
|
||||
|
||||
assertEquals("newer", controller.effectiveSessionProfileName.value)
|
||||
assertEquals("newer", awaitFlow(controller.serverDefaultDisplayProfile) { it?.name == "newer" }?.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectionSwitchRejectsOldDefaultIdentity() {
|
||||
dashboardUrl = "https://dashboard.example"
|
||||
val started = CompletableDeferred<Unit>()
|
||||
val old = CompletableDeferred<DashboardProfileScope>()
|
||||
coEvery { dashboardClient.getActiveProfileScope() } coAnswers {
|
||||
started.complete(Unit)
|
||||
Result.success(old.await())
|
||||
}
|
||||
controller.refreshDashboardProfileScope()
|
||||
runBlocking { withTimeout(5_000) { started.await() } }
|
||||
controller.resetForConnectionSwitch()
|
||||
activeConnectionId.value = "other-connection"
|
||||
coEvery { dashboardClient.getActiveProfileScope() } returns Result.success(
|
||||
DashboardProfileScope(active = "other", current = "default"))
|
||||
controller.refreshDashboardProfileScope()
|
||||
assertEquals("other", awaitFlow(controller.serverDefaultDisplayProfile) { it?.name == "other" }?.name)
|
||||
old.complete(DashboardProfileScope(active = "victor", current = "default"))
|
||||
assertEquals("other", awaitFlow(controller.effectiveSessionProfileName) { it == "other" })
|
||||
assertNull(controller.selectedProfile.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unresolvedDefaultDoesNotBorrowRootAvatarFromGatewayRoster() = runBlocking {
|
||||
gatewayClient = mockk(relaxed = true)
|
||||
coEvery { gatewayClient!!.petInfo(any(), any()) } returns Result.failure(
|
||||
IllegalStateException("Pet metadata temporarily unavailable"))
|
||||
coEvery { gatewayClient!!.listProfiles() } returns Result.success(
|
||||
listOf(literalDefault.copy(isDefault = true, hasAvatar = true)))
|
||||
coEvery { gatewayClient!!.getProfileAvatar("default") } returns Result.failure(
|
||||
IllegalStateException("Avatar temporarily unavailable"))
|
||||
controller.refreshGatewayProfiles()
|
||||
awaitFlow(controller.agentProfiles) { it.any { profile -> profile.name == "default" } }
|
||||
controller.profileIconStore.setServerAvatar(connectionId, "default", "root-avatar.png")
|
||||
assertNull(controller.profileIconFlow(null).first())
|
||||
assertEquals("root-avatar.png", controller.profileIconFlow("default").first())
|
||||
assertNull(controller.serverDefaultDisplayProfile.value)
|
||||
controller.clearSharedProfileAvatar()
|
||||
coVerify(exactly = 0) { gatewayClient!!.clearProfileAvatar(any()) }
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -352,6 +394,7 @@ class ProfileControllerLockTest {
|
||||
|
||||
assertEquals("pinned", awaitFlow(controller.effectiveSessionProfileName) { it == "pinned" })
|
||||
assertEquals(pinned, awaitFlow(controller.effectiveDisplayProfile) { it?.name == "pinned" })
|
||||
assertEquals(pinned, awaitFlow(controller.serverDefaultDisplayProfile) { it?.name == "pinned" })
|
||||
assertEquals("default", controller.serverDefaultProfileScope.value?.current)
|
||||
assertTrue(awaitFlow(controller.selectionSettled) { it })
|
||||
runBlocking { controller.listProfileScopedSessions()?.getOrThrow() }
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.hermesandroid.relay.voice
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Intent
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.mockkObject
|
||||
import io.mockk.spyk
|
||||
import io.mockk.unmockkAll
|
||||
import io.mockk.verify
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
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 = [35])
|
||||
class VoiceOverlayForegroundServiceTest {
|
||||
private val host = mockk<VoiceOverlayHost>(relaxed = true)
|
||||
private lateinit var service: VoiceOverlayForegroundService
|
||||
@Before fun setup() {
|
||||
mockkObject(VoiceOverlayHost.Companion)
|
||||
every { VoiceOverlayHost.peek() } returns host
|
||||
every { host.sessionId } returns 7L
|
||||
every { host.canStart(7L) } returns true
|
||||
every { host.canContinue(7L) } returns true
|
||||
every { host.onServiceReady(7L) } returns true
|
||||
service = Robolectric.buildService(VoiceOverlayForegroundService::class.java).create().get()
|
||||
}
|
||||
@After fun cleanup() { service.onDestroy(); unmockkAll() }
|
||||
private fun command(action: String, id: Long = 7L) = Intent().setAction(action)
|
||||
.putExtra(VoiceOverlayForegroundService.EXTRA_SESSION_ID, id)
|
||||
|
||||
@Test fun notificationIsPostedBeforeWindowReadiness() {
|
||||
every { host.onServiceReady(7L) } answers {
|
||||
assertNotNull(shadowOf(service).lastForegroundNotification)
|
||||
true
|
||||
}
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
verify(exactly = 1) { host.onServiceReady(7L) }
|
||||
}
|
||||
@Test fun unownedOrRestartIntentNeverPromotesService() {
|
||||
service.onStartCommand(null, 0, 1)
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START, 8), 0, 2)
|
||||
assertNull(shadowOf(service).lastForegroundNotification)
|
||||
verify(exactly = 0) { host.onServiceReady(any()) }
|
||||
}
|
||||
@Test fun oldNotificationCannotStopCurrentSession() {
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_STOP, 6), 0, 2)
|
||||
verify(exactly = 0) { host.exitVoiceSession(any()) }
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_STOP), 0, 3)
|
||||
verify(exactly = 1) { host.exitVoiceSession(7L) }
|
||||
}
|
||||
@Test fun windowFailureEndsVoiceInsteadOfLeavingUnprotectedCapture() {
|
||||
every { host.onServiceReady(7L) } returns false
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
verify(exactly = 1) { host.exitVoiceSession(7L) }
|
||||
}
|
||||
@Test fun taskRemovalEndsVoice() {
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
service.onTaskRemoved(null)
|
||||
verify(exactly = 1) { host.exitVoiceSession(7L) }
|
||||
}
|
||||
|
||||
@Test fun permissionLossEndsVoiceAtTheNextAccessCheck() {
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
every { host.canContinue(7L) } returns false
|
||||
shadowOf(android.os.Looper.getMainLooper()).idle()
|
||||
verify(exactly = 1) { host.exitVoiceSession(7L) }
|
||||
}
|
||||
|
||||
@Test fun screenOffEndsVoiceWithoutWaitingForPolling() {
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
service.sendBroadcast(Intent(Intent.ACTION_SCREEN_OFF))
|
||||
shadowOf(android.os.Looper.getMainLooper()).idle()
|
||||
verify(exactly = 1) { host.exitVoiceSession(7L) }
|
||||
}
|
||||
|
||||
@Test fun failedForegroundPromotionNeverAttachesWindow() {
|
||||
service = spyk(service)
|
||||
every { service.startForeground(any(), any(), any()) } throws SecurityException("denied")
|
||||
service.onStartCommand(command(VoiceOverlayForegroundService.ACTION_START), 0, 1)
|
||||
verify(exactly = 0) { host.onServiceReady(any()) }
|
||||
verify(exactly = 1) { host.exitVoiceSession(7L) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.hermesandroid.relay.voice
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import com.hermesandroid.relay.viewmodel.VoiceUiState
|
||||
import io.mockk.every
|
||||
import io.mockk.mockkObject
|
||||
import io.mockk.unmockkAll
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = Application::class, sdk = [35])
|
||||
class VoiceOverlayLifecycleTest {
|
||||
private lateinit var host: VoiceOverlayHost
|
||||
private val owner = object : LifecycleOwner {
|
||||
override val lifecycle = LifecycleRegistry(this)
|
||||
}
|
||||
private var exits = 0
|
||||
private var access = VoiceOverlayAccess(true, true, true, true)
|
||||
private val state = MutableStateFlow(VoiceUiState(voiceMode = true))
|
||||
|
||||
@Before fun setup() {
|
||||
mockkObject(VoiceOverlayAccess.Companion)
|
||||
every { VoiceOverlayAccess.read(any()) } answers { access }
|
||||
host = VoiceOverlayHost(RuntimeEnvironment.getApplication())
|
||||
owner.lifecycle.currentState = Lifecycle.State.RESUMED
|
||||
}
|
||||
@After fun cleanup() { host.hide(); unmockkAll() }
|
||||
|
||||
private fun session() = VoiceOverlaySession(state, provider = null, model = null, voice = null,
|
||||
profileName = "Test", configScope = null, outputEnabled = true, fallbackEnabled = false,
|
||||
onStartListening = {}, onStopListening = {}, onInterrupt = {}, onPauseAutoMode = {},
|
||||
onReturnToHermes = {}, onDismissOverlay = {}, onExit = { exits++ })
|
||||
|
||||
@Test fun backgroundCallerCannotCreateSession() {
|
||||
owner.lifecycle.currentState = Lifecycle.State.STARTED
|
||||
assertFalse(host.show(session(), owner.lifecycle))
|
||||
assertNull(host.sessionId)
|
||||
}
|
||||
|
||||
@Test fun missingAccessCannotCreateSession() {
|
||||
listOf(access.copy(microphone = false), access.copy(notifications = false),
|
||||
access.copy(overlay = false), access.copy(unlocked = false)).forEach {
|
||||
access = it
|
||||
assertFalse(host.show(session(), owner.lifecycle))
|
||||
assertNull(host.sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stopBeforeServiceReadyRejectsLateStartAndExitsOnce() {
|
||||
assertTrue(host.show(session(), owner.lifecycle))
|
||||
val id = host.sessionId!!
|
||||
host.exitVoiceSession(id)
|
||||
host.exitVoiceSession(id)
|
||||
assertFalse(host.onServiceReady(id))
|
||||
assertEquals(1, exits)
|
||||
}
|
||||
|
||||
@Test fun oldStopAndReadyCannotAffectNewSession() {
|
||||
host.show(session(), owner.lifecycle)
|
||||
val old = host.sessionId!!
|
||||
host.exitVoiceSession(old)
|
||||
host.show(session(), owner.lifecycle)
|
||||
val current = host.sessionId!!
|
||||
host.exitVoiceSession(old)
|
||||
assertFalse(host.onServiceReady(old))
|
||||
assertEquals(current, host.sessionId)
|
||||
assertTrue(host.canStart(current))
|
||||
assertEquals(1, exits)
|
||||
}
|
||||
|
||||
@Test fun lossOfForegroundBeforeServicePromotionFailsClosed() {
|
||||
host.show(session(), owner.lifecycle)
|
||||
owner.lifecycle.currentState = Lifecycle.State.STARTED
|
||||
assertFalse(host.canStart(host.sessionId!!))
|
||||
}
|
||||
|
||||
@Test fun revocationAndVoiceExitInvalidateActiveEligibility() {
|
||||
host.show(session(), owner.lifecycle)
|
||||
val id = host.sessionId!!
|
||||
access = access.copy(overlay = false)
|
||||
assertFalse(host.canContinue(id))
|
||||
access = access.copy(overlay = true)
|
||||
state.value = VoiceUiState(voiceMode = false)
|
||||
assertFalse(host.canContinue(id))
|
||||
}
|
||||
|
||||
@Test fun destroyedCallerEndsPendingSession() {
|
||||
host.show(session(), owner.lifecycle)
|
||||
owner.lifecycle.currentState = Lifecycle.State.DESTROYED
|
||||
assertNull(host.sessionId)
|
||||
assertEquals(1, exits)
|
||||
}
|
||||
|
||||
@Test fun returningToResumedAppReleasesOverlayWithoutEndingVoice() {
|
||||
host.show(session(), owner.lifecycle)
|
||||
val id = host.sessionId!!
|
||||
assertTrue(host.onServiceReady(id))
|
||||
owner.lifecycle.currentState = Lifecycle.State.STARTED
|
||||
assertTrue(host.canContinue(id))
|
||||
owner.lifecycle.currentState = Lifecycle.State.RESUMED
|
||||
assertNull(host.sessionId)
|
||||
assertEquals(0, exits)
|
||||
assertTrue(state.value.voiceMode)
|
||||
}
|
||||
|
||||
@Test fun revocationBeforeResumeEndsVoiceInsteadOfHandingItBack() {
|
||||
host.show(session(), owner.lifecycle)
|
||||
assertTrue(host.onServiceReady(host.sessionId!!))
|
||||
owner.lifecycle.currentState = Lifecycle.State.STARTED
|
||||
access = access.copy(overlay = false)
|
||||
owner.lifecycle.currentState = Lifecycle.State.RESUMED
|
||||
assertNull(host.sessionId)
|
||||
assertEquals(1, exits)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.hermesandroid.relay.voice
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.VoiceUiState
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = Application::class, qualifiers = "w360dp-h720dp-xhdpi", sdk = [35])
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class VoiceOverlayPresentationTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test fun missingPermissionKeepsStartDisabled() = setupDialog(false, 1f)
|
||||
@Test fun grantedPermissionsStillRequireStart() = setupDialog(true, 1f)
|
||||
@Test fun largeTextPermissionSetup() = setupDialog(true, 1.5f)
|
||||
|
||||
private fun setupDialog(granted: Boolean, scale: Float) {
|
||||
org.robolectric.RuntimeEnvironment.setFontScale(scale)
|
||||
compose.waitForIdle()
|
||||
var starts = 0
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(LocalDensity provides Density(LocalDensity.current.density, scale)) {
|
||||
VoiceOverlaySetupContent(VoiceOverlayAccess(true, granted, granted, true), false,
|
||||
{}, { starts++ }, {}, {}, {})
|
||||
}
|
||||
}
|
||||
}
|
||||
val start = compose.onNodeWithText("Start voice overlay")
|
||||
start.assertIsDisplayed()
|
||||
assertEquals(0, starts)
|
||||
if (granted) start.assertIsEnabled() else start.assertIsNotEnabled()
|
||||
capture("setup-$granted-$scale")
|
||||
compose.onNodeWithText("Display over other apps", substring = true).performScrollTo().assertIsDisplayed()
|
||||
if (scale > 1f) capture("setup-large-text-scrolled")
|
||||
if (granted) {
|
||||
start.performClick()
|
||||
compose.runOnIdle { assertEquals(1, starts) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stopRemainsReachableWhenMinimized() = overlay(1f)
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w320dp-h480dp-xhdpi")
|
||||
fun narrowOverlayWithLargeText() = overlay(1.5f)
|
||||
|
||||
private fun overlay(scale: Float) {
|
||||
org.robolectric.RuntimeEnvironment.setFontScale(scale)
|
||||
compose.waitForIdle()
|
||||
var exits = 0
|
||||
val session = VoiceOverlaySession(MutableStateFlow(VoiceUiState(voiceMode = true)),
|
||||
provider = null, model = null, voice = null, profileName = "Research", configScope = null,
|
||||
outputEnabled = true, fallbackEnabled = false, onStartListening = {}, onStopListening = {},
|
||||
onInterrupt = {}, onPauseAutoMode = {}, onReturnToHermes = {}, onDismissOverlay = {},
|
||||
onExit = { exits++ }, connectionLabel = "Home server")
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
VoiceFloatingOverlayPill(session, { _, _ -> })
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onNodeWithContentDescription("Stop voice").assertIsDisplayed().assertHeightIsAtLeast(48.dp)
|
||||
capture("overlay-compact-$scale")
|
||||
compose.onNodeWithContentDescription("Expand voice controls")
|
||||
.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) { it() }
|
||||
compose.runOnIdle { androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications() }
|
||||
compose.mainClock.advanceTimeByFrame()
|
||||
compose.mainClock.advanceTimeBy(500)
|
||||
capture("overlay-expanded-$scale")
|
||||
compose.onNodeWithText("Minimize").performScrollTo()
|
||||
.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) { it() }
|
||||
compose.mainClock.advanceTimeBy(500)
|
||||
compose.onNodeWithText("Stop voice").assertIsDisplayed()
|
||||
capture("overlay-minimized-$scale")
|
||||
compose.onNodeWithText("Stop voice")
|
||||
.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) { it() }
|
||||
compose.runOnIdle { assertEquals(1, exits) }
|
||||
}
|
||||
|
||||
private fun capture(name: String) {
|
||||
val file = File("build/ui-evidence/play-voice-$name.png")
|
||||
file.parentFile?.mkdirs()
|
||||
compose.onRoot().captureRoboImage(file.absolutePath)
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 80 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 82 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 82 KiB |
|
Before Width: | Height: | Size: 88 KiB After Width: | Height: | Size: 81 KiB |
@@ -22,13 +22,24 @@ export const desktopUiScreenshotSourceFiles = Object.freeze([
|
||||
|
||||
const binaryExtensions = new Set(['.png'])
|
||||
|
||||
function normalizedSource(relativePath, bytes) {
|
||||
if (binaryExtensions.has(extname(relativePath))) return bytes
|
||||
const text = bytes.toString('utf8').replace(/\r\n?/g, '\n')
|
||||
if (relativePath !== 'desktop/tray/package-lock.json') return Buffer.from(text, 'utf8')
|
||||
|
||||
// The screenshot fixture has fixed display versions. A release-only bump of
|
||||
// the root package does not change it; dependency versions still affect rendering.
|
||||
const lockfile = JSON.parse(text)
|
||||
delete lockfile.version
|
||||
if (lockfile.packages?.['']) delete lockfile.packages[''].version
|
||||
return Buffer.from(JSON.stringify(lockfile), 'utf8')
|
||||
}
|
||||
|
||||
export async function computeDesktopUiSourceFingerprint(repositoryRoot = defaultRepositoryRoot) {
|
||||
const hash = createHash('sha256')
|
||||
for (const relativePath of desktopUiScreenshotSourceFiles) {
|
||||
const bytes = await readFile(resolve(repositoryRoot, relativePath))
|
||||
const normalized = binaryExtensions.has(extname(relativePath))
|
||||
? bytes
|
||||
: Buffer.from(bytes.toString('utf8').replace(/\r\n?/g, '\n'), 'utf8')
|
||||
const normalized = normalizedSource(relativePath, bytes)
|
||||
hash.update(relativePath)
|
||||
hash.update('\0')
|
||||
hash.update(normalized)
|
||||
@@ -36,7 +47,7 @@ export async function computeDesktopUiSourceFingerprint(repositoryRoot = default
|
||||
}
|
||||
return {
|
||||
algorithm: 'sha256',
|
||||
normalization: 'text-lf-v1',
|
||||
normalization: 'text-lf-lockfile-root-version-v2',
|
||||
digest: hash.digest('hex'),
|
||||
files: [...desktopUiScreenshotSourceFiles]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { basename, dirname, join, resolve } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { computeDesktopUiSourceFingerprint, desktopUiScreenshotSourceFiles } from './desktop-ui-source-fingerprint.mjs'
|
||||
|
||||
async function fixture(t) {
|
||||
const root = await mkdtemp(join(tmpdir(), 'hermes-desktop-fingerprint-'))
|
||||
t.after(async () => {
|
||||
assert.equal(dirname(resolve(root)), resolve(tmpdir()))
|
||||
assert.ok(basename(root).startsWith('hermes-desktop-fingerprint-'))
|
||||
await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
for (const file of desktopUiScreenshotSourceFiles) {
|
||||
const destination = join(root, file)
|
||||
await mkdir(dirname(destination), { recursive: true })
|
||||
await writeFile(destination, 'fixture\n')
|
||||
}
|
||||
const lockfile = {
|
||||
name: '@hermes-relay/tray-ui', version: '0.4.0-beta.6', lockfileVersion: 3,
|
||||
packages: {
|
||||
'': { name: '@hermes-relay/tray-ui', version: '0.4.0-beta.6', dependencies: { react: '^19.0.0' } },
|
||||
'node_modules/react': { version: '19.0.0', integrity: 'example-integrity' },
|
||||
},
|
||||
}
|
||||
const saveLock = () => writeFile(join(root, 'desktop/tray/package-lock.json'), JSON.stringify(lockfile, null, 2))
|
||||
await saveLock()
|
||||
return { root, lockfile, saveLock, fingerprint: () => computeDesktopUiSourceFingerprint(root) }
|
||||
}
|
||||
|
||||
test('root release versions do not invalidate fixed-version screenshots', async t => {
|
||||
const f = await fixture(t)
|
||||
const before = await f.fingerprint()
|
||||
f.lockfile.version = '0.4.0-beta.7'
|
||||
f.lockfile.packages[''].version = '0.4.0-beta.7'
|
||||
await f.saveLock()
|
||||
assert.deepEqual(await f.fingerprint(), before)
|
||||
})
|
||||
|
||||
test('dependency versions and integrity remain fingerprinted', async t => {
|
||||
const f = await fixture(t)
|
||||
const before = (await f.fingerprint()).digest
|
||||
f.lockfile.packages['node_modules/react'].version = '19.1.0'
|
||||
await f.saveLock()
|
||||
const changedVersion = (await f.fingerprint()).digest
|
||||
assert.notEqual(changedVersion, before)
|
||||
f.lockfile.packages['node_modules/react'].integrity = 'changed-integrity'
|
||||
await f.saveLock()
|
||||
assert.notEqual((await f.fingerprint()).digest, changedVersion)
|
||||
})
|
||||
|
||||
test('production UI changes still invalidate screenshots', async t => {
|
||||
const f = await fixture(t)
|
||||
const before = (await f.fingerprint()).digest
|
||||
await writeFile(join(f.root, 'desktop/tray/ui/App.tsx'), 'changed UI\n')
|
||||
assert.notEqual((await f.fingerprint()).digest, before)
|
||||
})
|
||||
|
||||
test('text line endings do not cause platform-only drift', async t => {
|
||||
const f = await fixture(t)
|
||||
const before = await f.fingerprint()
|
||||
for (const file of desktopUiScreenshotSourceFiles.filter(file => !file.endsWith('.png'))) {
|
||||
const path = join(f.root, file)
|
||||
await writeFile(path, (await readFile(path, 'utf8')).replace(/\n/g, '\r\n'))
|
||||
}
|
||||
assert.deepEqual(await f.fingerprint(), before)
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
# Play voice overlay verification
|
||||
|
||||
The Google Play build adds user-started voice controls over other apps. This
|
||||
does not enable Device Control, AccessibilityService, MediaProjection or phone
|
||||
utility permissions. Standard voice keeps the upstream Dashboard/Gateway path.
|
||||
|
||||
## Session contract
|
||||
|
||||
- Permission setup explains the purpose before launching Android Settings.
|
||||
Permission grants do not start the overlay; Start requires a resumed, unlocked
|
||||
app with microphone, overlay and notification access.
|
||||
- The microphone foreground service must successfully promote before the window
|
||||
attaches. Session identifiers reject stale starts, readiness and Stop actions.
|
||||
- The existing voice runtime owns capture and microphone-release barriers. The
|
||||
service creates no recorder. Stop/close, screen lock, task removal, permission
|
||||
loss and failed startup terminate the voice session. Notification-channel
|
||||
revocation is checked at most one second later while the service is running.
|
||||
- Returning to Hermes preserves foreground protection until the app resumes.
|
||||
No overlay session is restored after process death or started by boot, Relay
|
||||
commands or wake detection. Independent opt-in wake settings remain unchanged.
|
||||
|
||||
## Host verification
|
||||
|
||||
Run focused tests through the Windows Android lane:
|
||||
|
||||
```powershell
|
||||
.\scripts\android-lane.ps1 gradle :app:testGooglePlayDebugUnitTest `
|
||||
--tests '*VoiceOverlay*Test' --tests '*VoiceModeOverlayInteractionTest' `
|
||||
--tests '*VoiceViewModelBargeInTest' --tests '*BargeInListenerShutdownRaceTest' `
|
||||
--console=plain
|
||||
```
|
||||
|
||||
The new session/service tests exercise foreground eligibility, missing/revoked
|
||||
access, stopped-before-ready sessions, old notification actions, failed foreground
|
||||
promotion/window attachment, screen-off and task removal. Existing voice tests
|
||||
cover the microphone handoff and shutdown race. The same new tests are included
|
||||
in the both-flavor on-demand focused preset.
|
||||
|
||||
`scripts/check-android-capabilities.py` checks source overlays and the merged
|
||||
Play debug/release manifests. Its mutation tests reject transitive sensitive
|
||||
permissions, renamed accessibility services and exported overlay services.
|
||||
CI debug/release builds and Play preflight run this check.
|
||||
|
||||
## Rendered controls
|
||||
|
||||
These are production Compose components rendered by Robolectric/Roborazzi on
|
||||
API 35, with synthetic voice state. They are not physical microphone evidence.
|
||||
Normal layout is 360 × 720 dp; narrow layout is 320 × 480 dp with 150% font size.
|
||||
The permission dialog is also checked at 150%, including scrolling to the last
|
||||
permission row while Start/Cancel remain reachable.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## Release validation
|
||||
|
||||
Physical-device tests and Play Console changes are separate release work. Before
|
||||
production, validate real repeated microphone turns after backgrounding on Android
|
||||
14–16, denial/revocation, task/process termination, screen lock, audio interruption,
|
||||
network loss and OEM window behavior. Use the Standard Phone API 36 emulator lane
|
||||
for the smallest relevant instrumentation run; device claims still require a real
|
||||
device. Do not install an APK or submit a test-track build without authorization.
|
||||
|
||||
Update the microphone FGS declaration and demo for the actual Google Play package.
|
||||
`scripts/android-fgs-demo.py` defaults to that package and requires permissions to
|
||||
be granted manually before recording. Review Data Safety against real recipients,
|
||||
retention and any applicable exceptions. Publish the corresponding canonical and
|
||||
legacy privacy pages before stable preflight; the strengthened live checker
|
||||
deliberately rejects the old blanket no-screen-access policy. See the
|
||||
[submission requirements](../play-store-listing.md#voice-overlay-review-before-production).
|
||||
@@ -0,0 +1,96 @@
|
||||
# Android profile identity audit
|
||||
|
||||
## Upstream contract
|
||||
|
||||
Source inspection used clean upstream commit
|
||||
`b0c383cdf7d8e9e540087610324ec3bb89f3b250` from `NousResearch/hermes-agent`.
|
||||
|
||||
- [`hermes_cli/profiles.py`](https://github.com/NousResearch/hermes-agent/blob/b0c383cdf7d8e9e540087610324ec3bb89f3b250/hermes_cli/profiles.py):
|
||||
`default` is the reserved request name for the root Hermes home. Named profiles
|
||||
resolve beneath the profiles directory. `is_default` marks that root row; it
|
||||
does not identify the sticky selection. The active-profile marker is written
|
||||
atomically, and selecting root removes the marker. Profile `display_name` is
|
||||
presentation metadata in `profile.yaml`; renaming root changes that display
|
||||
metadata rather than moving its home.
|
||||
- [`hermes_cli/web_routers/profiles.py`](https://github.com/NousResearch/hermes-agent/blob/b0c383cdf7d8e9e540087610324ec3bb89f3b250/hermes_cli/web_routers/profiles.py):
|
||||
`/api/profiles` returns `name`, `display_name`, `description`, and `is_default`.
|
||||
`/api/profiles/active` returns two different authorities: `active` is the sticky
|
||||
choice for new invocations, while `current` describes the running Dashboard.
|
||||
- [`tui_gateway/methods_profiles.py`](https://github.com/NousResearch/hermes-agent/blob/b0c383cdf7d8e9e540087610324ec3bb89f3b250/tui_gateway/methods_profiles.py):
|
||||
`profiles.list` returns the same profile identity plus avatar/UI metadata.
|
||||
Standard Android requests `include_sessions:false`; Bot Mode retains the
|
||||
richer roster contract and its own optional Bot title.
|
||||
- [`tui_gateway/methods_session.py`](https://github.com/NousResearch/hermes-agent/blob/b0c383cdf7d8e9e540087610324ec3bb89f3b250/tui_gateway/methods_session.py):
|
||||
explicit `profile` selects the profile home for session creation and resume.
|
||||
Omission uses launch context; it is not inherently a request for the sticky
|
||||
active profile. Android already resolves the sticky setting explicitly for
|
||||
standard profile-scoped sessions and retains that behavior.
|
||||
- [`apps/desktop/src/store/profile.ts`](https://github.com/NousResearch/hermes-agent/blob/b0c383cdf7d8e9e540087610324ec3bb89f3b250/apps/desktop/src/store/profile.ts):
|
||||
`profileLabel` uses trimmed `display_name`, then the request name. TUI's
|
||||
[`appLayout.tsx`](https://github.com/NousResearch/hermes-agent/blob/b0c383cdf7d8e9e540087610324ec3bb89f3b250/ui-tui/src/components/appLayout.tsx)
|
||||
supplies session `profile_name` to its composer prompt rather than a server
|
||||
connection label.
|
||||
|
||||
The `active_status_profile_scope` scenario's current-upstream conformance check
|
||||
passed against this SHA. This is source-only evidence, with no provider calls.
|
||||
|
||||
## Product decision
|
||||
|
||||
The agent name is Hermes `display_name`, otherwise the exact profile request
|
||||
name. Descriptions are not identity. A connection name remains infrastructure
|
||||
identity. Existing local aliases and personality fallback remain supported; an
|
||||
otherwise unknown agent is **Hermes**.
|
||||
|
||||
When the server default resolves to a catalog profile, the shelf and canonical
|
||||
switcher show one identity with a home badge. The switcher shows **Server default**
|
||||
as secondary status and **Follow server default** as a separate selection control.
|
||||
Unchecking it explicitly selects the resolved profile; checking it restores the
|
||||
null selection. Both use the existing profile-switch lifecycle. No server setting
|
||||
is written and no session, draft, history, lock, or asset key is migrated.
|
||||
|
||||
The explicit root `default` choice remains available. Equal display names never
|
||||
cause grouping. Grouping requires exact upstream request identity within the
|
||||
current connection. Missing scope stays unresolved; a known scope without roster
|
||||
metadata retains its request name rather than borrowing root metadata.
|
||||
|
||||
## Surface review
|
||||
|
||||
| Surface | Result |
|
||||
| --- | --- |
|
||||
| Chat header and Passport | Shared identity helper consumes display metadata; connection label and description no longer masquerade as an agent. |
|
||||
| Profile shelf and canonical switcher | Exact-identity grouping, selected-key preservation, role text, follow control, unchanged switch callbacks and local/shared avatar lookup. |
|
||||
| Connection selection | Connection identity and credentials remain separately scoped; no endpoint or persistence changes. |
|
||||
| Settings locks and display management | Follow-default preference is labeled as an action; independent lock/order/hidden keys remain visible for management. |
|
||||
| Manage profile catalog | Uses upstream display name while preserving the raw name for actions. |
|
||||
| Bot Mode | Already prioritizes Bot title, then display name, then request name; parsing now also retains display name in its Profile metadata. Route keys and connection-qualified handles stay unchanged. |
|
||||
| Restoration and diagnostics | Raw profile/session/connection keys remain authoritative. No display-label parsing, normalization, session deletion, or routing changes. |
|
||||
| Supervised mode, avatars, pets | Lock gates and exact asset keys remain unchanged. An unresolved default cannot borrow or modify the root avatar from `is_default`; shared-avatar actions require a resolved or explicit profile. The follow control is disabled under a lock. |
|
||||
| Legacy private agent sheet | Not the canonical switcher; retained without a separate routing/model rewrite. |
|
||||
|
||||
## Rendered evidence
|
||||
|
||||
Sanitized fixtures render the production Compose profile switcher with mocked
|
||||
metadata and avatar flows. They make no network requests and contain no profile
|
||||
contents or private infrastructure. These are JVM/Robolectric renders, not phone
|
||||
screenshots or live-server certification.
|
||||
|
||||
| Before | After |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||
The rendered checks cover 360 x 720 dp, 720 x 360 dp landscape, and
|
||||
840 x 720 dp expanded layouts, plus 1.5x system font scale and a long display
|
||||
name. Text truncates with ellipsis, the request name remains available as
|
||||
supporting text, and the follow control preserves checkbox state and a 48 dp
|
||||
minimum target. Landscape opens fully expanded with scrollable content.
|
||||
|
||||
- [Large text](assets/profile-identity/large-text.png)
|
||||
- [Landscape](assets/profile-identity/landscape.png)
|
||||
- [Expanded layout](assets/profile-identity/expanded.png)
|
||||
- [Long name](assets/profile-identity/long-name.png)
|
||||
|
||||
Focused sideload and Google Play suites each passed 497 tests with no failures
|
||||
or skips. Lint and build results are recorded with the PR. Live-server,
|
||||
physical-device, screen-reader, and fold-posture transition behavior remain
|
||||
separate verification gaps. No APK was installed and no server profile was
|
||||
modified.
|
||||
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 100 KiB |