Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75feb55adf | ||
|
|
e20540d16f | ||
|
|
c932adbc7b | ||
|
|
23cec497ce | ||
|
|
1739dc36a2 | ||
|
|
c917a94fcb | ||
|
|
e1a72ee8af | ||
|
|
94f9ba4305 | ||
|
|
3186afdde8 | ||
|
|
f4b366389b | ||
|
|
2ec7b7aac9 |
+18
-6
@@ -6,17 +6,29 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [Android 1.15.1] - 2026-09-02
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android Chat and Voice use tablet space intentionally.** Expanded layouts keep introductions, transcripts, composer controls, and status chrome on readable centered rails, while landscape Voice Focus separates identity controls from conversation activity without changing phone or portrait interaction behavior.
|
||||
- Chat and Bot Chat offer a compact Correct now / Queue next tray behind the composer. Chat settings sets the default; each message can override it. Stop pauses pending work until Resume, and editing or removing queued messages preserves the remaining order.
|
||||
- Wider Chat and Voice layouts keep text and controls centered and readable, including landscape Voice Focus.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android attachment previews survive rotation and preserve video proportions.** Full-screen image, video, audio, PDF, text, and file previews remain open while the chat reflows, respect the device rotation preference, and render portrait or landscape video through Media3's fitted content surface instead of a fixed 16:9 box. (#483)
|
||||
- **Android wake-word JNI configuration survives release shrinking.** R8 now preserves sherpa-onnx configuration class and field names that the native keyword spotter resolves at runtime. (#444)
|
||||
- **Android streams Standard Hermes attachments into its on-disk media cache.** Automatic Dashboard downloads no longer preallocate and duplicate the full response body on the OkHttp dispatcher, while declared and observed size limits remain enforced. (#531)
|
||||
- **Android fresh Gateway chats wait for their upstream runtime before sending.** Android now consumes the lazy `session.create` readiness edge instead of racing the first prompt into compute-host ownership rejection. Genuine ownership refusals keep the exact holder-aware error and retryable local prompt instead of falling into unfinished-message history recovery.
|
||||
- **Windows desktop updates keep the installed CLI and UI on one release.** `hermes-relay update` now detects a colocated management UI, reports both installed versions, and uses the verified bundle installer to replace and restart the affected surfaces together. Explicit CLI-only installations retain the standalone binary updater.
|
||||
- Delivery and correction labels remain readable inside user-message bubbles.
|
||||
- Voice errors use a scrollable dialog with separate Retry and Dismiss actions.
|
||||
- Attachment previews stay open through rotation, and videos retain their original proportions. (#483)
|
||||
- Release builds preserve the native configuration names required for wake-word startup. (#444)
|
||||
- Standard Hermes attachments stream to disk while enforcing download size limits. (#531)
|
||||
- Session refresh no longer sustains a request loop. History loads, chat rendering, image previews, and media exports keep memory use bounded.
|
||||
- Image-generation progress remains visible between interim replies and media delivery.
|
||||
- New Gateway chats wait for session readiness before the first prompt; ownership refusals preserve the retryable prompt and server error.
|
||||
|
||||
## [0.4.0-beta.7] - 2026-09-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- Windows updates detect a colocated management UI, report both installed versions, and update the CLI and UI together through the verified bundle installer. CLI-only installations keep their standalone updater.
|
||||
|
||||
## [Android 1.15.0] - 2026-08-31
|
||||
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
# Hermes-Relay CLI+UI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-08-31
|
||||
**Release Date:** 2026-09-02
|
||||
|
||||
This beta preserves complete multi-route pairing while preventing Desktop from dialing Dashboard-ingress Relay routes before Dashboard WebSocket ticket support is available. (Related: #399)
|
||||
This beta fixes Windows updates so the installed CLI and management UI advance together. Explicit CLI-only installations keep their standalone update path.
|
||||
|
||||
**Beta phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64/arm64, and macOS x64/arm64; the management UI is Windows-only.
|
||||
|
||||
## What's changed
|
||||
|
||||
### Changed
|
||||
|
||||
- **Saved hosts retain the full route topology.** Dashboard, Relay, optional API, route priority, transport protection, certificate pins, and the selected host survive LAN, Tailscale, and public-route changes without creating duplicate hosts.
|
||||
- **API-less pairing is first-class.** Dashboard plus direct Relay can pair without inventing an optional API server, while secure-first ranking retains plain LAN as the final fallback.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Dashboard-ingress Relay routes fail closed on Desktop.** The daemon, host selector, and Relay transport reject ingress that requires a Dashboard WebSocket ticket and choose a compatible direct Relay fallback instead of attempting an unauthenticated dial.
|
||||
- **Pairing accepts the current v3 candidate shape.** Optional API records, same-origin Dashboard/Relay routes, and legacy top-level payloads remain compatible without collapsing route ownership.
|
||||
- `hermes-relay update` detects an installed management UI beside the CLI and reports both installed versions.
|
||||
- Bundle installations use the checksum-verified Windows installer to update and restart the affected CLI and UI together.
|
||||
- Explicit CLI-only installations continue to use the standalone binary updater.
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
+20
-23
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.15.0
|
||||
# Hermes-Relay Android v1.15.1
|
||||
|
||||
**Release Date:** August 31, 2026
|
||||
**Release Date:** September 2, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.15.0-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.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).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,32 +12,29 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This release makes the everyday Android experience work through current upstream Hermes without treating the optional Hermes-Relay Plugin as a prerequisite. It also strengthens parent access, cross-client activity, transport ownership, recovery, and release visibility.
|
||||
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.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Upstream-first standard surfaces.** Chat attachments, inbound host files, current-session Git reads, Nous usage bars, and keyed Hermes notices use authenticated Dashboard/Gateway contracts first. Relay remains an additive compatibility and enhancement layer.
|
||||
- **Clear Settings ownership.** Media sits with Chat and Voice under Hermes. Proactive Threads, Terminal, Notification Companion, Relay sessions, enhanced voice, and Device Control stay grouped under Relay tools.
|
||||
- **App-specific supervised parent access.** Parents choose a PIN or password and receive a six-word recovery phrase; Android device credentials and biometrics no longer grant parent authority.
|
||||
- **Complete What's New history.** Release highlights, the remaining improvements and fixes, compatibility notes, toast counts, and history now come from one structured inventory.
|
||||
- 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.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Host-local images, audio, video, and files download through the authenticated Dashboard and remain loaded across history reconciliation instead of flashing `Relay URL not configured` or returning to Loading.
|
||||
- Standard voice remains usable after explicit Relay removal, while temporary Relay outages preserve configured choices and default-profile preferences stay isolated across connections.
|
||||
- Android can display uniquely matched Desktop/TUI Working and Waiting activity without resuming, activating, or interrupting the external turn.
|
||||
- Dashboard/Gateway chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing to Direct API.
|
||||
- Completed text survives Dashboard-history authentication expiry and returns the existing sign-in recovery path.
|
||||
- Long-running context compaction refreshes the turn watchdog instead of being interrupted as idle.
|
||||
- Bot Chat history renders immediately after its route-owned handler binds.
|
||||
- An exact idle live-session snapshot settles an Android-owned turn whose terminal frame was lost, reconciles history, and drains its queued follow-up.
|
||||
- Supervised Add Gateway remains parent-owned across relock, back navigation, and pending setup cancellation.
|
||||
- Completed generated images stay visible during marker persistence lag and retain the intended image-generation presentation.
|
||||
- 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.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.15.0** (versionCode **53**).
|
||||
- Standard Chat, sessions, profiles, Manage, standard voice, outbound attachments, and ordinary inbound files work against current unmodified upstream Hermes without the optional Hermes-Relay Plugin.
|
||||
- Install Hermes-Relay Plugin v1.11.1 for Terminal, proactive Threads/offline delivery, Notification Companion, Relay sessions, provider-native/realtime voice, compatibility media metadata, Secure Link, and phone/device control.
|
||||
- Explicit Direct API/API-only connections remain supported and are never used as a silent failover for a Dashboard-owned chat.
|
||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only; the Google Play build does not declare their restricted permissions.
|
||||
- App version: **1.15.1** (versionCode **54**).
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
+79
@@ -15,6 +15,10 @@ import androidx.compose.ui.test.assertTextEquals
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
@@ -171,6 +175,81 @@ class GatewayExternalFixtureInstrumentedTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedStopResume_preservesWorkAcrossLifecycleAndUsesExplicitResume() {
|
||||
val base = InstrumentationRegistry.getArguments().getString(ARG_FIXTURE_BASE_URL)?.trimEnd('/')
|
||||
assumeTrue("Pass a queued_stop_resume fixture URL", !base.isNullOrBlank())
|
||||
requireNotNull(base)
|
||||
val http = OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).build()
|
||||
assertEquals("queued_stop_resume", readFixtureJson(http, "$base/__fixture__/state")["scenario"]?.jsonString())
|
||||
val dashboard = DashboardApiClient(base, http)
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { gatewayScope = it }
|
||||
val gateway = GatewayChatClient(
|
||||
initialDashboardClient = dashboard, okHttpClient = http, scope = scope,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
).also { gatewayClient = it }
|
||||
val handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
val vm = ChatViewModel().also {
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoaderWithMode { profile, session, mode -> dashboard.getSessionMessages(session, profile, mode) }
|
||||
it.updateGatewayClient(gateway)
|
||||
it.switchProfileContext(com.hermesandroid.relay.data.AgentDisplay.profileContextKey("fixture-queue", null), STORED_SESSION_ID)
|
||||
}.also { viewModel = it }
|
||||
compose.setContent {
|
||||
val queue by vm.queuedMessages.collectAsStateWithLifecycle()
|
||||
val paused by vm.queuePaused.collectAsStateWithLifecycle()
|
||||
com.hermesandroid.relay.ui.theme.HermesRelayTheme(themePreference = "dark") {
|
||||
androidx.compose.material3.Surface {
|
||||
Column {
|
||||
com.hermesandroid.relay.ui.components.ChatBusyActionSelector(
|
||||
com.hermesandroid.relay.data.BusyMessageAction.QueueNext, {}, onStop = vm::cancelStream,
|
||||
)
|
||||
com.hermesandroid.relay.ui.components.ChatMessageQueue(
|
||||
queue, paused, vm::resumeQueue, vm::clearQueue, {}, vm::removeQueuedAt, canEdit = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
compose.runOnIdle { vm.sendMessage("Original work") }
|
||||
compose.waitUntil(10_000) { handler.isStreaming.value && vm.steerableTurn.value }
|
||||
compose.runOnIdle {
|
||||
vm.sendMessage("Remove this follow-up", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
vm.sendMessage("Keep this follow-up", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
}
|
||||
compose.onAllNodesWithContentDescription("Remove queued message")[0].performClick()
|
||||
compose.onNodeWithContentDescription("Stop streaming").performClick()
|
||||
compose.onNodeWithText("Queue paused").assertIsDisplayed()
|
||||
assertEquals(listOf("Keep this follow-up"), vm.queuedMessages.value)
|
||||
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.CREATED)
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
compose.onNodeWithText("Keep this follow-up").assertIsDisplayed()
|
||||
compose.onNodeWithText("Resume").performClick()
|
||||
try {
|
||||
compose.waitUntil(15_000) {
|
||||
vm.queuedMessages.value.isEmpty() && !handler.isStreaming.value &&
|
||||
handler.messages.value.any { it.content == "Resumed follow-up." }
|
||||
}
|
||||
} catch (error: androidx.compose.ui.test.ComposeTimeoutException) {
|
||||
throw AssertionError(
|
||||
"Synthetic queue fixture did not settle: queued=${vm.queuedMessages.value.size}, " +
|
||||
"paused=${vm.queuePaused.value}, streaming=${handler.isStreaming.value}, " +
|
||||
"messages=${handler.messages.value.map { it.role to it.content }}, " +
|
||||
"error=${handler.error.value}",
|
||||
error,
|
||||
)
|
||||
}
|
||||
val evidence = readFixtureJson(http, "$base/__fixture__/evidence")["entries"] as JsonArray
|
||||
assertEquals(2, evidence.rpcCount("prompt.submit"))
|
||||
assertEquals(1, evidence.rpcCount("session.interrupt"))
|
||||
assertEquals(0, evidence.rpcCount("session.redirect"))
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
}
|
||||
|
||||
private fun JsonArray.rpcCount(method: String): Int = count { element ->
|
||||
val entry = element as? JsonObject ?: return@count false
|
||||
entry["kind"]?.jsonString() == "rpc" && entry["method"]?.jsonString() == method
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
v1.15.0 - Standard Hermes first, with clearer Relay boundaries
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
|
||||
Standard Chat, Voice, attachments, returned files, current-session Git, usage, and Hermes notices now prefer upstream Dashboard and Gateway support without requiring Relay. Returned media stays loaded, voice survives Relay removal, and Settings clearly separates standard Hermes from Relay tools. Supervised Mode also gains app-specific parent access and recovery.
|
||||
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.
|
||||
|
||||
@@ -1,6 +1,83 @@
|
||||
{
|
||||
"schema": 3,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.15.1",
|
||||
"title": "Steadier chat, media, and voice",
|
||||
"date": "2026-09-02",
|
||||
"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.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "follow-up-controls",
|
||||
"kind": "improved",
|
||||
"title": "Choose when follow-up messages are sent",
|
||||
"summary": "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.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "tablet-layouts",
|
||||
"kind": "improved",
|
||||
"title": "Make better use of wider screens",
|
||||
"summary": "Chat and Voice keep text and controls on readable centered layouts. Landscape Voice Focus separates identity controls from conversation activity."
|
||||
},
|
||||
{
|
||||
"id": "delivery-labels",
|
||||
"kind": "fixed",
|
||||
"title": "Read message delivery status clearly",
|
||||
"summary": "Correction and delivery labels use contrasting text instead of disappearing into the message bubble."
|
||||
},
|
||||
{
|
||||
"id": "voice-error-dialog",
|
||||
"kind": "fixed",
|
||||
"title": "Read and dismiss voice errors",
|
||||
"summary": "Voice errors open in a contained dialog with scrollable details and separate Retry and Dismiss actions, without overlapping chat controls."
|
||||
},
|
||||
{
|
||||
"id": "attachment-previews",
|
||||
"kind": "fixed",
|
||||
"title": "Keep attachment previews open through rotation",
|
||||
"summary": "Image, video, audio, PDF, text, and file previews stay open as the screen rotates. Videos retain their original proportions.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "wake-word-startup",
|
||||
"kind": "fixed",
|
||||
"title": "Fix wake-word startup in release builds",
|
||||
"summary": "Release optimization now preserves the native speech configuration names needed to initialize wake-word detection."
|
||||
},
|
||||
{
|
||||
"id": "attachment-downloads",
|
||||
"kind": "fixed",
|
||||
"title": "Download attachments with less memory",
|
||||
"summary": "Standard Hermes attachments stream into the on-disk cache while download size limits remain enforced."
|
||||
},
|
||||
{
|
||||
"id": "chat-memory-safety",
|
||||
"kind": "fixed",
|
||||
"title": "Keep large chats and media manageable",
|
||||
"summary": "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.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "image-progress",
|
||||
"kind": "fixed",
|
||||
"title": "Keep image-generation progress visible",
|
||||
"summary": "The working indicator stays visible between interim replies and the generated image, including gateways that omit tool activity events."
|
||||
},
|
||||
{
|
||||
"id": "first-message-readiness",
|
||||
"kind": "fixed",
|
||||
"title": "Wait for new chats to be ready",
|
||||
"summary": "The first message waits for the Gateway session to initialize. Ownership refusals keep the prompt retryable and show the server's error."
|
||||
}
|
||||
],
|
||||
"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."
|
||||
],
|
||||
"playNotes": "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.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.15.0",
|
||||
"title": "Standard Hermes first, with clearer Relay boundaries",
|
||||
|
||||
@@ -1,29 +1,24 @@
|
||||
v1.15.0 - Standard Hermes first, with clearer Relay boundaries
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
|
||||
Summary
|
||||
* Chat, voice, attachments, inbound files, current-session Git, usage, and Hermes notices now prefer current upstream Dashboard and Gateway support. Relay stays optional for compatibility and the tools it uniquely provides.
|
||||
* 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.
|
||||
|
||||
Highlights
|
||||
* Use standard Hermes without Relay prompts — Chat attachments, inbound files, current-session Git, Nous usage, and Hermes notices use upstream routes first.
|
||||
* Keep returned files loaded — Images, audio, video, and documents download through the Dashboard and no longer flash Relay errors or return to Loading.
|
||||
* Use app-specific parent access — A parent PIN or password plus recovery phrase protects Supervised Mode without trusting the phone unlock credential.
|
||||
* 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.
|
||||
|
||||
Improved
|
||||
* See which features need Relay — Media sits with standard Hermes settings while Threads, Terminal, notifications, enhanced voice, and device tools stay under Relay tools.
|
||||
* Read the complete release record — What's New shows one release summary, selected highlights, every remaining change, and relevant compatibility notes.
|
||||
* 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.
|
||||
|
||||
Fixed
|
||||
* Keep Standard voice after removing Relay — Dashboard voice remains ready, temporary outages preserve choices, and shared default-profile settings stay isolated.
|
||||
* Observe another client's activity safely — A uniquely matched Desktop or TUI turn can show Working or Waiting without Android taking control.
|
||||
* Keep each chat on its chosen transport — Dashboard chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing databases.
|
||||
* Preserve completed replies at sign-in expiry — A Dashboard history authentication failure keeps completed text visible and opens the existing sign-in recovery path.
|
||||
* Let long context compaction finish — Visible compaction activity refreshes the turn watchdog instead of being interrupted as idle.
|
||||
* Render Bot Chat history immediately — Route-owned Bot Chats observe their bound history from first composition.
|
||||
* Settle turns after a lost terminal frame — An exact idle live-session snapshot reconciles the Android-owned turn and drains its queued follow-up.
|
||||
* Keep Gateway setup parent-owned — Relock and back navigation cancel the exact pending setup without bypassing parent authority.
|
||||
* Keep completed generated images visible — Generated media survives marker persistence lag and retains its intended Chat animation.
|
||||
* 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.
|
||||
|
||||
Compatibility
|
||||
* Current upstream Hermes provides standard Chat, sessions, Manage, voice, attachments, inbound files, current-session Git reads, usage, and notices without the optional Hermes-Relay Plugin.
|
||||
* Hermes-Relay Plugin 1.11.1 remains required for Terminal, proactive Threads and offline delivery, Notification Companion, Relay sessions, enhanced voice, Secure Link, and phone or device control.
|
||||
* Granular Device Control and the system Voice Focus overlay remain sideload-only.
|
||||
* 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.
|
||||
|
||||
@@ -22,6 +22,26 @@ enum class PhysicalKeyboardEnterBehavior(val storedValue: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Default intent for a message submitted while an agent is responding. */
|
||||
enum class BusyMessageAction(val storedValue: String) {
|
||||
CorrectNow("correct_now"),
|
||||
QueueNext("queue_next");
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): BusyMessageAction =
|
||||
entries.firstOrNull { it.storedValue == value } ?: CorrectNow
|
||||
}
|
||||
}
|
||||
|
||||
fun canCorrectBusyMessage(
|
||||
steerable: Boolean,
|
||||
hasAttachments: Boolean,
|
||||
hasPendingInput: Boolean,
|
||||
status: String?,
|
||||
text: String,
|
||||
): Boolean = steerable && !hasAttachments && !hasPendingInput &&
|
||||
status?.contains("compact", ignoreCase = true) != true && !text.trimStart().startsWith("/")
|
||||
|
||||
/** Device-level chat input preferences shared by every Hermes profile. */
|
||||
class ChatInputPreferencesRepository(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
@@ -29,6 +49,7 @@ class ChatInputPreferencesRepository(
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
companion object {
|
||||
internal val KEY_BUSY_MESSAGE_ACTION = stringPreferencesKey("busy_message_action")
|
||||
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||
internal val KEY_CONVERT_LARGE_PASTES =
|
||||
@@ -45,6 +66,14 @@ class ChatInputPreferencesRepository(
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
|
||||
val busyMessageAction: Flow<BusyMessageAction> = dataStore.data
|
||||
.map { BusyMessageAction.fromStoredValue(it[KEY_BUSY_MESSAGE_ACTION]) }
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setBusyMessageAction(action: BusyMessageAction) {
|
||||
dataStore.edit { it[KEY_BUSY_MESSAGE_ACTION] = action.storedValue }
|
||||
}
|
||||
|
||||
val convertLargePastesToAttachments: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
@@ -35,6 +35,9 @@ data class ChatTurnCheckpoint(
|
||||
val baselineAssistantCount: Int,
|
||||
val pendingAsk: ChatTurnAskCheckpoint? = null,
|
||||
val queuedMessages: List<ChatQueuedMessageCheckpoint> = emptyList(),
|
||||
val queuePaused: Boolean = false,
|
||||
/** Only pending local work remains; never reattach the completed/stopped turn. */
|
||||
val queueOnly: Boolean = false,
|
||||
val startedAt: Long,
|
||||
val updatedAt: Long,
|
||||
) {
|
||||
|
||||
@@ -49,6 +49,7 @@ import okhttp3.Request
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
@@ -1355,7 +1356,7 @@ class DashboardApiClient(
|
||||
suspend fun getSessionMessages(
|
||||
sessionId: String,
|
||||
profile: String? = null,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>> = withContext(Dispatchers.IO) {
|
||||
val name = profile?.trim().orEmpty()
|
||||
loadSessionMessages(mode) { page ->
|
||||
@@ -1759,6 +1760,7 @@ class DashboardApiClient(
|
||||
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
||||
// client-side avoids uploading a body the Dashboard will reject.
|
||||
internal const val MAX_BACKUP_TRANSFER_BYTES = 100L * 1024L * 1024L
|
||||
internal const val MAX_JSON_RESPONSE_BYTES = 8L * 1024L * 1024L
|
||||
|
||||
fun pathSegment(value: String): String =
|
||||
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||
@@ -2487,17 +2489,44 @@ data class StoredDashboardCookie(
|
||||
}
|
||||
|
||||
private fun Response.readJsonObject(json: Json): JsonObject {
|
||||
val raw = body.string()
|
||||
val raw = body.readUtf8Bounded(DashboardApiClient.MAX_JSON_RESPONSE_BYTES)
|
||||
if (raw.isBlank()) return JsonObject(emptyMap())
|
||||
return json.parseToJsonElement(raw).jsonObject
|
||||
}
|
||||
|
||||
private fun Response.readJsonElement(json: Json): JsonElement {
|
||||
val raw = body.string()
|
||||
val raw = body.readUtf8Bounded(DashboardApiClient.MAX_JSON_RESPONSE_BYTES)
|
||||
if (raw.isBlank()) return JsonObject(emptyMap())
|
||||
return json.parseToJsonElement(raw)
|
||||
}
|
||||
|
||||
internal fun okhttp3.ResponseBody.readUtf8Bounded(maxBytes: Long): String {
|
||||
require(maxBytes in 1..Int.MAX_VALUE.toLong()) { "Invalid response byte limit" }
|
||||
val declaredLength = contentLength()
|
||||
if (declaredLength > maxBytes) {
|
||||
throw IOException("Dashboard response exceeds Android's bounded JSON limit")
|
||||
}
|
||||
val initialSize = when {
|
||||
declaredLength in 1..maxBytes -> declaredLength.toInt()
|
||||
else -> minOf(maxBytes, DEFAULT_BUFFER_SIZE.toLong()).toInt()
|
||||
}
|
||||
val output = ByteArrayOutputStream(initialSize)
|
||||
byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
if (total > maxBytes) {
|
||||
throw IOException("Dashboard response exceeds Android's bounded JSON limit")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return output.toString(Charsets.UTF_8.name())
|
||||
}
|
||||
|
||||
private fun contentDispositionFileName(header: String): String? {
|
||||
val encoded = Regex("""filename\*=UTF-8''([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
@@ -2586,7 +2615,11 @@ internal fun Throwable.isDashboardManagedFilesUnsupported(): Boolean {
|
||||
}
|
||||
|
||||
private fun apiFailure(response: Response, operation: String): IOException {
|
||||
val bodyDetail = runCatching { response.body.string() }.getOrDefault("")
|
||||
val bodyDetail = try {
|
||||
response.body.readUtf8Bounded(4L * 1024L)
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
val detail = bodyDetail.take(240).ifBlank { response.message }
|
||||
return DashboardHttpException(
|
||||
statusCode = response.code,
|
||||
|
||||
@@ -416,6 +416,10 @@ class GatewayChatClient(
|
||||
@Volatile
|
||||
private var webSocket: WebSocket? = null
|
||||
|
||||
/** Profile explicitly routed by the Dashboard `/api/ws?profile=` handshake. */
|
||||
@Volatile
|
||||
private var connectedSocketProfile: String? = null
|
||||
|
||||
/** Completed when the server's `gateway.ready` event arrives for the current socket. */
|
||||
@Volatile
|
||||
private var readySignal: CompletableDeferred<Unit>? = null
|
||||
@@ -3066,9 +3070,10 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
val ticketMs = (System.nanoTime() - connectStart) / 1_000_000
|
||||
val socketProfile = currentSessionProfile()
|
||||
val url = dashboardClient.gatewayWebSocketUrl(
|
||||
ticket = ticket.ticket,
|
||||
profile = currentSessionProfile(),
|
||||
profile = socketProfile,
|
||||
)
|
||||
?: throw GatewayConnectAttemptException(
|
||||
"could not build /api/ws URL",
|
||||
@@ -3102,6 +3107,7 @@ class GatewayChatClient(
|
||||
if (readyFailure != null) {
|
||||
socket.cancel()
|
||||
webSocket = null
|
||||
connectedSocketProfile = null
|
||||
throw (readyFailure as? GatewayConnectAttemptException
|
||||
?: GatewayConnectAttemptException(
|
||||
"gateway connection failed: ${readyFailure.message}",
|
||||
@@ -3114,6 +3120,7 @@ class GatewayChatClient(
|
||||
val wsMs = (System.nanoTime() - connectStart) / 1_000_000 - ticketMs
|
||||
Log.i(TAG, "Gateway connected (/api/ws ready) — ticket=${ticketMs}ms ws=${wsMs}ms")
|
||||
hasEverReachedReady = true
|
||||
connectedSocketProfile = socketProfile
|
||||
coldStartFailureEpisodes = 0
|
||||
_reconnectDisposition.value = GatewayReconnectDisposition.None
|
||||
_connectionState.value = GatewayConnectionState.Ready
|
||||
@@ -3288,7 +3295,8 @@ class GatewayChatClient(
|
||||
?.stringField("profile_name")
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
if (actual != expected) {
|
||||
val socketConfirmed = actual == null && connectedSocketProfile == expected
|
||||
if (actual != expected && !socketConfirmed) {
|
||||
val detail = actual?.let { "Hermes returned profile '$it'" }
|
||||
?: "Hermes did not confirm profile ownership"
|
||||
throw GatewayPreflightException(
|
||||
@@ -3692,6 +3700,22 @@ class GatewayChatClient(
|
||||
sessionReadyWaiters.remove(eventSessionId)?.complete(Unit)
|
||||
}
|
||||
|
||||
// Deferred agent construction can fail after lazy session.create/
|
||||
// resume returns but before prompt.submit. Fail the readiness barrier
|
||||
// immediately so the optimistic prompt remains retryable/Not sent
|
||||
// instead of waiting for the five-minute readiness timeout.
|
||||
if (type == "error" && !eventSessionId.isNullOrBlank() &&
|
||||
(eventSessionId in lazyLiveSessions || sessionReadyWaiters.containsKey(eventSessionId))
|
||||
) {
|
||||
val message = payload?.stringField("message")
|
||||
?: "Hermes session initialization failed"
|
||||
lazyLiveSessions.remove(eventSessionId)
|
||||
readyLiveSessions.remove(eventSessionId)
|
||||
sessionReadyWaiters.remove(eventSessionId)
|
||||
?.completeExceptionally(GatewayRpcException(message))
|
||||
return
|
||||
}
|
||||
|
||||
// Upstream emits session.reclaimed process-wide, so it is identified
|
||||
// by payload rather than params.session_id. Retire only an exact live
|
||||
// runtime we own; preserve the durable id so the next send resumes it.
|
||||
@@ -4006,6 +4030,7 @@ class GatewayChatClient(
|
||||
// id on the shared gateway stream) keeps matching after reconnect.
|
||||
val preservedLiveId = liveSessionId
|
||||
webSocket = null
|
||||
connectedSocketProfile = null
|
||||
readySignal = null
|
||||
liveSessionId = null
|
||||
attachMethodForSocket = null
|
||||
@@ -4197,6 +4222,7 @@ class GatewayChatClient(
|
||||
private fun closeSocket(reason: String) {
|
||||
webSocket?.close(1000, reason)
|
||||
webSocket = null
|
||||
connectedSocketProfile = null
|
||||
readySignal = null
|
||||
liveSessionId = null
|
||||
failSessionReadyWaiters("gateway socket closed")
|
||||
|
||||
@@ -196,7 +196,8 @@ class GatewayEventMapper(
|
||||
|
||||
"tool.start" -> {
|
||||
clearActivityStatuses()
|
||||
val name = payload.string("name") ?: "unknown"
|
||||
val identity = payload.effectiveToolIdentity()
|
||||
val name = identity.name
|
||||
// A pending generating placeholder for this name is adopted
|
||||
// (consumed FIFO) whether or not the server sent a real id.
|
||||
val adopted = generatingIdsByName[name]?.removeFirstOrNull()
|
||||
@@ -208,7 +209,7 @@ class GatewayEventMapper(
|
||||
}
|
||||
else -> syntheticToolId(name)
|
||||
}
|
||||
val argsPreview = payload?.get("args")
|
||||
val argsPreview = identity.argsPreview ?: payload?.get("args")
|
||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||
?.toString()
|
||||
?.takeIf { it.isNotBlank() && it != "null" }
|
||||
@@ -220,7 +221,7 @@ class GatewayEventMapper(
|
||||
|
||||
"tool.complete" -> {
|
||||
clearActivityStatuses()
|
||||
val name = payload.string("name") ?: "unknown"
|
||||
val name = payload.effectiveToolIdentity().name
|
||||
val toolId = payload.string("tool_id")
|
||||
?: openSyntheticIdsByName[name]?.removeFirstOrNull()
|
||||
?: return
|
||||
@@ -627,6 +628,34 @@ private const val MAX_CLARIFY_CHOICES = 4
|
||||
private const val SUDO_TIMEOUT_SECONDS = 120
|
||||
private const val SECRET_TIMEOUT_SECONDS = 300
|
||||
|
||||
private data class GatewayToolIdentity(
|
||||
val name: String,
|
||||
val argsPreview: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Older Tool Search gateways can expose the model-visible `tool_call` bridge
|
||||
* instead of the effective tool identity that current upstream callbacks use.
|
||||
* Unwrap only the bridge's explicit structured `{name, arguments}` envelope;
|
||||
* never infer a tool from prompt text or result content.
|
||||
*/
|
||||
private fun JsonObject?.effectiveToolIdentity(): GatewayToolIdentity {
|
||||
val outerName = string("name") ?: "unknown"
|
||||
val outerArgs = this?.get("args") as? JsonObject
|
||||
if (outerName != "tool_call" || outerArgs == null) {
|
||||
return GatewayToolIdentity(outerName, null)
|
||||
}
|
||||
val effectiveName = outerArgs.string("name")
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
?: return GatewayToolIdentity(outerName, null)
|
||||
val effectiveArgs = outerArgs["arguments"]
|
||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||
?.toString()
|
||||
?.takeIf { it.isNotBlank() && it != "null" }
|
||||
return GatewayToolIdentity(effectiveName, effectiveArgs)
|
||||
}
|
||||
|
||||
private fun JsonObject?.string(key: String): String? =
|
||||
(this?.get(key) as? JsonPrimitive)?.contentOrNull
|
||||
|
||||
|
||||
@@ -726,10 +726,10 @@ class HermesApiClient(
|
||||
|
||||
suspend fun getMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||
loadSessionMessages(mode) { page ->
|
||||
runCatching {
|
||||
try {
|
||||
val url = "$baseUrl/api/sessions/$sessionId/messages".toHttpUrlOrNull()
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("limit", page.limit.toString())
|
||||
@@ -740,14 +740,20 @@ class HermesApiClient(
|
||||
val request = authRequest(url.toString()).get().build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) error("HTTP ${response.code}")
|
||||
val body = response.body?.string() ?: error("empty response body")
|
||||
val body = response.body.readUtf8Bounded(
|
||||
DashboardApiClient.MAX_JSON_RESPONSE_BYTES,
|
||||
)
|
||||
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||
SessionMessagePage(
|
||||
messages = parsed.data ?: parsed.items ?: parsed.messages ?: emptyList(),
|
||||
pagination = parsed.pagination,
|
||||
payloadChars = body.length,
|
||||
)
|
||||
}
|
||||
}.let { Result.success(it) }
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}.getOrElse { error ->
|
||||
if (error is CancellationException) throw error
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ internal suspend fun loadSessionMessages(
|
||||
Result.success(collected)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -195,7 +195,7 @@ class StandardHermesVoiceClient(
|
||||
.let { Result.success<VoiceSpeechStream?>(it) }
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: Throwable) {
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,9 @@ class StandardHermesVoiceClient(
|
||||
if (!response.isSuccessful) {
|
||||
return Result.failure(apiFailure(response, operation))
|
||||
}
|
||||
val body = response.body.string()
|
||||
val body = response.body.readUtf8Bounded(
|
||||
DashboardApiClient.MAX_JSON_RESPONSE_BYTES,
|
||||
)
|
||||
if (body.isBlank()) {
|
||||
return Result.failure(IOException("$operation returned an empty response"))
|
||||
}
|
||||
@@ -245,7 +247,11 @@ class StandardHermesVoiceClient(
|
||||
}
|
||||
|
||||
private fun apiFailure(response: Response, operation: String): IOException {
|
||||
val body = runCatching { response.body.string() }.getOrDefault("")
|
||||
val body = try {
|
||||
response.body.readUtf8Bounded(4L * 1024L)
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
val detail = body.takeIf { it.isNotBlank() } ?: response.message
|
||||
val message = when (response.code) {
|
||||
400 -> "$operation rejected that input - ${detail.ifBlank { "bad request" }}"
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.hermesandroid.relay.ui.theme.appearanceTopRoundedCornerShape
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
|
||||
private val COMPOSER_TRAY_UNDERLAP = 12.dp
|
||||
|
||||
/** A separate rear surface tucked beneath the composer's foreground edge. */
|
||||
@Composable
|
||||
fun ChatComposerLayers(
|
||||
action: BusyMessageAction?,
|
||||
onActionChange: (BusyMessageAction) -> Unit,
|
||||
correctionAvailable: Boolean,
|
||||
onStop: (() -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(-COMPOSER_TRAY_UNDERLAP),
|
||||
) {
|
||||
if (action != null) {
|
||||
ChatBusyActionSelector(
|
||||
action, onActionChange,
|
||||
correctionAvailable = correctionAvailable,
|
||||
onStop = onStop,
|
||||
bottomUnderlap = COMPOSER_TRAY_UNDERLAP,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).zIndex(0f),
|
||||
)
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().zIndex(1f).testTag("chatComposerForeground")) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Compact current intent; optional plain-text choices slide out from behind it. */
|
||||
@Composable
|
||||
fun ChatBusyActionSelector(
|
||||
action: BusyMessageAction,
|
||||
onActionChange: (BusyMessageAction) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
correctionAvailable: Boolean = true,
|
||||
onStop: (() -> Unit)? = null,
|
||||
bottomUnderlap: Dp = 0.dp,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
BackHandler(enabled = expanded) { expanded = false }
|
||||
Surface(
|
||||
modifier = modifier.testTag("chatBusyActionTray"),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLow.copy(alpha = 0.82f),
|
||||
shape = appearanceTopRoundedCornerShape(12.dp),
|
||||
tonalElevation = 0.dp,
|
||||
) {
|
||||
Column(Modifier.padding(bottom = bottomUnderlap)) {
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically(tween(220), expandFrom = Alignment.Bottom) +
|
||||
slideInVertically(tween(220)) { it } + fadeIn(tween(160)),
|
||||
exit = shrinkVertically(tween(180), shrinkTowards = Alignment.Bottom) +
|
||||
slideOutVertically(tween(180)) { it } + fadeOut(tween(120)),
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().testTag("chatBusyActionDrawer").padding(horizontal = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
BusyMessageAction.entries.forEach { option ->
|
||||
val available = option == BusyMessageAction.QueueNext || correctionAvailable
|
||||
Row(
|
||||
Modifier.weight(1f).heightIn(min = 48.dp)
|
||||
.testTag("chatBusyAction-${option.storedValue}")
|
||||
.selectable(selected = option == action, enabled = available, role = Role.RadioButton) {
|
||||
onActionChange(option)
|
||||
expanded = false
|
||||
}.padding(horizontal = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (option == action) {
|
||||
Icon(Icons.Default.Check, null, Modifier.size(14.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurface)
|
||||
} else Spacer(Modifier.size(14.dp))
|
||||
Text(
|
||||
stringResource(if (option == BusyMessageAction.CorrectNow) R.string.chat_correct_now else R.string.chat_queue_next),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (available) 1f else 0.38f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
Modifier.weight(1f).heightIn(min = 40.dp)
|
||||
.testTag("chatBusyActionTrigger")
|
||||
.clickable(role = Role.Button) { expanded = !expanded },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(if (action == BusyMessageAction.CorrectNow) R.string.chat_correct_now else R.string.chat_queue_next),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Icon(
|
||||
if (expanded) Icons.Default.ExpandMore else Icons.Default.ExpandLess,
|
||||
null, Modifier.size(14.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (onStop != null) {
|
||||
IconButton(onClick = onStop) {
|
||||
Icon(Icons.Default.Stop, stringResource(R.string.chat_input_stop_streaming), Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ChatMessageQueue(
|
||||
messages: List<String>,
|
||||
paused: Boolean,
|
||||
onResume: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
onEdit: (Int) -> Unit,
|
||||
onRemove: (Int) -> Unit,
|
||||
canEdit: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (messages.isEmpty()) return
|
||||
Column(modifier) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
if (paused) stringResource(R.string.chat_queue_paused)
|
||||
else pluralStringResource(R.plurals.chat_queue_count, messages.size, messages.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (paused) TextButton(onClick = onResume) { Text(stringResource(R.string.chat_queue_resume)) }
|
||||
TextButton(onClick = onClear) { Text(stringResource(R.string.chat_clear)) }
|
||||
}
|
||||
Column(
|
||||
Modifier.heightIn(max = 144.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
messages.forEachIndexed { index, text ->
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
text = text,
|
||||
maxLines = 2,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f)
|
||||
.clickable(enabled = canEdit, role = Role.Button) { onEdit(index) }
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
IconButton(onClick = { onRemove(index) }) {
|
||||
Icon(Icons.Default.Close, stringResource(R.string.chat_queue_remove))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,13 @@ fun ChatFailurePanel(
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.chat_failure_title),
|
||||
text = stringResource(
|
||||
if (isInferenceUnavailableFailure(failure.rawError)) {
|
||||
R.string.chat_failure_inference_unavailable
|
||||
} else {
|
||||
R.string.chat_failure_title
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
@@ -148,3 +154,10 @@ internal fun failureIdentity(route: String, model: String?, provider: String?):
|
||||
provider?.trim()?.takeIf { it.isNotEmpty() },
|
||||
model?.trim()?.takeIf { it.isNotEmpty() },
|
||||
).distinct().joinToString(" · ")
|
||||
|
||||
internal fun isInferenceUnavailableFailure(rawError: String): Boolean {
|
||||
val message = rawError.lowercase()
|
||||
return "agent init failed" in message ||
|
||||
"no codex credentials stored" in message ||
|
||||
"runtime resolution still failed" in message
|
||||
}
|
||||
|
||||
@@ -505,15 +505,17 @@ private fun RelayServerImage(
|
||||
phase = withContext(Dispatchers.IO) {
|
||||
val result = try {
|
||||
resolver.fetch(image.src)
|
||||
} catch (t: Throwable) {
|
||||
ServerImageResult.Failure(t.message ?: "relay fetch failed")
|
||||
} catch (error: Exception) {
|
||||
ServerImageResult.Failure(error.message ?: "relay fetch failed")
|
||||
}
|
||||
when (result) {
|
||||
is ServerImageResult.Success -> {
|
||||
val cachedUri = Uri.parse(result.cachedUri)
|
||||
val bmp = runCatching {
|
||||
decodeOrientedBitmap(context, cachedUri)
|
||||
}.getOrNull()?.asImageBitmap()
|
||||
val bmp = try {
|
||||
decodeBoundedOrientedBitmap(context, cachedUri)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}?.asImageBitmap()
|
||||
if (bmp != null) {
|
||||
putInlineImage(image.src, bmp, result.sensitive)
|
||||
RelayImagePhase.Loaded(bmp, result.sensitive)
|
||||
|
||||
@@ -170,7 +170,11 @@ fun ChatImageViewer(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
val bytes = try {
|
||||
source.bytesProvider()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
busy = false
|
||||
if (bytes == null) {
|
||||
toast(context, errorMsg)
|
||||
@@ -195,7 +199,11 @@ fun ChatImageViewer(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
val bytes = try {
|
||||
source.bytesProvider()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
if (bytes == null) {
|
||||
busy = false
|
||||
toast(context, errorMsg)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.tween
|
||||
@@ -191,6 +192,9 @@ fun ChatInputBar(
|
||||
physicalEnterSends: Boolean = true,
|
||||
largePasteThreshold: Int? = null,
|
||||
onLargePaste: (String) -> Unit = {},
|
||||
busyAction: BusyMessageAction? = null,
|
||||
correctionAvailable: Boolean = true,
|
||||
onBusyActionChange: (BusyMessageAction) -> Unit = {},
|
||||
) {
|
||||
val canSubmit = enabled && submitEnabled && trailing in setOf(
|
||||
ChatInputTrailing.SEND,
|
||||
@@ -236,7 +240,7 @@ fun ChatInputBar(
|
||||
// Correction and queueing are materially different actions. Keep the
|
||||
// explanation, but lead with a visible state pill so the distinction
|
||||
// does not depend on the trailing icon or accent color alone.
|
||||
AnimatedVisibility(visible = caption != null) {
|
||||
AnimatedVisibility(visible = caption != null && busyAction == null) {
|
||||
val detail = caption ?: lastCaption.orEmpty()
|
||||
val actionLabel = when (trailing) {
|
||||
ChatInputTrailing.STEER -> stringResource(R.string.chat_input_steer_response)
|
||||
@@ -319,6 +323,12 @@ fun ChatInputBar(
|
||||
)
|
||||
}
|
||||
|
||||
ChatComposerLayers(
|
||||
action = busyAction,
|
||||
onActionChange = onBusyActionChange,
|
||||
correctionAvailable = correctionAvailable,
|
||||
onStop = onStop.takeUnless { trailing == ChatInputTrailing.STOP },
|
||||
) {
|
||||
Surface(
|
||||
shape = appearanceComposerShape(),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
@@ -646,6 +656,7 @@ fun ChatInputBar(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class LargeTextInsertion(
|
||||
val insertedText: String,
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -303,19 +304,21 @@ private fun ImageRender(
|
||||
}
|
||||
LaunchedEffect(attachment.cachedUri, attachment.content) {
|
||||
val decoded = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
try {
|
||||
when {
|
||||
!attachment.cachedUri.isNullOrBlank() ->
|
||||
decodeOrientedBitmap(context, Uri.parse(attachment.cachedUri))
|
||||
decodeBoundedOrientedBitmap(context, Uri.parse(attachment.cachedUri))
|
||||
?.asImageBitmap()
|
||||
attachment.content.isNotBlank() ->
|
||||
android.util.Base64.decode(
|
||||
attachment.content,
|
||||
android.util.Base64.DEFAULT,
|
||||
).let { decodeOrientedBitmap(it)?.asImageBitmap() }
|
||||
).let { decodeBoundedOrientedBitmap(it)?.asImageBitmap() }
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
if (decoded != null) bitmap = decoded else decodeFailed = true
|
||||
}
|
||||
@@ -375,6 +378,8 @@ private fun ImageRender(
|
||||
contentDescription = attachment.fileName,
|
||||
modifier = Modifier
|
||||
.widthIn(max = maxWidth)
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(bmp.width.toFloat() / bmp.height.coerceAtLeast(1))
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.combinedClickable(
|
||||
onClick = {
|
||||
@@ -391,7 +396,7 @@ private fun ImageRender(
|
||||
},
|
||||
onLongClick = { menuExpanded = true },
|
||||
),
|
||||
contentScale = ContentScale.FillWidth,
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
// One-tap save overlay — hidden while the blur cover is up so it
|
||||
@@ -683,7 +688,11 @@ private fun rememberAttachmentThumbnail(attachment: Attachment): ImageBitmap? {
|
||||
}
|
||||
LaunchedEffect(attachment.cachedUri, attachment.content, attachment.renderMode) {
|
||||
thumb = withContext(Dispatchers.IO) {
|
||||
runCatching { generateThumbnail(context, attachment) }.getOrNull()
|
||||
try {
|
||||
generateThumbnail(context, attachment)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
return thumb
|
||||
|
||||
@@ -46,7 +46,11 @@ internal fun decodeInlineImageDataUrl(
|
||||
// ceil(maxBytes / 3) * 4 plus at most two trailing padding characters.
|
||||
val maxEncoded = ((maxBytes.toLong() + 2L) / 3L) * 4L
|
||||
if (encoded.length.toLong() > maxEncoded) return null
|
||||
val bytes = runCatching { Base64.getDecoder().decode(encoded) }.getOrNull() ?: return null
|
||||
val bytes = try {
|
||||
Base64.getDecoder().decode(encoded)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
return null
|
||||
}
|
||||
if (bytes.isEmpty() || bytes.size > maxBytes || !matchesImageMagic(mime, bytes)) return null
|
||||
return DecodedInlineImageData(bytes, mime)
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ fun MarkdownContent(
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
ConfiguredMarkdownContent(
|
||||
content = content,
|
||||
content = markdownRenderWindow(content),
|
||||
textColor = textColor,
|
||||
modifier = modifier,
|
||||
)
|
||||
@@ -318,7 +318,7 @@ fun StreamingMarkdownContent(
|
||||
var generation by remember { mutableIntStateOf(0) }
|
||||
key(generation) {
|
||||
NativeStreamingMarkdownGeneration(
|
||||
content = content.withoutLeadingBlankLines(),
|
||||
content = markdownRenderWindow(content.withoutLeadingBlankLines()),
|
||||
textColor = textColor,
|
||||
modifier = modifier,
|
||||
onResetRequired = { generation += 1 },
|
||||
@@ -353,6 +353,17 @@ private fun NativeStreamingMarkdownGeneration(
|
||||
)
|
||||
}
|
||||
|
||||
internal const val MAX_RENDERED_MARKDOWN_CHARS = 256_000
|
||||
private const val MARKDOWN_TRUNCATION_NOTICE =
|
||||
"\n\n---\n_Response display was shortened for Android memory safety._"
|
||||
|
||||
internal fun markdownRenderWindow(content: String): String =
|
||||
if (content.length <= MAX_RENDERED_MARKDOWN_CHARS) {
|
||||
content
|
||||
} else {
|
||||
content.take(MAX_RENDERED_MARKDOWN_CHARS) + MARKDOWN_TRUNCATION_NOTICE
|
||||
}
|
||||
|
||||
internal data class StreamingMarkdownAppendPlan(
|
||||
val resetRequired: Boolean,
|
||||
val delta: String,
|
||||
|
||||
@@ -856,13 +856,13 @@ fun MessageBubble(
|
||||
}
|
||||
}
|
||||
|
||||
// Delivery status — only on agent-Thread reply bubbles (a user
|
||||
// message routed over the relay proactive channel). Null on every
|
||||
// ordinary chat message, which render nothing here.
|
||||
// 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),
|
||||
|
||||
+3
-1
@@ -18,6 +18,7 @@ import androidx.compose.material3.minimumInteractiveComponentSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -57,6 +58,7 @@ fun MessageDeliveryIndicator(
|
||||
modifier: Modifier = Modifier,
|
||||
failureMessage: String? = null,
|
||||
onRetry: (() -> Unit)? = null,
|
||||
contentColor: Color? = null,
|
||||
) {
|
||||
val retryAction = onRetry.takeIf { status == MessageDeliveryStatus.FAILED }
|
||||
val retryable = retryAction != null
|
||||
@@ -67,7 +69,7 @@ fun MessageDeliveryIndicator(
|
||||
retryable = retryable,
|
||||
)
|
||||
val presentation = messageDeliveryPresentation(status)
|
||||
val tint = when (presentation.colorRole) {
|
||||
val tint = contentColor ?: when (presentation.colorRole) {
|
||||
DeliveryColorRole.NEUTRAL -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
DeliveryColorRole.ACCENT -> MaterialTheme.colorScheme.primary
|
||||
DeliveryColorRole.QUEUED -> MaterialTheme.colorScheme.tertiary
|
||||
|
||||
+72
-20
@@ -27,6 +27,11 @@ internal fun imageOrientationTransform(orientation: Int): ImageOrientationTransf
|
||||
else -> ImageOrientationTransform()
|
||||
}
|
||||
|
||||
internal fun shouldApplyExifOrientation(mimeType: String?): Boolean = when (mimeType?.lowercase()) {
|
||||
"image/png", "image/gif", "image/bmp" -> false
|
||||
else -> true
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode image bytes for display and apply their EXIF orientation. BitmapFactory
|
||||
* returns the stored pixel layout and otherwise leaves portrait phone photos
|
||||
@@ -43,14 +48,16 @@ internal fun decodeOrientedBitmap(
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
} ?: return null
|
||||
|
||||
val orientation = runCatching {
|
||||
val orientation = try {
|
||||
ByteArrayInputStream(bytes).use { stream ->
|
||||
ExifInterface(stream).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
}
|
||||
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
||||
} catch (_: Exception) {
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
}
|
||||
val transform = imageOrientationTransform(orientation)
|
||||
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
||||
|
||||
@@ -58,26 +65,53 @@ internal fun decodeOrientedBitmap(
|
||||
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
||||
if (transform.flipHorizontal) postScale(-1f, 1f)
|
||||
}
|
||||
return runCatching {
|
||||
val oriented = try {
|
||||
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||
}.getOrNull()?.also { oriented ->
|
||||
if (oriented !== decoded) decoded.recycle()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return oriented?.also { bitmap ->
|
||||
if (bitmap !== decoded) decoded.recycle()
|
||||
} ?: decoded
|
||||
}
|
||||
|
||||
/** Decode a cached content URI without first copying the encoded file into RAM. */
|
||||
internal fun decodeOrientedBitmap(context: Context, uri: Uri): Bitmap? {
|
||||
val decoded = context.contentResolver.openFileDescriptor(uri, "r")?.use { descriptor ->
|
||||
BitmapFactory.decodeFileDescriptor(descriptor.fileDescriptor)
|
||||
/** Decode a cached content URI without copying the encoded file into RAM. */
|
||||
internal fun decodeOrientedBitmap(context: Context, uri: Uri): Bitmap? =
|
||||
decodeBoundedOrientedBitmap(context, uri)
|
||||
|
||||
internal fun decodeBoundedOrientedBitmap(context: Context, uri: Uri): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
val boundsInput = context.contentResolver.openInputStream(uri) ?: return null
|
||||
boundsInput.use { input ->
|
||||
// Bounds-only decode deliberately returns null; the populated Options
|
||||
// are the result and must not be treated as a decode failure.
|
||||
BitmapFactory.decodeStream(input, null, bounds)
|
||||
}
|
||||
val sample = inlineImageSampleSize(bounds.outWidth, bounds.outHeight) ?: return null
|
||||
val decoded = context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
BitmapFactory.decodeStream(
|
||||
input,
|
||||
null,
|
||||
BitmapFactory.Options().apply {
|
||||
inSampleSize = sample
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
},
|
||||
)
|
||||
} ?: return null
|
||||
val orientation = runCatching {
|
||||
context.contentResolver.openFileDescriptor(uri, "r")?.use { descriptor ->
|
||||
ExifInterface(descriptor.fileDescriptor).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
}
|
||||
}.getOrNull() ?: ExifInterface.ORIENTATION_NORMAL
|
||||
val orientation = if (shouldApplyExifOrientation(bounds.outMimeType)) {
|
||||
try {
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
ExifInterface(input).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} ?: ExifInterface.ORIENTATION_NORMAL
|
||||
} else {
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
}
|
||||
val transform = imageOrientationTransform(orientation)
|
||||
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
||||
|
||||
@@ -85,9 +119,27 @@ internal fun decodeOrientedBitmap(context: Context, uri: Uri): Bitmap? {
|
||||
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
||||
if (transform.flipHorizontal) postScale(-1f, 1f)
|
||||
}
|
||||
return runCatching {
|
||||
val oriented = try {
|
||||
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||
}.getOrNull()?.also { oriented ->
|
||||
if (oriented !== decoded) decoded.recycle()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return oriented?.also { bitmap ->
|
||||
if (bitmap !== decoded) decoded.recycle()
|
||||
} ?: decoded
|
||||
}
|
||||
|
||||
/** Decode an encoded chat image only after bounding its decoded pixel footprint. */
|
||||
internal fun decodeBoundedOrientedBitmap(bytes: ByteArray): Bitmap? {
|
||||
if (bytes.isEmpty()) return null
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
val sample = inlineImageSampleSize(bounds.outWidth, bounds.outHeight) ?: return null
|
||||
return decodeOrientedBitmap(
|
||||
bytes,
|
||||
BitmapFactory.Options().apply {
|
||||
inSampleSize = sample
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
+6
-4
@@ -296,12 +296,12 @@ internal fun formatAttachmentSize(bytes: Long): String {
|
||||
|
||||
private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageBitmap? =
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
try {
|
||||
val bytes = Base64.decode(attachment.content, Base64.DEFAULT)
|
||||
if (bytes.isEmpty()) return@runCatching null
|
||||
if (bytes.isEmpty()) return@withContext null
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@runCatching null
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null
|
||||
|
||||
var sample = 1
|
||||
while (
|
||||
@@ -314,7 +314,9 @@ private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageB
|
||||
bytes,
|
||||
BitmapFactory.Options().apply { inSampleSize = sample },
|
||||
)?.asImageBitmap()
|
||||
}.getOrNull()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface PendingPreviewState {
|
||||
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.fillMaxHeight
|
||||
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.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
@@ -39,6 +40,9 @@ import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CenterFocusStrong
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
@@ -48,10 +52,11 @@ import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
@@ -77,6 +82,7 @@ import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
@@ -145,8 +151,7 @@ fun VoiceModeOverlay(
|
||||
onModeChange: (InteractionMode) -> Unit,
|
||||
onClearError: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
// Nullable so existing call sites compile; when wired, voice errors
|
||||
// surface as global snackbars in addition to the inline banner below.
|
||||
// Retained for callers; uiState.error owns the modal while voice is visible.
|
||||
errorEvents: SharedFlow<HumanError>? = null,
|
||||
// === PHASE3-voice-mode-transcript ===
|
||||
// Compact rolling transcript of the last N chat messages — the
|
||||
@@ -255,7 +260,7 @@ fun VoiceModeOverlay(
|
||||
)
|
||||
}
|
||||
|
||||
// Voice errors surface ONLY on the overlay's own inline top banner
|
||||
// Voice errors surface ONLY in the overlay's dialog
|
||||
// (uiState.error) while the overlay is up — we deliberately do NOT also pipe
|
||||
// them to the app-wide bottom snackbar. Doing both duplicated the message
|
||||
// and left a retry-only, un-dismissable toast at the bottom during long /
|
||||
@@ -510,59 +515,15 @@ fun VoiceModeOverlay(
|
||||
)
|
||||
}
|
||||
|
||||
// Error banner
|
||||
AnimatedVisibility(
|
||||
visible = uiState.error != null,
|
||||
enter = fadeIn(),
|
||||
exit = fadeOut(),
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopCenter)
|
||||
.then(
|
||||
responsiveLayout.chromeMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(top = 64.dp, start = 16.dp, end = 16.dp),
|
||||
) {
|
||||
Surface(
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
tonalElevation = 2.dp,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = uiState.error.orEmpty(),
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// Dismiss clears the error and returns to Idle without
|
||||
// retrying, so a failed/timed-out turn never traps the user
|
||||
// on a retry-only banner.
|
||||
TextButton(onClick = { onClearError() }) {
|
||||
Text(stringResource(R.string.common_dismiss))
|
||||
}
|
||||
TextButton(
|
||||
onClick = {
|
||||
onClearError()
|
||||
onMicTap()
|
||||
},
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Refresh,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(Modifier.size(4.dp))
|
||||
Text(stringResource(R.string.voice_overlay_retry))
|
||||
}
|
||||
}
|
||||
}
|
||||
uiState.error?.let { error ->
|
||||
VoiceErrorDialog(
|
||||
error = error,
|
||||
onDismiss = onClearError,
|
||||
onRetry = {
|
||||
onClearError()
|
||||
onMicTap()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Mic button — dispatch by current voice state.
|
||||
@@ -589,6 +550,60 @@ fun VoiceModeOverlay(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceErrorDialog(
|
||||
error: String,
|
||||
onDismiss: () -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
) {
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
LaunchedEffect(error) { keyboard?.hide() }
|
||||
|
||||
// Match ChatFailureDetailsDialog: keep provider detail selectable and inside
|
||||
// a bounded surface, with actions outside the scroll area. A real dialog
|
||||
// owns focus and blocks the underlying chat in both voice presentations.
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
title = { Text(stringResource(R.string.voice_overlay_error_title)) },
|
||||
text = {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = MaterialTheme.shapes.small,
|
||||
) {
|
||||
SelectionContainer {
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 320.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = onRetry) {
|
||||
Text(stringResource(R.string.voice_overlay_retry))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(stringResource(R.string.common_dismiss))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceFocusIdentityPane(
|
||||
uiState: VoiceUiState,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import com.hermesandroid.relay.data.canCorrectBusyMessage
|
||||
import com.hermesandroid.relay.ui.components.ChatComposerLayers
|
||||
import com.hermesandroid.relay.ui.components.ChatMessageQueue
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -85,6 +89,7 @@ fun BotChatScreen(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||
ChatMediaViewerHost(route.key, sessionId) {
|
||||
BotChatScreen(
|
||||
route = route,
|
||||
@@ -103,6 +108,7 @@ fun BotChatScreen(
|
||||
)
|
||||
},
|
||||
profileIconFlow = connectionViewModel::profileIconFlow,
|
||||
busyMessageAction = busyMessageAction,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -120,6 +126,7 @@ internal fun BotChatScreen(
|
||||
handlerFactory: () -> ChatHandler,
|
||||
historyLoader: BotChatHistoryLoader,
|
||||
profileIconFlow: BotChatProfileIconFlow,
|
||||
busyMessageAction: BusyMessageAction = BusyMessageAction.CorrectNow,
|
||||
) {
|
||||
val handler = remember(route.key) { handlerFactory() }
|
||||
val context = LocalContext.current
|
||||
@@ -136,6 +143,21 @@ internal fun BotChatScreen(
|
||||
.collectAsState(initial = null)
|
||||
val listState = rememberLazyListState()
|
||||
var composer by remember(route.key, sessionId) { mutableStateOf("") }
|
||||
var editingQueuedMessage by remember(route.key, sessionId) { mutableStateOf(false) }
|
||||
var busyActionOverride by remember(route.key, sessionId, busyMessageAction) {
|
||||
mutableStateOf<BusyMessageAction?>(null)
|
||||
}
|
||||
val steerable by chatViewModel.steerableTurn.collectAsState()
|
||||
val attachments by chatViewModel.pendingAttachments.collectAsState()
|
||||
val pendingAsk by chatViewModel.pendingAsk.collectAsState()
|
||||
val turnStatus by handler.turnStatus.collectAsState()
|
||||
val queue by chatViewModel.queuedMessages.collectAsState()
|
||||
val queuePaused by chatViewModel.queuePaused.collectAsState()
|
||||
val correctionAvailable = canCorrectBusyMessage(
|
||||
steerable, attachments.isNotEmpty(), pendingAsk != null, turnStatus, composer,
|
||||
)
|
||||
val effectiveBusyAction = if (correctionAvailable && !editingQueuedMessage) busyActionOverride ?: busyMessageAction
|
||||
else BusyMessageAction.QueueNext
|
||||
|
||||
DisposableEffect(chatViewModel, gatewayClient, dashboardClient, route.key) {
|
||||
chatViewModel.initialize(apiClient = null, chatHandler = handler)
|
||||
@@ -237,49 +259,82 @@ internal fun BotChatScreen(
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
ChatComposerLayers(
|
||||
action = effectiveBusyAction.takeIf { isStreaming },
|
||||
onActionChange = {
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = it
|
||||
},
|
||||
correctionAvailable = correctionAvailable,
|
||||
onStop = if (composer.isNotBlank()) chatViewModel::cancelStream else null,
|
||||
modifier = Modifier.imePadding(),
|
||||
) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp),
|
||||
modifier = Modifier.imePadding(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = composer,
|
||||
onValueChange = { composer = it },
|
||||
placeholder = { Text(stringResource(R.string.chat_placeholder_message)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
minLines = 1,
|
||||
maxLines = 6,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isStreaming) {
|
||||
chatViewModel.cancelStream()
|
||||
} else {
|
||||
val text = composer.trim()
|
||||
if (text.isNotEmpty()) {
|
||||
composer = ""
|
||||
chatViewModel.sendMessage(text)
|
||||
}
|
||||
Column {
|
||||
ChatMessageQueue(
|
||||
messages = queue,
|
||||
paused = queuePaused,
|
||||
onResume = chatViewModel::resumeQueue,
|
||||
onClear = chatViewModel::clearQueue,
|
||||
onRemove = chatViewModel::removeQueuedAt,
|
||||
canEdit = composer.isBlank() && attachments.isEmpty(),
|
||||
onEdit = { index ->
|
||||
chatViewModel.takeQueuedForEdit(index)?.let {
|
||||
composer = it
|
||||
editingQueuedMessage = true
|
||||
}
|
||||
},
|
||||
enabled = isStreaming || composer.isNotBlank(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
) {
|
||||
Icon(
|
||||
if (isStreaming) Icons.Filled.Stop else Icons.AutoMirrored.Filled.Send,
|
||||
contentDescription = stringResource(
|
||||
if (isStreaming) R.string.chat_input_stop_streaming
|
||||
else R.string.chat_input_send_message,
|
||||
),
|
||||
OutlinedTextField(
|
||||
value = composer,
|
||||
onValueChange = { composer = it },
|
||||
placeholder = { Text(stringResource(R.string.chat_placeholder_message)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
minLines = 1,
|
||||
maxLines = 6,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isStreaming && composer.isBlank()) {
|
||||
chatViewModel.cancelStream()
|
||||
} else {
|
||||
val text = composer.trim()
|
||||
if (text.isNotEmpty()) {
|
||||
composer = ""
|
||||
chatViewModel.sendMessage(text, effectiveBusyAction)
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = null
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = isStreaming || composer.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
if (isStreaming && composer.isBlank()) Icons.Filled.Stop else Icons.AutoMirrored.Filled.Send,
|
||||
contentDescription = stringResource(
|
||||
when {
|
||||
isStreaming && composer.isBlank() -> R.string.chat_input_stop_streaming
|
||||
isStreaming && effectiveBusyAction == BusyMessageAction.CorrectNow -> R.string.chat_correct_now
|
||||
isStreaming -> R.string.chat_queue_next
|
||||
else -> R.string.chat_input_send_message
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Box(
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import com.hermesandroid.relay.data.canCorrectBusyMessage
|
||||
import com.hermesandroid.relay.ui.components.ChatMessageQueue
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.Canvas
|
||||
@@ -1138,6 +1141,12 @@ fun ChatScreen(
|
||||
|
||||
val availableSkills by chatViewModel.availableSkills.collectAsState()
|
||||
val queuedMessages by chatViewModel.queuedMessages.collectAsState()
|
||||
val queuePaused by chatViewModel.queuePaused.collectAsState()
|
||||
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||
var busyActionOverride by remember(currentSessionId, busyMessageAction) {
|
||||
mutableStateOf<BusyMessageAction?>(null)
|
||||
}
|
||||
var editingQueuedMessage by remember(currentSessionId) { mutableStateOf(false) }
|
||||
val recentPrompts by chatViewModel.recentPrompts.collectAsState()
|
||||
val recentPromptsEnabled by connectionViewModel.chatRecentPromptsEnabled.collectAsState()
|
||||
// Effective approval-bypass (server-computed: ORs global approvals.mode=off,
|
||||
@@ -4114,69 +4123,21 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(visible = queuedMessages.isNotEmpty()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = pluralStringResource(
|
||||
R.plurals.chat_queue_count,
|
||||
queuedMessages.size,
|
||||
queuedMessages.size,
|
||||
),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
TextButton(
|
||||
onClick = { chatViewModel.clearQueue() },
|
||||
modifier = Modifier.height(28.dp)
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.chat_clear),
|
||||
style = MaterialTheme.typography.labelSmall
|
||||
)
|
||||
}
|
||||
ChatMessageQueue(
|
||||
messages = queuedMessages,
|
||||
paused = queuePaused,
|
||||
onResume = chatViewModel::resumeQueue,
|
||||
onClear = chatViewModel::clearQueue,
|
||||
onRemove = chatViewModel::removeQueuedAt,
|
||||
canEdit = inputText.isBlank() && pendingAttachments.isEmpty(),
|
||||
onEdit = { index ->
|
||||
chatViewModel.takeQueuedForEdit(index)?.let {
|
||||
inputText = it
|
||||
editingQueuedMessage = true
|
||||
}
|
||||
// Per-item: tap the text to pull it back into the composer
|
||||
// for editing; ✕ to drop just that one. (Reorder omitted —
|
||||
// low value vs. drag-handle complexity on a transient queue.)
|
||||
queuedMessages.forEachIndexed { index, msg ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = msg,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clickable {
|
||||
chatViewModel.takeQueuedForEdit(index)?.let { t ->
|
||||
inputText = if (inputText.isBlank()) t else "$inputText $t"
|
||||
}
|
||||
}
|
||||
.padding(vertical = 4.dp),
|
||||
)
|
||||
TextButton(
|
||||
onClick = { chatViewModel.removeQueuedAt(index) },
|
||||
modifier = Modifier.height(28.dp),
|
||||
) {
|
||||
Text("✕", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp),
|
||||
)
|
||||
|
||||
val quoteYouLabel = stringResource(R.string.chat_quote_you)
|
||||
val quoteHermesLabel = stringResource(R.string.chat_quote_hermes)
|
||||
@@ -4285,25 +4246,32 @@ fun ChatScreen(
|
||||
// Gateway redirect is text-only. Attachment-bearing follow-ups must
|
||||
// retain their files in the session-owned queue instead of showing
|
||||
// a correction action that cannot carry them.
|
||||
val canSteerCurrentMessage = steerableTurn && pendingAttachments.isEmpty() &&
|
||||
val canSteerCurrentMessage = canCorrectBusyMessage(
|
||||
steerableTurn, pendingAttachments.isNotEmpty(), pendingAsk != null, turnStatus, inputText,
|
||||
) &&
|
||||
(!supervised || supervisedPolicy.capabilities.steerResponse)
|
||||
val effectiveBusyAction = if (canSteerCurrentMessage && !editingQueuedMessage) busyActionOverride ?: busyMessageAction
|
||||
else BusyMessageAction.QueueNext
|
||||
val correctCurrentMessage = canSteerCurrentMessage &&
|
||||
effectiveBusyAction == BusyMessageAction.CorrectNow
|
||||
val trailing = when {
|
||||
!isStreaming && hasContent -> ChatInputTrailing.SEND
|
||||
!isStreaming -> ChatInputTrailing.VOICE
|
||||
isStreaming && !hasContent -> ChatInputTrailing.STOP
|
||||
canSteerCurrentMessage -> ChatInputTrailing.STEER
|
||||
correctCurrentMessage -> ChatInputTrailing.STEER
|
||||
else -> ChatInputTrailing.QUEUE
|
||||
}
|
||||
val inputCaption = when {
|
||||
isStreaming && hasContent && canSteerCurrentMessage ->
|
||||
isStreaming && hasContent && correctCurrentMessage ->
|
||||
stringResource(R.string.chat_sends_now)
|
||||
isStreaming && hasContent && queuePaused -> stringResource(R.string.chat_queue_paused)
|
||||
isStreaming && hasContent -> stringResource(R.string.chat_delivered_after_turn)
|
||||
isStreaming && steerNotice != null -> steerNotice
|
||||
else -> null
|
||||
}
|
||||
val inputPlaceholder = when {
|
||||
editingMessage != null -> stringResource(R.string.chat_placeholder_edit)
|
||||
isStreaming && canSteerCurrentMessage -> stringResource(R.string.chat_placeholder_steer)
|
||||
isStreaming && correctCurrentMessage -> stringResource(R.string.chat_placeholder_steer)
|
||||
isStreaming -> stringResource(R.string.chat_placeholder_queue)
|
||||
else -> stringResource(R.string.chat_placeholder_message)
|
||||
}
|
||||
@@ -4555,6 +4523,12 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
ChatInputBar(
|
||||
busyAction = effectiveBusyAction.takeIf { isStreaming },
|
||||
correctionAvailable = canSteerCurrentMessage,
|
||||
onBusyActionChange = {
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = it
|
||||
},
|
||||
value = inputText,
|
||||
onValueChange = { inputText = it },
|
||||
placeholder = inputPlaceholder,
|
||||
@@ -4583,7 +4557,9 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
} else {
|
||||
chatViewModel.sendMessage(outboundText)
|
||||
chatViewModel.sendMessage(outboundText, effectiveBusyAction)
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = null
|
||||
inputText = ""
|
||||
finishSuccessfulSend()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.ui.components.ChatBusyActionSelector
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -499,6 +500,22 @@ fun ChatSettingsScreen(
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.chat_busy_default_title), style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
stringResource(R.string.chat_busy_default_description),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
ChatBusyActionSelector(
|
||||
action = busyMessageAction,
|
||||
onActionChange = connectionViewModel::setBusyMessageAction,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
HorizontalDivider()
|
||||
|
||||
val physicalKeyboardEnterBehavior by
|
||||
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
|
||||
@@ -14,6 +14,9 @@ import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
@@ -39,6 +42,7 @@ object MediaSaver {
|
||||
|
||||
private const val SAVE_SUBDIR = "Hermes-Relay"
|
||||
private const val SHARE_CACHE_DIR = "hermes-media"
|
||||
private const val MAX_IN_MEMORY_MEDIA_BYTES = 25L * 1024L * 1024L
|
||||
|
||||
private val httpClient: OkHttpClient by lazy {
|
||||
OkHttpClient.Builder()
|
||||
@@ -70,7 +74,10 @@ object MediaSaver {
|
||||
httpClient.newCall(request).execute().use { resp ->
|
||||
if (!resp.isSuccessful) error("HTTP ${resp.code}")
|
||||
val contentType = resp.header("Content-Type")?.substringBefore(';')?.trim()
|
||||
val body = resp.body.bytes()
|
||||
val responseBody = resp.body
|
||||
val body = responseBody.byteStream().use { input ->
|
||||
readBoundedBytes(input, responseBody.contentLength())
|
||||
}
|
||||
body to contentType
|
||||
}
|
||||
}
|
||||
@@ -78,11 +85,42 @@ object MediaSaver {
|
||||
/** Read the bytes behind a `content://` (or `file://`) [uri]. */
|
||||
suspend fun readUriBytes(context: Context, uri: Uri): ByteArray? =
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}.getOrNull()
|
||||
try {
|
||||
val declaredLength = context.contentResolver.openAssetFileDescriptor(uri, "r")
|
||||
?.use { it.length }
|
||||
?.takeIf { it >= 0L }
|
||||
?: -1L
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
readBoundedBytes(input, declaredLength)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun readBoundedBytes(input: InputStream, declaredLength: Long): ByteArray {
|
||||
if (declaredLength > MAX_IN_MEMORY_MEDIA_BYTES) {
|
||||
throw IOException("Media exceeds Android's in-memory export limit")
|
||||
}
|
||||
val initialSize = when {
|
||||
declaredLength in 1..MAX_IN_MEMORY_MEDIA_BYTES -> declaredLength.toInt()
|
||||
else -> DEFAULT_BUFFER_SIZE
|
||||
}
|
||||
val output = ByteArrayOutputStream(initialSize)
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
if (total > MAX_IN_MEMORY_MEDIA_BYTES) {
|
||||
throw IOException("Media exceeds Android's in-memory export limit")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
// --- Save ---------------------------------------------------------------
|
||||
|
||||
suspend fun saveImage(
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import com.hermesandroid.relay.data.canCorrectBusyMessage
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
@@ -745,6 +747,7 @@ class ChatViewModel : ViewModel() {
|
||||
private const val CHECKPOINT_WRITE_INTERVAL_MS = 750L
|
||||
private const val SESSION_REFRESH_RETRY_DELAY_MS = 1_000L
|
||||
private const val SESSION_REFRESH_MAX_READINESS_RETRIES = 2
|
||||
private const val MAX_COALESCED_SESSION_REFRESH_PASSES = 2
|
||||
private const val SESSION_DRAWER_FRESHNESS_WINDOW_MS = 5_000L
|
||||
private const val PROFILE_SESSION_CACHE_CONTEXTS = 24
|
||||
private const val PROFILE_SESSION_CACHE_ROWS = 50
|
||||
@@ -911,6 +914,10 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
|
||||
private val queuedMessageItems = mutableListOf<QueuedMessage>()
|
||||
private val pausedQueueDestinations = mutableSetOf<Pair<String, String>>()
|
||||
private val retainedQueueCheckpoints = mutableMapOf<Pair<String, String>, ChatTurnCheckpoint>()
|
||||
private val _queuePaused = MutableStateFlow(false)
|
||||
val queuePaused: StateFlow<Boolean> = _queuePaused.asStateFlow()
|
||||
private val completedQueueOwnerRuns = ConcurrentHashMap.newKeySet<String>()
|
||||
private val _queuedMessages = MutableStateFlow<List<String>>(emptyList())
|
||||
val queuedMessages: StateFlow<List<String>> = _queuedMessages.asStateFlow()
|
||||
@@ -3402,8 +3409,6 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
if (visibleSignature != serverSignature) {
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(storedSessionId)
|
||||
return@launch
|
||||
}
|
||||
if (attempt < 7 && retryUntilChanged) delay(250L)
|
||||
@@ -4037,7 +4042,7 @@ class ChatViewModel : ViewModel() {
|
||||
private suspend fun loadSessionHistory(
|
||||
sessionId: String,
|
||||
requireProfileScope: Boolean = false,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
profileName: String? = currentSessionProfileName(),
|
||||
): List<MessageItem> {
|
||||
if (profileMessageLoader != null) {
|
||||
@@ -4063,7 +4068,7 @@ class ChatViewModel : ViewModel() {
|
||||
private suspend fun loadGatewaySessionHistory(
|
||||
sessionId: String,
|
||||
requireProfileScope: Boolean = false,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
profileName: String? = currentSessionProfileName(),
|
||||
): List<MessageItem> {
|
||||
val scoped = profileMessageLoader?.invoke(profileName, sessionId, mode)
|
||||
@@ -4801,6 +4806,8 @@ class ChatViewModel : ViewModel() {
|
||||
publishBackgroundSessionActivity()
|
||||
queuedMessageItems.clear()
|
||||
completedQueueOwnerRuns.clear()
|
||||
pausedQueueDestinations.clear()
|
||||
retainedQueueCheckpoints.clear()
|
||||
publishQueuedMessages()
|
||||
_steerableTurn.value = false
|
||||
_steerNotice.value = null
|
||||
@@ -5331,11 +5338,13 @@ class ChatViewModel : ViewModel() {
|
||||
val sessionPageLoadFailed: StateFlow<Boolean> = _sessionPageLoadFailed.asStateFlow()
|
||||
val sessionListUnavailable: StateFlow<Boolean> = _sessionListUnavailable.asStateFlow()
|
||||
|
||||
fun refreshSessions() = refreshSessions(
|
||||
allowReadinessRetry = true,
|
||||
preserveFailurePresentation = false,
|
||||
readinessRetryAttempt = 0,
|
||||
)
|
||||
fun refreshSessions() {
|
||||
refreshSessions(
|
||||
allowReadinessRetry = true,
|
||||
preserveFailurePresentation = false,
|
||||
readinessRetryAttempt = 0,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Drawer-open freshness gate. Process-owned startup binding may already be
|
||||
@@ -5460,8 +5469,10 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
var retryUnavailable = false
|
||||
var retryReadiness = false
|
||||
var refreshPass = 0
|
||||
try {
|
||||
do {
|
||||
refreshPass += 1
|
||||
sessionRefreshPending = false
|
||||
// A queued trailing refresh owns a new outcome. Never let
|
||||
// an earlier timeout overwrite a later successful list.
|
||||
@@ -5559,7 +5570,7 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
} catch (e: Exception) {
|
||||
if (isCurrentRefresh()) {
|
||||
android.util.Log.w(
|
||||
"ChatViewModel",
|
||||
@@ -5582,7 +5593,11 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (sessionRefreshPending && isCurrentRefresh())
|
||||
} while (
|
||||
refreshPass < MAX_COALESCED_SESSION_REFRESH_PASSES &&
|
||||
sessionRefreshPending &&
|
||||
isCurrentRefresh()
|
||||
)
|
||||
} finally {
|
||||
val shouldRetry = allowReadinessRetry &&
|
||||
retryReadiness &&
|
||||
@@ -6303,7 +6318,11 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
// --- Message sending ---
|
||||
|
||||
fun sendMessage(text: String) {
|
||||
fun sendMessage(
|
||||
text: String,
|
||||
busyAction: BusyMessageAction =
|
||||
BusyMessageAction.CorrectNow,
|
||||
) {
|
||||
if (text.isBlank()) return
|
||||
supervisedMessageBlockReason(supervisedModePolicy, text)?.let { reason ->
|
||||
chatHandler?.addSystemNotice(reason)
|
||||
@@ -6390,9 +6409,13 @@ class ChatViewModel : ViewModel() {
|
||||
// Mid-turn: redirect on the gateway transport, queue everywhere else.
|
||||
if (activeStream != null) {
|
||||
if (
|
||||
_steerableTurn.value &&
|
||||
busyAction == BusyMessageAction.CorrectNow &&
|
||||
(!supervisedModePolicy.enabled || supervisedModePolicy.capabilities.steerResponse) &&
|
||||
streamingEndpoint == "gateway" &&
|
||||
_pendingAttachments.value.isEmpty()
|
||||
canCorrectBusyMessage(
|
||||
_steerableTurn.value, _pendingAttachments.value.isNotEmpty(),
|
||||
_pendingAsk.value != null, chatHandler?.turnStatus?.value, text,
|
||||
)
|
||||
) {
|
||||
steerActiveTurn(text.trim())
|
||||
} else {
|
||||
@@ -7572,8 +7595,7 @@ class ChatViewModel : ViewModel() {
|
||||
queuedMessages = queuedMessageItems
|
||||
.filter {
|
||||
it.contextKey == contextKey &&
|
||||
it.sessionId == sessionId &&
|
||||
it.ownerRunId == seed.userMessageId
|
||||
it.sessionId == sessionId
|
||||
}
|
||||
.map { item ->
|
||||
ChatQueuedMessageCheckpoint(
|
||||
@@ -7585,17 +7607,22 @@ class ChatViewModel : ViewModel() {
|
||||
hadAttachments = item.attachments.isNotEmpty(),
|
||||
)
|
||||
},
|
||||
queuePaused = (contextKey to sessionId) in pausedQueueDestinations,
|
||||
startedAt = seed.startedAt,
|
||||
updatedAt = now,
|
||||
)
|
||||
}
|
||||
|
||||
private fun restoreQueuedMessages(checkpoint: ChatTurnCheckpoint) {
|
||||
val destination = checkpoint.contextKey to checkpoint.sessionId
|
||||
if (checkpoint.queuePaused || checkpoint.queueOnly) pausedQueueDestinations += destination
|
||||
var droppedAttachmentQueue = false
|
||||
val droppedOwners = mutableMapOf<String, String>()
|
||||
checkpoint.queuedMessages.forEach { saved ->
|
||||
if (queuedMessageItems.any { it.id == saved.id }) return@forEach
|
||||
if (saved.hadAttachments) {
|
||||
droppedAttachmentQueue = true
|
||||
droppedOwners[saved.id] = droppedOwners[saved.ownerRunId] ?: saved.ownerRunId
|
||||
return@forEach
|
||||
}
|
||||
queuedMessageItems += QueuedMessage(
|
||||
@@ -7604,11 +7631,16 @@ class ChatViewModel : ViewModel() {
|
||||
contextKey = checkpoint.contextKey,
|
||||
sessionId = checkpoint.sessionId,
|
||||
transport = saved.transport,
|
||||
ownerRunId = saved.ownerRunId,
|
||||
ownerRunId = droppedOwners[saved.ownerRunId] ?: saved.ownerRunId,
|
||||
attachments = emptyList(),
|
||||
interfaceContextPrompt = saved.interfaceContextPrompt,
|
||||
)
|
||||
}
|
||||
if (checkpoint.queueOnly) {
|
||||
val ids = queuedMessageItems.mapTo(mutableSetOf()) { it.id }
|
||||
queuedMessageItems.filter { it.contextKey == checkpoint.contextKey && it.sessionId == checkpoint.sessionId }
|
||||
.map { it.ownerRunId }.filterNot { it in ids }.forEach { completedQueueOwnerRuns += it }
|
||||
}
|
||||
publishQueuedMessages()
|
||||
if (droppedAttachmentQueue) {
|
||||
_transientNotice.tryEmit(
|
||||
@@ -7643,10 +7675,12 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearTurnCheckpoint() {
|
||||
private fun clearTurnCheckpoint(preserveQueue: Boolean = false) {
|
||||
val queueSnapshot = if (preserveQueue) buildQueueOnlyCheckpoint() else null
|
||||
queueSnapshot?.let { retainedQueueCheckpoints[it.contextKey to it.sessionId] = it }
|
||||
val key = activeTurnCheckpointSeed?.let { seed ->
|
||||
seed.contextKey?.let { TurnCheckpointKey(it, seed.sessionId) }
|
||||
}
|
||||
} ?: queueSnapshot?.let { TurnCheckpointKey(it.contextKey, it.sessionId) }
|
||||
activeTurnCheckpointSeed = null
|
||||
activeQueueOwnerRunId = null
|
||||
val generation = checkpointGeneration.incrementAndGet()
|
||||
@@ -7663,7 +7697,8 @@ class ChatViewModel : ViewModel() {
|
||||
viewModelScope.launch {
|
||||
checkpointMutex.withLock {
|
||||
if (generation == checkpointGeneration.get() && activeTurnCheckpointSeed == null) {
|
||||
if (key != null) runCatching { store.remove(key.contextKey, key.sessionId) }
|
||||
if (queueSnapshot != null) runCatching { store.write(queueSnapshot) }
|
||||
else if (key != null) runCatching { store.remove(key.contextKey, key.sessionId) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7793,6 +7828,11 @@ class ChatViewModel : ViewModel() {
|
||||
backgroundNeedsInputKeys -= key
|
||||
publishBackgroundSessionActivity()
|
||||
if (checkpoint.transport !in setOf("gateway", "sessions")) return false
|
||||
if (checkpoint.queueOnly) {
|
||||
retainedQueueCheckpoints[contextKey to sessionId] = checkpoint
|
||||
restoreQueuedMessages(checkpoint)
|
||||
return false
|
||||
}
|
||||
if (activeStream != null) return true
|
||||
if (streamRecovery != null) {
|
||||
if (checkpoint.transport == "gateway" && client != null) {
|
||||
@@ -7806,7 +7846,13 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
adoptTurnCheckpoint(checkpoint)
|
||||
val initialHistory = runCatching { loadSessionHistory(sessionId) }.getOrDefault(emptyList())
|
||||
val initialHistory = try {
|
||||
loadSessionHistory(sessionId)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
if (!ownsTurnCheckpoint(checkpoint, handler)) return true
|
||||
if (initialHistory.isNotEmpty()) handler.loadMessageHistory(initialHistory)
|
||||
handler.restoreInFlightTurn(checkpoint)
|
||||
@@ -8219,7 +8265,7 @@ class ChatViewModel : ViewModel() {
|
||||
if (completedOwner != null && queuedMessageItems.any { it.ownerRunId == completedOwner }) {
|
||||
completedQueueOwnerRuns += completedOwner
|
||||
}
|
||||
clearTurnCheckpoint()
|
||||
clearTurnCheckpoint(preserveQueue = true)
|
||||
activeStream = null
|
||||
_steerableTurn.value = false
|
||||
_steerNotice.value = null
|
||||
@@ -8463,6 +8509,106 @@ class ChatViewModel : ViewModel() {
|
||||
it.contextKey == destination.first && it.sessionId == destination.second
|
||||
}.map(QueuedMessage::text)
|
||||
}
|
||||
_queuePaused.value = _queuedMessages.value.isNotEmpty() && destination in pausedQueueDestinations
|
||||
}
|
||||
|
||||
private fun persistQueueChanges() {
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
val destination = currentQueueDestination() ?: return
|
||||
if (activeTurnCheckpointSeed?.let { it.contextKey to it.sessionId } == destination) return
|
||||
val template = retainedQueueCheckpoints[destination] ?: return
|
||||
val items = queuedMessageItems.filter { it.contextKey to it.sessionId == destination }
|
||||
val snapshot = template.copy(
|
||||
queuePaused = destination in pausedQueueDestinations,
|
||||
queuedMessages = items.map { item ->
|
||||
ChatQueuedMessageCheckpoint(
|
||||
id = item.id,
|
||||
text = item.text.take(MAX_CHECKPOINT_TEXT_CHARS),
|
||||
transport = item.transport,
|
||||
ownerRunId = item.ownerRunId,
|
||||
interfaceContextPrompt = item.interfaceContextPrompt,
|
||||
hadAttachments = item.attachments.isNotEmpty(),
|
||||
)
|
||||
},
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
)
|
||||
if (items.isEmpty()) retainedQueueCheckpoints.remove(destination)
|
||||
else retainedQueueCheckpoints[destination] = snapshot
|
||||
val generation = checkpointGeneration.get()
|
||||
val store = chatTurnCheckpointStore ?: return
|
||||
viewModelScope.launch {
|
||||
checkpointMutex.withLock {
|
||||
if (generation != checkpointGeneration.get()) return@withLock
|
||||
runCatching {
|
||||
if (items.isEmpty()) store.remove(destination.first, destination.second)
|
||||
else store.write(snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildQueueOnlyCheckpoint(): ChatTurnCheckpoint? {
|
||||
val destination = currentQueueDestination() ?: return null
|
||||
val items = queuedMessageItems.filter { (it.contextKey to it.sessionId) == destination }
|
||||
if (items.isEmpty()) return null
|
||||
buildTurnCheckpoint()?.let { return it.copy(queueOnly = true, pendingAsk = null) }
|
||||
// A server-initiated turn has no outgoing user checkpoint. Retain only
|
||||
// queue ownership metadata; queueOnly restoration never renders these
|
||||
// empty turn fields or attempts to reattach the cancelled runtime.
|
||||
val now = System.currentTimeMillis()
|
||||
return ChatTurnCheckpoint(
|
||||
contextKey = destination.first,
|
||||
sessionId = destination.second,
|
||||
transport = items.first().transport,
|
||||
user = ChatTurnUserCheckpoint(items.first().ownerRunId, "", now),
|
||||
assistant = ChatTurnAssistantCheckpoint(id = items.first().ownerRunId, timestamp = now, isStreaming = false),
|
||||
priorUserMessageCount = 0,
|
||||
baselineAssistantCount = 0,
|
||||
queuedMessages = items.map { item ->
|
||||
ChatQueuedMessageCheckpoint(
|
||||
item.id, item.text.take(MAX_CHECKPOINT_TEXT_CHARS), item.transport,
|
||||
item.ownerRunId, item.interfaceContextPrompt, item.attachments.isNotEmpty(),
|
||||
)
|
||||
},
|
||||
queuePaused = destination in pausedQueueDestinations,
|
||||
queueOnly = true,
|
||||
startedAt = now,
|
||||
updatedAt = now,
|
||||
)
|
||||
}
|
||||
|
||||
/** Stop preserves pending work. Resume is explicit and always keeps its destination. */
|
||||
fun resumeQueue() {
|
||||
val destination = currentQueueDestination() ?: return
|
||||
val first = queuedMessageItems.firstOrNull { it.contextKey to it.sessionId == destination } ?: return
|
||||
if (activeStream != null) {
|
||||
val owner = activeQueueOwnerRunId ?: return
|
||||
val index = queuedMessageItems.indexOf(first)
|
||||
queuedMessageItems[index] = first.copy(ownerRunId = owner)
|
||||
} else {
|
||||
completedQueueOwnerRuns += first.ownerRunId
|
||||
}
|
||||
pausedQueueDestinations -= destination
|
||||
publishQueuedMessages()
|
||||
persistQueueChanges()
|
||||
drainQueue()
|
||||
}
|
||||
|
||||
private fun removeQueuedItem(item: QueuedMessage) {
|
||||
queuedMessageItems.removeAll { it.id == item.id }
|
||||
// Splice the run chain: successors now wait for the removed item's
|
||||
// predecessor, never for a deleted turn that can no longer complete.
|
||||
queuedMessageItems.replaceAll { next ->
|
||||
if (next.contextKey == item.contextKey && next.sessionId == item.sessionId && next.ownerRunId == item.id) {
|
||||
next.copy(ownerRunId = item.ownerRunId)
|
||||
} else next
|
||||
}
|
||||
if (queuedMessageItems.none { it.ownerRunId == item.ownerRunId }) completedQueueOwnerRuns -= item.ownerRunId
|
||||
if (queuedMessageItems.none { it.contextKey == item.contextKey && it.sessionId == item.sessionId }) {
|
||||
pausedQueueDestinations -= item.contextKey to item.sessionId
|
||||
}
|
||||
publishQueuedMessages()
|
||||
persistQueueChanges()
|
||||
}
|
||||
|
||||
private fun removeQueuedMessagesFor(contextKey: String?, sessionId: String): Int {
|
||||
@@ -8488,6 +8634,9 @@ class ChatViewModel : ViewModel() {
|
||||
fun clearQueue() {
|
||||
val destination = currentQueueDestination() ?: return
|
||||
removeQueuedMessagesFor(destination.first, destination.second)
|
||||
pausedQueueDestinations -= destination
|
||||
publishQueuedMessages()
|
||||
persistQueueChanges()
|
||||
}
|
||||
|
||||
/** Drop a single queued message by index (no-op if out of range). */
|
||||
@@ -8497,11 +8646,7 @@ class ChatViewModel : ViewModel() {
|
||||
it.contextKey == destination.first && it.sessionId == destination.second
|
||||
}
|
||||
val item = visible.getOrNull(index) ?: return
|
||||
queuedMessageItems.removeAll { it.id == item.id }
|
||||
if (queuedMessageItems.none { it.ownerRunId == item.ownerRunId }) {
|
||||
completedQueueOwnerRuns -= item.ownerRunId
|
||||
}
|
||||
publishQueuedMessages()
|
||||
removeQueuedItem(item)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -8509,14 +8654,15 @@ class ChatViewModel : ViewModel() {
|
||||
* the composer can prefill it. Null if the index is out of range.
|
||||
*/
|
||||
fun takeQueuedForEdit(index: Int): String? {
|
||||
if (_pendingAttachments.value.isNotEmpty()) {
|
||||
_transientNotice.tryEmit("Finish the current attachment draft before editing a queued message.")
|
||||
return null
|
||||
}
|
||||
val destination = currentQueueDestination() ?: return null
|
||||
val item = queuedMessageItems.filter {
|
||||
it.contextKey == destination.first && it.sessionId == destination.second
|
||||
}.getOrNull(index) ?: return null
|
||||
queuedMessageItems.removeAll { it.id == item.id }
|
||||
if (queuedMessageItems.none { it.ownerRunId == item.ownerRunId }) {
|
||||
completedQueueOwnerRuns -= item.ownerRunId
|
||||
}
|
||||
removeQueuedItem(item)
|
||||
_pendingAttachments.value = item.attachments
|
||||
nextInterfaceContextPrompt = item.interfaceContextPrompt
|
||||
publishQueuedMessages()
|
||||
@@ -8530,6 +8676,7 @@ class ChatViewModel : ViewModel() {
|
||||
if (streamingEndpoint == "gateway" && gatewayClient == null && client == null) return
|
||||
if (activeStream != null || streamRecovery != null) return
|
||||
val destination = currentQueueDestination() ?: return
|
||||
if (destination in pausedQueueDestinations) return
|
||||
val next = queuedMessageItems.firstOrNull {
|
||||
it.contextKey == destination.first &&
|
||||
it.sessionId == destination.second &&
|
||||
@@ -9760,6 +9907,11 @@ class ChatViewModel : ViewModel() {
|
||||
handler.onTurnComplete(currentMessageId)
|
||||
gatewayInterimMessageId = currentMessageId
|
||||
gatewayInterimSealedCurrentMessage = true
|
||||
// `message.interim` closes one assistant segment but not the
|
||||
// agent run. Create the next blank owner immediately so the chat
|
||||
// retains its in-conversation working indicator even when the
|
||||
// next tool/reasoning event is delayed or suppressed upstream.
|
||||
ensurePostInterimMessage()
|
||||
scheduleCheckpointWrite(immediate = true)
|
||||
}
|
||||
val onInterimReconciledCb = { text: String ->
|
||||
@@ -10125,12 +10277,16 @@ class ChatViewModel : ViewModel() {
|
||||
(streamingEndpoint == "sessions" || streamingEndpoint == "gateway")
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
try {
|
||||
// Profile-aware read — see onCompleteCb: a bare
|
||||
// getMessages 404s for a non-default-profile session
|
||||
// and silently empties the transcript.
|
||||
val serverMessages = loadSessionHistory(errorSessionId)
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (_: Exception) {
|
||||
// The existing local failure remains authoritative.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10586,7 +10742,7 @@ class ChatViewModel : ViewModel() {
|
||||
_steerableTurn.value = false
|
||||
onPreflightErrorCb(Exception(reason))
|
||||
},
|
||||
onPreflightFailure = {
|
||||
onPreflightFailure = { reason ->
|
||||
_steerableTurn.value = false
|
||||
if (intentionallyCancelled) {
|
||||
// User cancelled while preflight was in flight —
|
||||
@@ -10598,11 +10754,11 @@ class ChatViewModel : ViewModel() {
|
||||
// Nothing started server-side. Keep this turn bound
|
||||
// to Gateway and settle it as retryable local state;
|
||||
// API sessions are a different owner/database.
|
||||
onPreflightErrorCb(
|
||||
IllegalStateException(
|
||||
"Hermes Dashboard chat is unavailable. Sign in or reconnect, then retry.",
|
||||
),
|
||||
)
|
||||
// Preserve the authoritative Gateway explanation.
|
||||
// Inference initialization failures happen before
|
||||
// prompt.submit, and replacing them with generic
|
||||
// reconnect advice hides the actual operator fix.
|
||||
onPreflightErrorCb(IllegalStateException(reason))
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -10675,6 +10831,13 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
fun cancelStream() {
|
||||
intentionallyCancelled = true
|
||||
currentQueueDestination()?.let { destination ->
|
||||
if (queuedMessageItems.any { it.contextKey to it.sessionId == destination }) {
|
||||
pausedQueueDestinations += destination
|
||||
activeQueueOwnerRunId?.let { completedQueueOwnerRuns += it }
|
||||
}
|
||||
}
|
||||
publishQueuedMessages()
|
||||
// User Stop also aborts a dropped-stream answer recovery. settleUi
|
||||
// false: the Stopped-badge block below finalizes the placeholder
|
||||
// itself (completing it here first would hide it from findLast).
|
||||
@@ -10685,13 +10848,12 @@ class ChatViewModel : ViewModel() {
|
||||
activeStream = null
|
||||
imageActivityJob?.cancel()
|
||||
imageActivityJob = null
|
||||
clearQueue()
|
||||
_steerableTurn.value = false
|
||||
_steerNotice.value = null
|
||||
// Gateway cancel issues session.interrupt, which force-denies any
|
||||
// blocked approval server-side — stamp the card to match.
|
||||
clearPendingAskAfterInterrupt()
|
||||
clearTurnCheckpoint()
|
||||
clearTurnCheckpoint(preserveQueue = true)
|
||||
AppAnalytics.onStreamCancelled()
|
||||
chatHandler?.let { handler ->
|
||||
val streamingMsg = handler.messages.value.findLast { it.isStreaming }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import android.app.Application
|
||||
import android.os.Build
|
||||
import android.content.Context
|
||||
@@ -2387,13 +2388,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? = profileController.loadProfileScopedMessages(sessionId, mode)
|
||||
|
||||
suspend fun loadProfileScopedMessages(
|
||||
profileName: String?,
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? =
|
||||
profileController.loadProfileScopedMessages(profileName, sessionId, mode)
|
||||
|
||||
@@ -3090,6 +3091,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
|
||||
val busyMessageAction = chatInputPreferencesRepository.busyMessageAction
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, BusyMessageAction.CorrectNow)
|
||||
|
||||
fun setBusyMessageAction(action: BusyMessageAction) {
|
||||
viewModelScope.launch { chatInputPreferencesRepository.setBusyMessageAction(action) }
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: StateFlow<PhysicalKeyboardEnterBehavior> =
|
||||
chatInputPreferencesRepository.physicalKeyboardEnterBehavior
|
||||
.stateIn(
|
||||
|
||||
+2
-2
@@ -909,7 +909,7 @@ class ProfileController(
|
||||
*/
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? = loadProfileScopedMessages(
|
||||
profileName = resolveSessionProfileName(),
|
||||
sessionId = sessionId,
|
||||
@@ -919,7 +919,7 @@ class ProfileController(
|
||||
suspend fun loadProfileScopedMessages(
|
||||
profileName: String?,
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? {
|
||||
val connectionId = activeConnectionId.value ?: return null
|
||||
val dashboardUrl = activeDashboardUrlProvider() ?: return null
|
||||
|
||||
@@ -122,6 +122,7 @@
|
||||
<string name="chat_retry">Tentar novamente</string>
|
||||
<string name="chat_dismiss">Dispensar</string>
|
||||
<string name="chat_failure_title">O Hermes não conseguiu concluir esta resposta</string>
|
||||
<string name="chat_failure_inference_unavailable">Inferência indisponível</string>
|
||||
<string name="chat_failure_details">Detalhes</string>
|
||||
<string name="chat_failure_details_title">Falha na resposta</string>
|
||||
<string name="chat_failure_details_guidance">O Hermes relatou este erro. O app não mudará de rota nem de modelo automaticamente.</string>
|
||||
@@ -4420,4 +4421,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">Erro de voz</string>
|
||||
<string name="chat_correct_now">Corrigir agora</string>
|
||||
<string name="chat_queue_next">Enviar depois</string>
|
||||
<string name="chat_busy_default_title">Durante a resposta</string>
|
||||
<string name="chat_busy_default_description">Escolha o que Enviar faz enquanto o Hermes trabalha. Este padrão do dispositivo também vale no campo de mensagem. Anexos e correções indisponíveis entram na fila.</string>
|
||||
<string name="chat_queue_paused">Fila pausada</string>
|
||||
<string name="chat_queue_resume">Retomar</string>
|
||||
<string name="chat_queue_remove">Remover mensagem da fila</string>
|
||||
</resources>
|
||||
|
||||
@@ -136,6 +136,7 @@
|
||||
<string name="chat_retry">重试</string>
|
||||
<string name="chat_dismiss">关闭</string>
|
||||
<string name="chat_failure_title">Hermes 无法完成此回复</string>
|
||||
<string name="chat_failure_inference_unavailable">推理服务不可用</string>
|
||||
<string name="chat_failure_details">详情</string>
|
||||
<string name="chat_failure_details_title">回复失败</string>
|
||||
<string name="chat_failure_details_guidance">Hermes 报告了此错误。应用不会自动切换路由或模型。</string>
|
||||
@@ -4501,4 +4502,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">语音错误</string>
|
||||
<string name="chat_correct_now">立即纠正</string>
|
||||
<string name="chat_queue_next">稍后发送</string>
|
||||
<string name="chat_busy_default_title">回复期间</string>
|
||||
<string name="chat_busy_default_description">选择 Hermes 工作时发送按钮的行为。此设备默认设置与输入框共用。附件及无法立即纠正的消息将进入队列。</string>
|
||||
<string name="chat_queue_paused">队列已暂停</string>
|
||||
<string name="chat_queue_resume">继续</string>
|
||||
<string name="chat_queue_remove">移除队列消息</string>
|
||||
</resources>
|
||||
|
||||
@@ -136,6 +136,7 @@
|
||||
<string name="chat_retry">Erneut versuchen</string>
|
||||
<string name="chat_dismiss">Schließen</string>
|
||||
<string name="chat_failure_title">Hermes konnte diese Antwort nicht abschließen</string>
|
||||
<string name="chat_failure_inference_unavailable">Inferenz nicht verfügbar</string>
|
||||
<string name="chat_failure_details">Details</string>
|
||||
<string name="chat_failure_details_title">Antwortfehler</string>
|
||||
<string name="chat_failure_details_guidance">Hermes hat diesen Fehler gemeldet. Die App wechselt Routen oder Modelle nicht automatisch.</string>
|
||||
@@ -4577,4 +4578,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">Sprachfehler</string>
|
||||
<string name="chat_correct_now">Jetzt korrigieren</string>
|
||||
<string name="chat_queue_next">Danach senden</string>
|
||||
<string name="chat_busy_default_title">Während der Antwort</string>
|
||||
<string name="chat_busy_default_description">Wähle, was Senden während der Arbeit ausführt. Dieser geräteweite Standard gilt auch im Eingabefeld. Anhänge und nicht verfügbare Korrekturen werden eingereiht.</string>
|
||||
<string name="chat_queue_paused">Warteschlange pausiert</string>
|
||||
<string name="chat_queue_resume">Fortsetzen</string>
|
||||
<string name="chat_queue_remove">Nachricht aus Warteschlange entfernen</string>
|
||||
</resources>
|
||||
|
||||
@@ -113,6 +113,7 @@
|
||||
<string name="chat_retry">Reintentar</string>
|
||||
<string name="chat_dismiss">Descartar</string>
|
||||
<string name="chat_failure_title">Hermes no pudo completar esta respuesta</string>
|
||||
<string name="chat_failure_inference_unavailable">Inferencia no disponible</string>
|
||||
<string name="chat_failure_details">Detalles</string>
|
||||
<string name="chat_failure_details_title">Error de respuesta</string>
|
||||
<string name="chat_failure_details_guidance">Hermes informó de este error. La aplicación no cambiará automáticamente de ruta ni de modelo.</string>
|
||||
@@ -4268,4 +4269,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">Error de voz</string>
|
||||
<string name="chat_correct_now">Corregir ahora</string>
|
||||
<string name="chat_queue_next">Enviar después</string>
|
||||
<string name="chat_busy_default_title">Durante la respuesta</string>
|
||||
<string name="chat_busy_default_description">Elige qué hace Enviar mientras Hermes trabaja. Este ajuste del dispositivo también se usa en el cuadro de mensaje. Los adjuntos y las correcciones no disponibles se ponen en cola.</string>
|
||||
<string name="chat_queue_paused">Cola pausada</string>
|
||||
<string name="chat_queue_resume">Reanudar</string>
|
||||
<string name="chat_queue_remove">Quitar mensaje de la cola</string>
|
||||
</resources>
|
||||
|
||||
@@ -136,6 +136,7 @@
|
||||
<string name="chat_retry">リトライ</string>
|
||||
<string name="chat_dismiss">却下する</string>
|
||||
<string name="chat_failure_title">Hermes はこの応答を完了できませんでした</string>
|
||||
<string name="chat_failure_inference_unavailable">推論を利用できません</string>
|
||||
<string name="chat_failure_details">詳細</string>
|
||||
<string name="chat_failure_details_title">応答エラー</string>
|
||||
<string name="chat_failure_details_guidance">Hermes からこのエラーが報告されました。アプリがルートやモデルを自動的に切り替えることはありません。</string>
|
||||
@@ -4572,4 +4573,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">音声エラー</string>
|
||||
<string name="chat_correct_now">今すぐ修正</string>
|
||||
<string name="chat_queue_next">次に送信</string>
|
||||
<string name="chat_busy_default_title">応答中の動作</string>
|
||||
<string name="chat_busy_default_description">Hermesの作業中に送信する際の動作を選択します。この端末の設定は入力欄と共通です。添付ファイルや修正できない場合はキューに追加します。</string>
|
||||
<string name="chat_queue_paused">キューを一時停止中</string>
|
||||
<string name="chat_queue_resume">再開</string>
|
||||
<string name="chat_queue_remove">キューからメッセージを削除</string>
|
||||
</resources>
|
||||
|
||||
@@ -130,6 +130,7 @@
|
||||
<string name="chat_retry">Повторить</string>
|
||||
<string name="chat_dismiss">Отменить</string>
|
||||
<string name="chat_failure_title">Hermes не смог завершить ответ</string>
|
||||
<string name="chat_failure_inference_unavailable">Генерация ответа недоступна</string>
|
||||
<string name="chat_failure_details">Подробности</string>
|
||||
<string name="chat_failure_details_title">Ошибка ответа</string>
|
||||
<string name="chat_failure_details_guidance">Hermes сообщил об этой ошибке. Приложение не будет автоматически менять маршрут или модель.</string>
|
||||
@@ -4316,4 +4317,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">Ошибка голосового режима</string>
|
||||
<string name="chat_correct_now">Исправить сейчас</string>
|
||||
<string name="chat_queue_next">Отправить позже</string>
|
||||
<string name="chat_busy_default_title">Во время ответа</string>
|
||||
<string name="chat_busy_default_description">Выберите действие отправки, пока Hermes работает. Настройка общая для устройства и поля ввода. Вложения и недоступные исправления добавляются в очередь.</string>
|
||||
<string name="chat_queue_paused">Очередь приостановлена</string>
|
||||
<string name="chat_queue_resume">Продолжить</string>
|
||||
<string name="chat_queue_remove">Удалить сообщение из очереди</string>
|
||||
</resources>
|
||||
|
||||
@@ -140,6 +140,7 @@
|
||||
<string name="chat_retry">Retry</string>
|
||||
<string name="chat_dismiss">Dismiss</string>
|
||||
<string name="chat_failure_title">Hermes couldn’t complete this response</string>
|
||||
<string name="chat_failure_inference_unavailable">Inference unavailable</string>
|
||||
<string name="chat_failure_details">Details</string>
|
||||
<string name="chat_failure_details_title">Response failure</string>
|
||||
<string name="chat_failure_details_guidance">Hermes reported this error. The app won’t switch routes or models automatically.</string>
|
||||
@@ -4593,4 +4594,12 @@
|
||||
<string name="settings_git_workspace">Git workspace</string>
|
||||
<string name="settings_git_workspace_desc">Current-session Git first, with optional host discovery</string>
|
||||
<string name="settings_git_workspace_off_desc">Session repository only · Host discovery is opt-in</string>
|
||||
<string name="voice_overlay_error_title">Voice error</string>
|
||||
<string name="chat_correct_now">Correct now</string>
|
||||
<string name="chat_queue_next">Queue next</string>
|
||||
<string name="chat_busy_default_title">While responding</string>
|
||||
<string name="chat_busy_default_description">Choose what Send does while Hermes is working. This device-wide default is shared with the composer. Attachments and unavailable corrections queue instead.</string>
|
||||
<string name="chat_queue_paused">Queue paused</string>
|
||||
<string name="chat_queue_resume">Resume</string>
|
||||
<string name="chat_queue_remove">Remove queued message</string>
|
||||
</resources>
|
||||
|
||||
@@ -15,6 +15,26 @@ import org.junit.Test
|
||||
|
||||
class ChatInputPreferencesTest {
|
||||
|
||||
@Test
|
||||
fun `busy action defaults to correction and is shared after repository recreation`() = runTest {
|
||||
val store = InMemoryChatInputDataStore()
|
||||
val repository = ChatInputPreferencesRepository(store)
|
||||
assertEquals(BusyMessageAction.CorrectNow, repository.busyMessageAction.first())
|
||||
repository.setBusyMessageAction(BusyMessageAction.QueueNext)
|
||||
assertEquals(BusyMessageAction.QueueNext, ChatInputPreferencesRepository(store).busyMessageAction.first())
|
||||
assertEquals(BusyMessageAction.CorrectNow, BusyMessageAction.fromStoredValue("unknown"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `correction availability rejects attachments blocked input compaction and slash commands`() {
|
||||
assertEquals(true, canCorrectBusyMessage(true, false, false, null, "Correct this"))
|
||||
assertEquals(false, canCorrectBusyMessage(false, false, false, null, "Correct this"))
|
||||
assertEquals(false, canCorrectBusyMessage(true, true, false, null, "Correct this"))
|
||||
assertEquals(false, canCorrectBusyMessage(true, false, true, null, "Correct this"))
|
||||
assertEquals(false, canCorrectBusyMessage(true, false, false, "Compacting context", "Correct this"))
|
||||
assertEquals(false, canCorrectBusyMessage(true, false, false, null, "/model next"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `large paste conversion defaults on and round trips`() = runTest {
|
||||
val store = InMemoryChatInputDataStore()
|
||||
|
||||
+25
-2
@@ -13,6 +13,8 @@ import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okhttp3.mockwebserver.SocketPolicy
|
||||
@@ -31,6 +33,23 @@ import java.util.concurrent.TimeUnit
|
||||
|
||||
class DashboardApiClientTest {
|
||||
|
||||
@Test
|
||||
fun boundedJsonReaderRejectsDeclaredAndObservedOverflow() {
|
||||
val declared = "{}".toResponseBody("application/json".toMediaType())
|
||||
assertThrows(IOException::class.java) {
|
||||
declared.readUtf8Bounded(1)
|
||||
}
|
||||
|
||||
val chunked = object : okhttp3.ResponseBody() {
|
||||
override fun contentType() = "application/json".toMediaType()
|
||||
override fun contentLength() = -1L
|
||||
override fun source() = Buffer().writeUtf8("{\"value\":123}")
|
||||
}
|
||||
assertThrows(IOException::class.java) {
|
||||
chunked.readUtf8Bounded(8)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `multiplex API routing uses served profiles instead of installed inventory`() {
|
||||
val status = DashboardStatus(
|
||||
@@ -1466,7 +1485,7 @@ class DashboardApiClientTest {
|
||||
assertEquals("mizu", url.queryParameter("profile"))
|
||||
assertEquals("500", url.queryParameter("limit"))
|
||||
assertEquals("0", url.queryParameter("offset"))
|
||||
assertEquals("oldest", url.queryParameter("order"))
|
||||
assertEquals("latest", url.queryParameter("order"))
|
||||
assertEquals(2, messages.size)
|
||||
assertEquals("user", messages[0].role)
|
||||
assertEquals("assistant", messages[1].role)
|
||||
@@ -1478,7 +1497,11 @@ class DashboardApiClientTest {
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 500, count = 1, returned = 1))
|
||||
|
||||
val messages = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.getSessionMessages("sess-a", profile = "mizu")
|
||||
.getSessionMessages(
|
||||
"sess-a",
|
||||
profile = "mizu",
|
||||
mode = SessionMessageLoadMode.COMPLETE,
|
||||
)
|
||||
.getOrThrow()
|
||||
|
||||
val first = server.takeRequest().requestUrl!!
|
||||
|
||||
+39
-1
@@ -2697,13 +2697,28 @@ class GatewayChatClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session create rejects older gateway without profile ownership metadata`() {
|
||||
fun `profile scoped socket accepts older session result without duplicate ownership metadata`() {
|
||||
val r = Recorder()
|
||||
client.sessionProfileProvider = { "mizu" }
|
||||
harness.omitSessionProfileMetadata = true
|
||||
|
||||
client.sendTurn(null, "hi", null, r.callbacks) { r.preflightFailures += it }
|
||||
harness.awaitServerSocket()
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
assertTrue(r.preflightFailures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unscoped socket still rejects missing named profile ownership metadata`() {
|
||||
val r = Recorder()
|
||||
harness.omitSessionProfileMetadata = true
|
||||
client.observe()
|
||||
harness.awaitServerSocket()
|
||||
awaitCondition { client.connectionState.value == GatewayConnectionState.Ready }
|
||||
client.sessionProfileProvider = { "mizu" }
|
||||
|
||||
client.sendTurn(null, "hi", null, r.callbacks) { r.preflightFailures += it }
|
||||
awaitCondition { r.preflightFailures.isNotEmpty() }
|
||||
|
||||
assertTrue(r.preflightFailures.single().contains("did not confirm profile ownership"))
|
||||
@@ -3990,6 +4005,29 @@ class GatewayChatClientTest {
|
||||
assertEquals(0, harness.rpcLog.count { it.first == "prompt.submit" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lazy session initialization error fails before prompt submit`() {
|
||||
harness.createdSessionLazy = true
|
||||
val r = Recorder()
|
||||
|
||||
client.sendTurn(null, "hello", null, r.callbacks) { r.preflightFailures += it }
|
||||
harness.awaitRpc("session.create")
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
serverWs.send(
|
||||
harness.eventFrame(
|
||||
"error",
|
||||
buildJsonObject {
|
||||
put("message", "agent init failed: No Codex credentials stored")
|
||||
},
|
||||
"live-1",
|
||||
),
|
||||
)
|
||||
|
||||
waitUntil { r.preflightFailures.isNotEmpty() }
|
||||
assertTrue(r.preflightFailures.single().contains("No Codex credentials stored"))
|
||||
assertEquals(0, harness.rpcLog.count { it.first == "prompt.submit" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `authoritative prompt rejections surface server message without preflight fallback`() {
|
||||
val cases = listOf(
|
||||
|
||||
+18
@@ -570,6 +570,24 @@ class GatewayEventMapperTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wrapped image generation start exposes the effective tool identity`() {
|
||||
val recorder = Recorder()
|
||||
val mapper = mapperWith(recorder)
|
||||
mapper.onEvent(
|
||||
"tool.start",
|
||||
obj(
|
||||
"""{"tool_id":"img-1","name":"tool_call","args":{"name":"image_generate","arguments":{"prompt":"test","aspect_ratio":"landscape"}}}""",
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(listOf("img-1" to "image_generate"), recorder.toolStarts)
|
||||
assertEquals(
|
||||
listOf("img-1" to "{\"prompt\":\"test\",\"aspect_ratio\":\"landscape\"}"),
|
||||
recorder.toolStartArgs,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tool complete with error routes to failed`() {
|
||||
val r = Recorder()
|
||||
|
||||
@@ -30,7 +30,7 @@ class HermesApiClientTest {
|
||||
server.enqueue(apiMessagePageResponse(start = 500, count = 1, returned = 1))
|
||||
|
||||
val messages = HermesApiClient(server.url("/").toString(), "test-key")
|
||||
.getMessages("sess-a")
|
||||
.getMessages("sess-a", SessionMessageLoadMode.COMPLETE)
|
||||
|
||||
val first = server.takeRequest().requestUrl!!
|
||||
val second = server.takeRequest().requestUrl!!
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsFocused
|
||||
import androidx.compose.ui.test.hasSetTextAction
|
||||
import androidx.compose.ui.test.isDialog
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.assertIsSelected
|
||||
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.onNodeWithTag
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
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)
|
||||
@Config(qualifiers = "w400dp-h800dp-xhdpi")
|
||||
class ChatBusyControlsTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test fun selectorChangesIntentWithoutSendingAndKeepsStopSeparate() {
|
||||
var selected by mutableStateOf(BusyMessageAction.CorrectNow)
|
||||
var stopped = 0
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
ChatBusyActionSelector(selected, { selected = it }, onStop = { stopped++ })
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Queue next").assertDoesNotExist()
|
||||
compose.onNodeWithTag("chatBusyActionTrigger").performClick()
|
||||
compose.onNodeWithTag("chatBusyAction-queue_next").performClick()
|
||||
compose.waitForIdle()
|
||||
compose.onNodeWithTag("chatBusyActionDrawer").assertDoesNotExist()
|
||||
compose.onNodeWithText("Queue next").assertIsDisplayed()
|
||||
assertEquals(BusyMessageAction.QueueNext, selected)
|
||||
assertEquals(0, stopped)
|
||||
compose.onNodeWithContentDescription("Stop streaming").performClick()
|
||||
assertEquals(1, stopped)
|
||||
}
|
||||
|
||||
@Test fun unavailableCorrectionKeepsQueueSelectable() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme {
|
||||
ChatBusyActionSelector(BusyMessageAction.QueueNext, {}, correctionAvailable = false)
|
||||
}
|
||||
}
|
||||
compose.onNodeWithTag("chatBusyActionTrigger").performClick()
|
||||
compose.onNodeWithTag("chatBusyAction-correct_now").assertIsNotEnabled()
|
||||
compose.onNodeWithTag("chatBusyAction-queue_next").assertIsSelected()
|
||||
compose.onNodeWithTag("chatBusyActionDrawer")
|
||||
.captureRoboImage("build/ui-evidence/chat-busy-drawer.png")
|
||||
}
|
||||
|
||||
@Test fun pausedQueueActionsAndComposerRenderTogether() {
|
||||
var resumed = 0
|
||||
var cleared = 0
|
||||
var draft by mutableStateOf("A correction")
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(verticalArrangement = Arrangement.Bottom) {
|
||||
ChatMessageQueue(listOf("A saved follow-up", "Another follow-up"), true,
|
||||
{ resumed++ }, { cleared++ }, {}, {}, canEdit = true)
|
||||
ChatInputBar(
|
||||
value = draft, onValueChange = { draft = it }, placeholder = "Message",
|
||||
trailing = ChatInputTrailing.STEER, onSend = {}, onVoice = {}, onStop = {},
|
||||
onAttachPhotos = {}, onAttachFiles = {}, onAttachCamera = {}, onPasteImage = {},
|
||||
onLongPressAttach = {}, charLimit = 20_000, caption = "Changes the current response",
|
||||
voiceReady = false, showVoiceHint = false, onVoiceHintShown = {}, isDarkTheme = true,
|
||||
busyAction = BusyMessageAction.CorrectNow,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Resume").assertIsDisplayed().performClick()
|
||||
compose.onNodeWithText("Clear").performClick()
|
||||
assertEquals(1, resumed)
|
||||
assertEquals(1, cleared)
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/chat-busy-controls-dark.png")
|
||||
|
||||
val input = compose.onNode(hasSetTextAction())
|
||||
input.performClick()
|
||||
val inputBottom = input.fetchSemanticsNode().boundsInRoot.bottom
|
||||
val composerHeight = compose.onNodeWithTag("chatComposerForeground").fetchSemanticsNode().boundsInRoot.height
|
||||
compose.onNodeWithTag("chatBusyActionTrigger").performClick()
|
||||
compose.onNodeWithTag("chatBusyActionDrawer").assertIsDisplayed()
|
||||
compose.onNode(isDialog()).assertDoesNotExist()
|
||||
input.assertIsDisplayed().assertIsFocused()
|
||||
assertEquals(inputBottom, input.fetchSemanticsNode().boundsInRoot.bottom, 1f)
|
||||
val foreground = compose.onNodeWithTag("chatComposerForeground").fetchSemanticsNode().boundsInRoot
|
||||
val rearTray = compose.onNodeWithTag("chatBusyActionTray").fetchSemanticsNode().boundsInRoot
|
||||
assertEquals(composerHeight, foreground.height, 1f)
|
||||
assertTrue("Rear tray must tuck behind the foreground composer", rearTray.bottom > foreground.top)
|
||||
assertTrue(compose.onNodeWithTag("chatBusyActionDrawer").fetchSemanticsNode().boundsInRoot.bottom <= foreground.top)
|
||||
input.performTextInput(" updated")
|
||||
assertTrue(draft.contains("updated"))
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/chat-busy-composer-expanded.png")
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,16 @@ class ChatFailurePanelTest {
|
||||
assertEquals("Gateway", failureIdentity("Gateway", null, null))
|
||||
assertEquals("", failureIdentity("", null, null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `inference initialization errors get a specific presentation`() {
|
||||
assertEquals(
|
||||
true,
|
||||
isInferenceUnavailableFailure(
|
||||
"agent init failed: No Codex credentials stored. " +
|
||||
"setup.status reports configured credentials, but runtime resolution still failed.",
|
||||
),
|
||||
)
|
||||
assertEquals(false, isInferenceUnavailableFailure("gateway connect cooling down"))
|
||||
}
|
||||
}
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.semantics.SemanticsActions
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
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.text.TextLayoutResult
|
||||
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.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w400dp-h800dp-xhdpi")
|
||||
class MessageDeliveryContrastTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test fun darkUserBubblesUseContrastingDeliveryText() = verifyDeliveryColors("dark")
|
||||
@Test fun lightUserBubblesUseContrastingDeliveryText() = verifyDeliveryColors("light")
|
||||
|
||||
private fun verifyDeliveryColors(theme: String) {
|
||||
var foreground = Color.Unspecified
|
||||
var background = Color.Unspecified
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = theme) {
|
||||
foreground = MaterialTheme.colorScheme.onPrimary
|
||||
background = MaterialTheme.colorScheme.primary
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
MessageDeliveryStatus.entries.forEach { status ->
|
||||
MessageBubble(
|
||||
message = ChatMessage(
|
||||
id = status.name,
|
||||
role = MessageRole.USER,
|
||||
content = "Test",
|
||||
timestamp = 1_700_000_000_000L,
|
||||
deliveryStatus = status,
|
||||
),
|
||||
animationEnabled = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertNotEquals(background, foreground)
|
||||
listOf("Sending…", "Queued", "Correction sent", "Delivered", "Not sent").forEach { label ->
|
||||
val layouts = mutableListOf<TextLayoutResult>()
|
||||
compose.onNodeWithText(label, useUnmergedTree = true)
|
||||
.assertIsDisplayed()
|
||||
.performSemanticsAction(SemanticsActions.GetTextLayoutResult) { it(layouts) }
|
||||
assertEquals("Delivery label must use the user bubble foreground: $label", foreground, layouts.single().layoutInput.style.color)
|
||||
}
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/message-delivery-$theme.png")
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,14 @@ class OrientedBitmapDecoderTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cached raster orientation matches viewer mime policy`() {
|
||||
assertEquals(false, shouldApplyExifOrientation("image/png"))
|
||||
assertEquals(false, shouldApplyExifOrientation("image/gif"))
|
||||
assertEquals(true, shouldApplyExifOrientation("image/jpeg"))
|
||||
assertEquals(true, shouldApplyExifOrientation("image/heif"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `content uri decoder reads encoded image without byte array handoff`() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
|
||||
+11
@@ -65,4 +65,15 @@ class StreamingMarkdownContentTest {
|
||||
planStreamingMarkdownAppend("", "authoritative final response"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oversizedMarkdownKeepsDataOutsideTheBoundedRenderWindow() {
|
||||
val source = "x".repeat(MAX_RENDERED_MARKDOWN_CHARS + 1)
|
||||
|
||||
val rendered = markdownRenderWindow(source)
|
||||
|
||||
assertEquals(MAX_RENDERED_MARKDOWN_CHARS, rendered.takeWhile { it == 'x' }.length)
|
||||
assertFalse(rendered.startsWith(source))
|
||||
assertTrue(rendered.contains("shortened for Android memory safety"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.isDialog
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.test.swipeUp
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.VoicePresentationMode
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.InteractionMode
|
||||
import com.hermesandroid.relay.viewmodel.VoiceState
|
||||
import com.hermesandroid.relay.viewmodel.VoiceUiState
|
||||
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)
|
||||
@Config(qualifiers = "w360dp-h780dp-xhdpi")
|
||||
class VoiceErrorDialogTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun conversationError_isModalAndDismissesWithoutStartingMicrophone() {
|
||||
val actions = mutableListOf<String>()
|
||||
renderError(onClear = { actions += "clear" }, onMicTap = { actions += "mic" })
|
||||
|
||||
compose.onNode(isDialog()).assertExists()
|
||||
compose.onNodeWithText("Voice error").assertIsDisplayed()
|
||||
compose.onNodeWithText("Dismiss").assertIsDisplayed()
|
||||
compose.onNodeWithText("Retry").assertIsDisplayed()
|
||||
compose.onNode(isDialog()).captureRoboImage("build/ui-evidence/voice-error-conversation-dark.png")
|
||||
compose.onNodeWithText("Dismiss").performClick()
|
||||
compose.mainClock.advanceTimeByFrame()
|
||||
|
||||
compose.onNode(isDialog()).assertDoesNotExist()
|
||||
compose.runOnIdle { assertEquals(listOf("clear"), actions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun focusError_retryClearsErrorBeforeStartingMicrophone() {
|
||||
val actions = mutableListOf<String>()
|
||||
renderError(
|
||||
mode = VoicePresentationMode.Focus,
|
||||
onClear = { actions += "clear" },
|
||||
onMicTap = { actions += "mic" },
|
||||
)
|
||||
|
||||
compose.onNode(isDialog()).assertExists()
|
||||
compose.onNodeWithText("Retry").performClick()
|
||||
compose.mainClock.advanceTimeByFrame()
|
||||
|
||||
compose.onNode(isDialog()).assertDoesNotExist()
|
||||
compose.runOnIdle { assertEquals(listOf("clear", "mic"), actions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w780dp-h360dp-xhdpi")
|
||||
fun landscapeLargeText_longErrorScrollsWithoutHidingActions() {
|
||||
val longError = List(8) { PROVIDER_ERROR }.joinToString("\n\n")
|
||||
renderError(error = longError, theme = "light", fontScale = 1.5f)
|
||||
|
||||
compose.onNodeWithText("Dismiss").assertIsDisplayed()
|
||||
compose.onNodeWithText("Retry").assertIsDisplayed()
|
||||
val detail = compose.onNodeWithText(longError)
|
||||
val scrollRange = detail.fetchSemanticsNode().config[SemanticsProperties.VerticalScrollAxisRange]
|
||||
assertTrue(scrollRange.maxValue() > 0f)
|
||||
detail.performTouchInput { swipeUp() }
|
||||
compose.runOnIdle { assertTrue(scrollRange.value() > 0f) }
|
||||
compose.onNodeWithText("Dismiss").assertIsDisplayed()
|
||||
compose.onNodeWithText("Retry").assertIsDisplayed()
|
||||
compose.onNode(isDialog()).captureRoboImage("build/ui-evidence/voice-error-landscape-light-large-text.png")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noError_doesNotShowDialog() {
|
||||
renderError(error = null)
|
||||
compose.onNode(isDialog()).assertDoesNotExist()
|
||||
}
|
||||
|
||||
private fun renderError(
|
||||
error: String? = PROVIDER_ERROR,
|
||||
mode: VoicePresentationMode = VoicePresentationMode.Conversation,
|
||||
theme: String = "dark",
|
||||
fontScale: Float = 1f,
|
||||
onClear: () -> Unit = {},
|
||||
onMicTap: () -> Unit = {},
|
||||
) {
|
||||
var state by mutableStateOf(
|
||||
VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = if (error == null) VoiceState.Idle else VoiceState.Error,
|
||||
interactionMode = InteractionMode.TapToTalk,
|
||||
error = error,
|
||||
),
|
||||
)
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent {
|
||||
HermesRelayTheme(themePreference = theme, fontScale = fontScale) {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Box {
|
||||
Text("Chat remains behind the modal")
|
||||
VoiceModeOverlay(
|
||||
uiState = state,
|
||||
presentationMode = mode,
|
||||
onMicTap = onMicTap,
|
||||
onMicRelease = {},
|
||||
onInterrupt = {},
|
||||
onDismiss = {},
|
||||
onModeChange = {},
|
||||
onClearError = {
|
||||
onClear()
|
||||
state = state.copy(error = null, state = VoiceState.Idle)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(500)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PROVIDER_ERROR = "Hermes audio transcribe rejected that input - " +
|
||||
"{\"detail\":\"No STT provider available. Install faster-whisper for free local " +
|
||||
"transcription, configure HERMES_LOCAL_STT_COMMAND or install a local whisper CLI, " +
|
||||
"set GROQ_API_KEY for free Groq Whisper, set MISTRAL_API_KEY for Mistral Voxtral " +
|
||||
"Transcribe, configure xAI OAuth or set XAI_API_KEY for xAI Grok STT, set " +
|
||||
"ELEVENLABS_API_KEY for ElevenLabs Scribe, or set VOICE_TOOLS_OPENAI_KEY or " +
|
||||
"OPENAI_API_KEY for the OpenAI Whisper API.\"}"
|
||||
}
|
||||
}
|
||||
+165
-2
@@ -913,6 +913,28 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertEquals(2, calls.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reentrantSessionPublicationCannotKeepTheRefreshBatchAlive() {
|
||||
val calls = AtomicInteger(0)
|
||||
viewModel.setProfileSessionLister {
|
||||
calls.incrementAndGet()
|
||||
// Reproduce a downstream publication observer requesting another
|
||||
// refresh while every successful directory read is still active.
|
||||
viewModel.refreshSessions()
|
||||
Result.success(listOf(SessionItem(id = "stable", title = "Stable session")))
|
||||
}
|
||||
|
||||
viewModel.refreshSessions()
|
||||
|
||||
awaitCondition { calls.get() >= 2 }
|
||||
Thread.sleep(150)
|
||||
val settledCalls = calls.get()
|
||||
Thread.sleep(150)
|
||||
assertEquals(settledCalls, calls.get())
|
||||
assertTrue(settledCalls <= 3)
|
||||
assertEquals("stable", handler.sessions.value.singleOrNull()?.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coalescedTrailingSuccessClearsTheInitialFailure() {
|
||||
val calls = AtomicInteger(0)
|
||||
@@ -1961,6 +1983,33 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertFalse(gatewayHarness.rpcLog.any { it.first == "prompt.submit" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayInterimImmediatelyLeavesAStreamingConversationOwner() {
|
||||
viewModel.sendMessage("Generate an image")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.interim",
|
||||
buildJsonObject {
|
||||
put("text", "Generating it now.")
|
||||
put("already_streamed", false)
|
||||
},
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
|
||||
awaitCondition {
|
||||
handler.messages.value.any { it.content == "Generating it now." }
|
||||
}
|
||||
assertTrue(handler.isStreaming.value)
|
||||
val activeOwner = handler.messages.value.last()
|
||||
assertTrue(activeOwner.isStreaming)
|
||||
assertEquals(MessageRole.ASSISTANT, activeOwner.role)
|
||||
assertTrue(activeOwner.content.isBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedMainDispatchAdmitsBackgroundStartAfterLocalCompletion() {
|
||||
viewModel.sendMessage("Local gateway turn")
|
||||
@@ -3138,6 +3187,87 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(viewModel.queuedMessages.value.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitQueueChoiceDoesNotAttemptRedirect() {
|
||||
startTurnForQueueTest()
|
||||
viewModel.sendMessage("Run next", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
assertEquals(listOf("Run next"), viewModel.queuedMessages.value)
|
||||
assertFalse(gatewayHarness.rpcLog.any { it.first == "session.redirect" || it.first == "session.steer" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deletingQueuedHeadReconnectsSuccessorToActiveTurn() {
|
||||
startTurnForQueueTest()
|
||||
viewModel.sendMessage("Remove me", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
viewModel.sendMessage("Keep me", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
viewModel.removeQueuedAt(0)
|
||||
completeQueueTestTurn()
|
||||
awaitCondition { gatewayHarness.rpcLog.any { it.first == "prompt.submit" && it.second["text"] == JsonPrimitive("Keep me") } }
|
||||
assertFalse(gatewayHarness.rpcLog.any { it.first == "prompt.submit" && it.second["text"] == JsonPrimitive("Remove me") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun editingQueuedHeadDoesNotStrandSuccessor() {
|
||||
startTurnForQueueTest()
|
||||
viewModel.sendMessage("Edit me", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
viewModel.sendMessage("Keep me", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
assertEquals("Edit me", viewModel.takeQueuedForEdit(0))
|
||||
completeQueueTestTurn()
|
||||
awaitCondition { gatewayHarness.rpcLog.any { it.first == "prompt.submit" && it.second["text"] == JsonPrimitive("Keep me") } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stopPausesQueueUntilExplicitResumeAndPersistsWholeChain() {
|
||||
val store = MemoryCheckpointStore()
|
||||
viewModel.setChatTurnCheckpointStore(store)
|
||||
startTurnForQueueTest()
|
||||
viewModel.sendMessage("First pending", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
viewModel.sendMessage("Second pending", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
viewModel.cancelStream()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
assertEquals(listOf("First pending", "Second pending"), viewModel.queuedMessages.value)
|
||||
assertTrue(viewModel.queuePaused.value)
|
||||
assertFalse(gatewayHarness.rpcLog.any { it.first == "prompt.submit" })
|
||||
awaitCondition { store.checkpoint?.queueOnly == true }
|
||||
assertEquals(true, store.checkpoint?.queuePaused)
|
||||
assertEquals(2, store.checkpoint?.queuedMessages?.size)
|
||||
|
||||
viewModel.resumeQueue()
|
||||
awaitCondition { gatewayHarness.rpcLog.any { it.first == "prompt.submit" && it.second["text"] == JsonPrimitive("First pending") } }
|
||||
assertFalse(viewModel.queuePaused.value)
|
||||
assertEquals(listOf("Second pending"), viewModel.queuedMessages.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pausedQueueCheckpointRestoresWithoutRecoveringStoppedTurn() {
|
||||
val store = MemoryCheckpointStore()
|
||||
viewModel.setChatTurnCheckpointStore(store)
|
||||
startTurnForQueueTest()
|
||||
viewModel.sendMessage("Keep paused", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
viewModel.cancelStream()
|
||||
awaitCondition { store.checkpoint?.queueOnly == true }
|
||||
val saved = requireNotNull(store.checkpoint)
|
||||
viewModel.clearQueue()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
store.checkpoint = saved
|
||||
val activationsBefore = gatewayHarness.rpcLog.count { it.first == "session.activate" }
|
||||
viewModel.prewarmGateway()
|
||||
awaitCondition { viewModel.queuedMessages.value == listOf("Keep paused") }
|
||||
assertTrue(viewModel.queuePaused.value)
|
||||
assertFalse(handler.isStreaming.value)
|
||||
assertEquals(activationsBefore, gatewayHarness.rpcLog.count { it.first == "session.activate" })
|
||||
}
|
||||
|
||||
private fun startTurnForQueueTest() {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
awaitCondition { handler.isStreaming.value }
|
||||
}
|
||||
|
||||
private fun completeQueueTestTurn() {
|
||||
serverWs.send(gatewayHarness.eventFrame("message.complete", buildJsonObject { put("text", "Original complete") }, "live-resumed"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedMessageStaysWithOriginWhileAnotherRunningSessionCompletes() {
|
||||
val secondSession = "stored-session-b"
|
||||
@@ -3283,6 +3413,29 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectionSwitchKeepsRunningCheckpointWhenQueueExists() {
|
||||
val store = MemoryCheckpointStore()
|
||||
val switches = MutableSharedFlow<String>(extraBufferCapacity = 1)
|
||||
viewModel.setChatTurnCheckpointStore(store)
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
viewModel.observeConnectionSwitches(switches)
|
||||
viewModel.sendMessage("Keep the running turn recoverable")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
viewModel.sendMessage("Follow up on this connection", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
awaitCondition { viewModel.queuedMessages.value.size == 1 }
|
||||
|
||||
switches.tryEmit("connection-b")
|
||||
awaitCondition { viewModel.queuedMessages.value.isEmpty() }
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
val checkpoint = requireNotNull(store.checkpoint)
|
||||
assertFalse("A detached running turn must not become queue-only", checkpoint.queueOnly)
|
||||
assertEquals("Keep the running turn recoverable", checkpoint.user.content)
|
||||
assertEquals(listOf("Follow up on this connection"), checkpoint.queuedMessages.map { it.text })
|
||||
assertFalse(gatewayHarness.rpcLog.any { it.first == "session.interrupt" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deletingDestinationCancelsItsQueueAndEditRestoresOnlyThatItem() {
|
||||
gatewayHarness.redirectStatus = "rejected"
|
||||
@@ -3330,7 +3483,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun retryQueuedForActiveRunIsCancelledWithThatRun() {
|
||||
fun retryQueuedForActiveRunIsPausedWhenThatRunStops() {
|
||||
gatewayHarness.redirectStatus = "rejected"
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("connection-a", null),
|
||||
@@ -3345,7 +3498,8 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
|
||||
viewModel.cancelStream()
|
||||
gatewayHarness.awaitRpc("session.interrupt")
|
||||
assertTrue(viewModel.queuedMessages.value.isEmpty())
|
||||
assertEquals(listOf("Retry this turn"), viewModel.queuedMessages.value)
|
||||
assertTrue(viewModel.queuePaused.value)
|
||||
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
@@ -3788,6 +3942,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
|
||||
@Test
|
||||
fun passiveForegroundObservationNeverClaimsOrInterruptsDesktopTurn() {
|
||||
val directoryReads = AtomicInteger(0)
|
||||
val observerProfile = Profile(
|
||||
name = "observer",
|
||||
model = "model-a",
|
||||
@@ -3855,7 +4010,12 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.Working
|
||||
}
|
||||
viewModel.setProfileSessionLister {
|
||||
directoryReads.incrementAndGet()
|
||||
Result.success(emptyList())
|
||||
}
|
||||
gatewayHarness.activeSessionListPayload = activeSessionPayload("waiting")
|
||||
val directoryReadsBeforeHistoryPublication = directoryReads.get()
|
||||
viewModel.requestSessionActivityRefresh()
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["observer:$STORED_SESSION_ID"] ==
|
||||
@@ -3873,6 +4033,9 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
handler.messages.value.singleOrNull()?.content ==
|
||||
"Desktop completed without Android attachment."
|
||||
}
|
||||
shadowOf(Looper.getMainLooper()).idleFor(4, TimeUnit.SECONDS)
|
||||
Thread.sleep(100)
|
||||
assertEquals(directoryReadsBeforeHistoryPublication, directoryReads.get())
|
||||
ownershipMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"passive foreground sent $method",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@hermes-relay/cli",
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@hermes-relay/cli",
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"hermes-relay": "bin/hermes-relay.js"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hermes-relay/cli",
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"description": "Thin-client CLI for Hermes-Relay — talk to a remote Hermes agent over WSS with pairing auth, stream-renders tool calls and responses to plain stdout.",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
// Regenerated from package.json by gen:version script. Do not edit by hand.
|
||||
export const VERSION = "0.4.0-beta.6" as const
|
||||
export const VERSION = "0.4.0-beta.7" as const
|
||||
|
||||
Generated
+1
-1
@@ -1232,7 +1232,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hermes-relay-tray"
|
||||
version = "0.4.0-beta.6"
|
||||
version = "0.4.0-beta.7"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"serde",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "hermes-relay-tray"
|
||||
version = "0.4.0-beta.6"
|
||||
version = "0.4.0-beta.7"
|
||||
description = "Compact Windows management UI for Hermes-Relay CLI"
|
||||
authors = ["Axiom Labs"]
|
||||
edition = "2021"
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@hermes-relay/tray-ui",
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@hermes-relay/tray-ui",
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.8.0",
|
||||
"lucide-react": "^0.468.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@hermes-relay/tray-ui",
|
||||
"private": true,
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Hermes-Relay CLI UI",
|
||||
"version": "0.4.0-beta.6",
|
||||
"version": "0.4.0-beta.7",
|
||||
"identifier": "com.axiomlabs.hermes-relay-tray",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
@@ -4226,6 +4226,12 @@ longer current.
|
||||
hidden-source exclusions server-side. Near-end scrolling appends subsequent
|
||||
50-row `offset` pages under the same owner/generation; older rows never block
|
||||
the first-open critical path.
|
||||
- Routine transcript open, restore, and post-turn reconciliation request one
|
||||
latest 500-row page, matching the rows Android can retain. Complete
|
||||
oldest-first pagination is reserved for positional recovery that proves it
|
||||
needs older anchors. Each Dashboard JSON response is rejected above the
|
||||
Android byte limit before parsing, and aggregate complete reads retain their
|
||||
independent row/payload ceilings.
|
||||
- A refresh over existing rows is quiet. The exact connection/profile cache
|
||||
remains visible until authoritative replacement rows arrive. An uncached
|
||||
profile may show loading, but a failed read never means "no sessions."
|
||||
|
||||
@@ -72,6 +72,7 @@ the upstream contract identifiers it depends on.
|
||||
| `compaction_status` | Compaction status is client-visible before terminal completion and may repeat as a heartbeat |
|
||||
| `rapid_tools_interims` | Rapid chunks, reasoning, tool activity, and interim assistant boundaries |
|
||||
| `queued_follow_up` | Two explicitly owned turns and ordered queue drainage |
|
||||
| `queued_stop_resume` | Explicit queue choice, removal of a predecessor, Stop/pause, lifecycle return, and explicit Resume through production Android controls |
|
||||
| `scope_rejection_inputs` | Exact, foreign, and unscoped event inputs |
|
||||
| `terminal_gap_activate` | Socket closes after live output; replacement `session.activate` reports `running=false`; history is authoritative |
|
||||
| `terminal_gap_active_list` | An exact Android-owned turn receives deltas but no terminal; `session.active_list` reports the same live/durable owner idle; history is authoritative |
|
||||
@@ -124,6 +125,16 @@ unreviewed endpoint.
|
||||
|
||||
## Physical-device certification
|
||||
|
||||
The queue-control instrumentation uses the `queued_stop_resume` fixture on
|
||||
loopback with an explicit ADB reverse. Run only
|
||||
`GatewayExternalFixtureInstrumentedTest#queuedStopResume_preservesWorkAcrossLifecycleAndUsesExplicitResume`
|
||||
with `gatewayFixtureBaseUrl` set to that fixture. It verifies two submits, one
|
||||
interrupt, no redirect, and a single completed resumed reply. This is a separate
|
||||
scenario from the terminal-gap certification runner below, whose evidence
|
||||
contract requires socket loss and activation. The fixture emits the upstream
|
||||
interrupted terminal before the next turn; omitting it would exercise a broken
|
||||
server contract rather than the queue controls.
|
||||
|
||||
Inspect the exact plan first. The runner requires an explicit serial or
|
||||
transport ID, targets only `com.axiomlabs.hermesrelay.sideload`, and performs no
|
||||
installation unless its corresponding install flag is supplied.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "227a53fc7a1fd3cf113b56b507c7d65372769db179f4772be892138ff0ac8060",
|
||||
"main": "1efc1c169120e525ddd1484f9ac33c15d27f558d74b766e7c04f42abd8169255",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -48,7 +48,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "227a53fc7a1fd3cf113b56b507c7d65372769db179f4772be892138ff0ac8060",
|
||||
"main": "1efc1c169120e525ddd1484f9ac33c15d27f558d74b766e7c04f42abd8169255",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -72,7 +72,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "227a53fc7a1fd3cf113b56b507c7d65372769db179f4772be892138ff0ac8060",
|
||||
"main": "1efc1c169120e525ddd1484f9ac33c15d27f558d74b766e7c04f42abd8169255",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -96,7 +96,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "227a53fc7a1fd3cf113b56b507c7d65372769db179f4772be892138ff0ac8060",
|
||||
"main": "1efc1c169120e525ddd1484f9ac33c15d27f558d74b766e7c04f42abd8169255",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -120,7 +120,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "227a53fc7a1fd3cf113b56b507c7d65372769db179f4772be892138ff0ac8060",
|
||||
"main": "1efc1c169120e525ddd1484f9ac33c15d27f558d74b766e7c04f42abd8169255",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -135,7 +135,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "227a53fc7a1fd3cf113b56b507c7d65372769db179f4772be892138ff0ac8060",
|
||||
"main": "1efc1c169120e525ddd1484f9ac33c15d27f558d74b766e7c04f42abd8169255",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
|
||||
@@ -91,9 +91,9 @@ This app is a community project and is not affiliated with or endorsed by NousRe
|
||||
Paste into Play Console → **What's new** (≤500 characters):
|
||||
|
||||
```
|
||||
v1.15.0 - Standard Hermes first, with clearer Relay boundaries
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
|
||||
Standard Chat, Voice, attachments, returned files, current-session Git, usage, and Hermes notices now prefer upstream Dashboard and Gateway support without requiring Relay. Returned media stays loaded, voice survives Relay removal, and Settings clearly separates standard Hermes from Relay tools. Supervised Mode also gains app-specific parent access and recovery.
|
||||
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.
|
||||
```
|
||||
## Category
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-09-02 — Android 1.15.1 and CLI+UI beta.7 release preparation
|
||||
|
||||
Prepared Android 1.15.1 (versionCode 54) and CLI+UI 0.4.0-beta.7 from the integrated release tree. Android notes cover chat memory bounds, media previews, Gateway readiness, follow-up controls, and voice recovery. CLI+UI notes cover the Windows unified updater. Plugin metadata remains at 1.11.1; its only unreleased change is a documentation-comment path.
|
||||
|
||||
The Android release uses the immutable signed Play preflight artifact for public publication. CLI+UI remains a prerelease and is approved from the exact prepared dev commit.
|
||||
|
||||
## 2026-09-01 — Exact-tree release artifact promotion
|
||||
|
||||
Android Play preflight now packages the signed sideload APK, Play AAB, R8
|
||||
|
||||
+2
-1
@@ -615,7 +615,8 @@ Bottom navigation bar with 4 tabs:
|
||||
- **Cold profile hydration** — a persisted named profile scopes its Dashboard session directory and last-session restore immediately, before `/api/profiles` metadata is available. Server-default selection waits for the lightweight active-profile scope. Roster, avatars, pets, skills, and model metadata never precede the first directory result. The startup sphere releases after route selection; Chat keeps identity and cached rows mounted while its existing animated status surfaces show Gateway wake, session restore, and directory loading.
|
||||
- **Authoritative session activity** — one composite registry keyed by connection, normalized profile, and durable session id drives the drawer, filters, grouping, animation, accessibility, and the visible composer. Exact pending approval/clarify/sudo/secret/MCP requests produce **Needs input**; the Gateway's process-wide `session.active_list` supplies **Starting**, **Working**, and **Idle**; an exact terminal, `session.info {running:false}`, or an exact live/durable active-list row reporting Idle can settle only the matching Android-owned turn and progress generation. Because active-list rows normally have no profile metadata, Android assigns a row through exact foreground/detached ownership already held by that client, explicit profile metadata if a future upstream sends it, or the currently selected passive session when its durable id has exactly one owner in the current connection directory. Duplicate same-id owners across profiles remain unresolved and create no status. Resolved rows from a partial snapshot may update their exact owners, but disappearance settles a scope only when the successful process-wide snapshot was completely and unambiguously resolved for it. Restart/checkpoint recovery is **Checking**; a failed or unsupported live refresh is **Unavailable**, never inferred Idle. REST `is_active` remains recency metadata only. `process.list` may add a separate **Background work** indicator and never keeps the parent conversation Working. Old socket generations, ambiguous bare session ids, delayed snapshots, and snapshots crossed by newer turn events cannot settle or revive a newer generation.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible Android-owned turn without sending `session.interrupt`; each Android-owned running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Opening, foregrounding, or selecting a saved session without that exact checkpoint is read-only observation: Android warms only the socket, reads profile-scoped history, and polls `session.active_list` without `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`. A Desktop/TUI-owned turn therefore remains owned by its producing client; Android refreshes persisted progress and performs one final history read when the runtime settles. Explicit send/config actions may resume the destination session, explicit Stop still interrupts, and Direct API compatibility chat stays single-stream and cancels on navigation.
|
||||
- **Queued Gateway follow-ups** — every local queued item is immutably scoped to its originating connection, profile, stored session, transport, and run generation; only that run's completion can make it eligible, and switching sessions shows only that session's queue. Restored text queues retain the same scope, while unavailable/deleted destinations and non-restorable attachment queues fail visibly instead of following the current composer. Drained messages add `queued: true` to `prompt.submit`; ordinary sends omit the field. Authoritative submit rejections (`4004`, `4018`, `4028`, `4029`, `4030`, `4090`, `5008`, `5070`, and `5071`) preserve the server message and never fall through to API-server SSE.
|
||||
- **Queued Gateway follow-ups** — every local queued item is scoped to its originating connection, profile, stored session, transport, and predecessor run; only that predecessor's completion can make it eligible, and switching sessions shows only that session's queue. Removing or pulling a queued item into an empty composer reconnects its successor to the removed item's predecessor. Restored text queues retain the complete chain; unavailable/deleted destinations and non-restorable attachment queues fail visibly instead of following the current composer. Stop pauses pending work; Resume explicitly continues the exact destination, and Clear is the separate discard action. Queue-only checkpoints restore paused messages without reattaching the stopped turn. Drained messages add `queued: true` to `prompt.submit`; ordinary sends omit the field. Authoritative submit rejections (`4004`, `4018`, `4028`, `4029`, `4030`, `4090`, `5008`, `5070`, and `5071`) preserve the server message and never fall through to API-server SSE.
|
||||
- **Busy Chat input** — Chat settings owns the device-local Correct now / Queue next default, initially correction. Chat and Bot Chat show the effective action in a slim translucent rear tray whose lower edge sits beneath the foreground composer. Plain-text choices slide upward without covering the input; selecting one overrides the current message and returns to the saved default after send. Attachments, pending input, context compaction, slash commands, and unavailable or policy-disabled correction use the queue without replacing the saved preference. Stop remains separate from sending typed text. Pulling a queued message out for editing keeps that send queued unless the user explicitly selects correction.
|
||||
- **Durable composer drafts** — each connection/profile/session owns one app-private draft containing text, quote/edit context, and pending attachment bytes. Metadata and content-addressed blobs live under Android's no-backup directory, are capped at 64 drafts and 128 MB of retained blobs outside the active draft, flush when Chat backgrounds, and are removed after a successful send. Session/profile/connection navigation saves the previous owner before restoring the destination; an opened cross-profile session uses its actual owning profile rather than the global picker.
|
||||
- **Large paste review** — a default-on Chat setting converts any single insertion of at least 5,000 characters into a visible `pasted-text.txt` attachment before the normal message-length limit rejects it. Gateway uses upstream `file.attach`; API-server SSE and proactive Thread paths materialize the same UTF-8 text into the outgoing prompt and remove only the synthetic attachment from that transport, so the behavior never requires Relay or silently drops content.
|
||||
- **Complete transcript reads** — Android requests the API-server and profile-scoped Dashboard message routes with an explicit 500-row contract. User-visible history pages oldest-first until complete, preserves legacy unpaginated envelopes, and stops with a clear 50,000-message/32 MB client safety bound. Short dropped-stream recovery polls one explicit latest page while the known transcript fits that window; longer histories retain complete paging so positional edit/recovery anchors cannot shift. Edit-and-regenerate submits always send `confirm_truncate`; ordinal zero alone also sends `confirm_empty_truncate`. Gateway history `row_id` values are retained as durable rewind targets (never UI keys), sent alongside the visible-user ordinal, and rebound from `survivor_user_row_ids` after each truncating rewrite. Histories with no row IDs remain ordinal-compatible with older Hermes; a mixed history fails closed when the selected row lacks its durable ID instead of guessing by position.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[versions]
|
||||
appVersionName = "1.15.0"
|
||||
appVersionCode = "53"
|
||||
appVersionName = "1.15.1"
|
||||
appVersionCode = "54"
|
||||
agp = "9.3.2"
|
||||
kotlin = "2.4.10"
|
||||
compose-bom = "2026.08.00"
|
||||
|
||||
@@ -316,6 +316,21 @@ class FixtureTestCase(unittest.IsolatedAsyncioTestCase):
|
||||
]
|
||||
self.assertEqual(2, len(completes))
|
||||
|
||||
async def test_interrupt_stops_old_turn_before_explicit_queue_resume(self) -> None:
|
||||
fixture, base_url = await self.start("queued_stop_resume")
|
||||
ws, _ = await self.connect(base_url)
|
||||
await self.rpc(ws, 1, "prompt.submit", {"text": "original"})
|
||||
await self.frames_until(ws, lambda f: f.get("params", {}).get("type") == "message.delta")
|
||||
await self.rpc(ws, 2, "session.interrupt")
|
||||
frames = await self.frames_until(ws, lambda f: f.get("id") == 2)
|
||||
self.assertFalse(fixture._running)
|
||||
self.assertFalse(fixture._turn_active)
|
||||
await self.rpc(ws, 3, "prompt.submit", {"text": "resumed", "queued": True})
|
||||
frames += await self.frames_until(ws, lambda f: f.get("params", {}).get("type") == "message.complete")
|
||||
completes = [f["params"]["payload"]["text"] for f in frames if f.get("params", {}).get("type") == "message.complete"]
|
||||
self.assertEqual(["", "Resumed follow-up."], completes)
|
||||
self.assertEqual(1, sum(f.get("params", {}).get("payload", {}).get("status") == "interrupted" for f in frames))
|
||||
|
||||
async def test_scope_scenario_exposes_rejection_inputs_and_exact_terminal(self) -> None:
|
||||
fixture, base_url = await self.start("scope_rejection_inputs")
|
||||
ws, _ = await self.connect(base_url)
|
||||
@@ -407,6 +422,7 @@ class ScenarioTestCase(unittest.TestCase):
|
||||
"terminal_gap_active_list",
|
||||
"terminal_gap_session_info",
|
||||
"queued_follow_up",
|
||||
"queued_stop_resume",
|
||||
"scope_rejection_inputs",
|
||||
):
|
||||
scenario = load_scenario(name)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "queued_stop_resume",
|
||||
"live_session_id": "fixture-live-1",
|
||||
"stored_session_id": "20260821_120000_fixture",
|
||||
"profile": "default",
|
||||
"contract_requirements": ["gateway.message_complete"],
|
||||
"turns": [
|
||||
{"steps": [
|
||||
{"op": "event", "type": "message.start"},
|
||||
{"op": "event", "type": "message.delta", "payload": {"text": "Original work."}},
|
||||
{"op": "sleep", "milliseconds": 5000},
|
||||
{"op": "sleep", "milliseconds": 5000},
|
||||
{"op": "sleep", "milliseconds": 5000},
|
||||
{"op": "set_running", "value": false},
|
||||
{"op": "event", "type": "message.complete", "payload": {"text": "Original work."}}
|
||||
]},
|
||||
{"steps": [
|
||||
{"op": "event", "type": "message.start"},
|
||||
{"op": "event", "type": "message.delta", "payload": {"text": "Resumed follow-up."}},
|
||||
{"op": "persist", "messages": [{"id": 2, "role": "assistant", "content": "Resumed follow-up.", "timestamp": 2.0}]},
|
||||
{"op": "set_running", "value": false},
|
||||
{"op": "event", "type": "message.complete", "payload": {"text": "Resumed follow-up."}}
|
||||
]}
|
||||
]
|
||||
}
|
||||
@@ -140,7 +140,18 @@ class GatewayFixture:
|
||||
await self._submit(socket, connection)
|
||||
return
|
||||
elif method == "session.interrupt":
|
||||
was_active = self._turn_active
|
||||
tasks = tuple(self._tasks)
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
if tasks:
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
self._running = False
|
||||
if was_active:
|
||||
await self._send_event(
|
||||
socket, connection, "message.complete",
|
||||
{"text": "", "status": "interrupted"}, self.scenario.live_session_id,
|
||||
)
|
||||
result = {"ok": True}
|
||||
elif method == "session.active_list" and self.scenario.active_list_supported:
|
||||
if self._active_list_snapshots:
|
||||
|
||||
Reference in New Issue
Block a user