Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d80b3db329 |
+1
-1
@@ -17,7 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android Clarify cards make custom answers explicit and keyboard-friendly.** Choice prompts label their Other answer field, submit trimmed text from the keyboard, and do not restore an authoritatively expired prompt after session navigation.
|
||||
- **Opening Android no longer claims or interrupts a turn already running in Hermes Desktop/TUI.** Passive foreground and session browsing now use read-only Gateway status plus profile-scoped history; live-session resume remains reserved for explicit Android actions and exact Android-owned recovery.
|
||||
- **The visible Android Sphere keeps its smooth procedural motion across startup and chat.** Backgrounded and motion-disabled surfaces remain still without reducing foreground animation to a stepped ambient pulse.
|
||||
|
||||
### Removed
|
||||
|
||||
@@ -26,6 +26,9 @@ model device-certified:
|
||||
renders as Working.
|
||||
- Run a background process that outlives its parent turn and verify Background
|
||||
work remains separate from the conversation's Idle state.
|
||||
- On a physical phone, open and repeatedly foreground Android while the same
|
||||
session is working in official Desktop/TUI; verify Android sends no live
|
||||
attach/interrupt RPC, the producer completes, and final history appears.
|
||||
- Pursue an upstream `session.active_list` profile field/filter or an aggregate
|
||||
activity route with explicit profile ownership so multi-profile clients do
|
||||
not need to resolve process-wide rows from durable keys.
|
||||
|
||||
+83
@@ -239,6 +239,60 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
val baseline = controlMethods.associateWith(fixture::rpcCount)
|
||||
val baselineActiveList = fixture.rpcCount("session.active_list")
|
||||
fixture.activeSessionStatus = "working"
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val okHttp = OkHttpClient()
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = fixture.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = okHttp,
|
||||
),
|
||||
okHttpClient = okHttp,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(null)
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.setChatVisible(true)
|
||||
fixture.awaitRpcCount("session.active_list", baselineActiveList + 1)
|
||||
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"passive lifecycle sent $method",
|
||||
baseline.getValue(method),
|
||||
fixture.rpcCount(method),
|
||||
)
|
||||
}
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
assertEquals(
|
||||
"observer teardown interrupted the Desktop turn",
|
||||
baseline.getValue("session.interrupt"),
|
||||
fixture.rpcCount("session.interrupt"),
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
@@ -263,6 +317,9 @@ internal class AndroidGatewayContractFixture {
|
||||
@Volatile
|
||||
var recoveryRunning = false
|
||||
|
||||
@Volatile
|
||||
var activeSessionStatus: String? = null
|
||||
|
||||
private val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
sockets.add(webSocket)
|
||||
@@ -282,6 +339,18 @@ internal class AndroidGatewayContractFixture {
|
||||
"session.activate" -> sessionSnapshot(
|
||||
(params["session_id"] as? JsonPrimitive)?.contentOrNull ?: "fixture-live-1",
|
||||
)
|
||||
"session.active_list" -> buildJsonObject {
|
||||
put("sessions", kotlinx.serialization.json.buildJsonArray {
|
||||
activeSessionStatus?.let { status ->
|
||||
add(buildJsonObject {
|
||||
put("id", LIVE_SESSION_ID)
|
||||
put("session_key", STORED_SESSION_ID)
|
||||
put("status", status)
|
||||
put("last_active", 1.0)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
"prompt.submit", "session.interrupt" -> buildJsonObject { put("ok", true) }
|
||||
else -> JsonObject(emptyMap())
|
||||
}
|
||||
@@ -345,6 +414,15 @@ internal class AndroidGatewayContractFixture {
|
||||
error("Gateway RPC $method not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun awaitRpcCount(method: String, count: Int) {
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (rpcCount(method) >= count) return
|
||||
Thread.sleep(20)
|
||||
}
|
||||
error("Gateway RPC $method count $count not observed; saw ${rpcLog.map { it.first }}")
|
||||
}
|
||||
|
||||
fun requestsTo(path: String): Int = requestPaths.count { it.startsWith(path) }
|
||||
|
||||
fun rpcCount(method: String): Int = rpcLog.count { it.first == method }
|
||||
@@ -353,4 +431,9 @@ internal class AndroidGatewayContractFixture {
|
||||
allSockets.forEach { socket -> runCatching { socket.close(1001, "teardown") } }
|
||||
runCatching { server.shutdown() }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -906,6 +906,30 @@ class GatewayChatClient(
|
||||
scope.launch { prewarmAwait(storedSessionId) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish only the shared Gateway socket for read-only observation.
|
||||
*
|
||||
* `session.resume` and `session.activate` attach a live runtime to this
|
||||
* transport. Opening Chat, foreground restoration, and selecting a saved
|
||||
* transcript must not claim a turn that another Desktop/TUI client owns,
|
||||
* so those paths use this socket-only warmup and observe through REST
|
||||
* history plus `session.active_list` instead.
|
||||
*/
|
||||
fun observe(onReady: (() -> Unit)? = null) {
|
||||
scope.launch {
|
||||
if (observeAwait() && onReady != null) callbackDispatcher(onReady)
|
||||
}
|
||||
}
|
||||
|
||||
/** Suspending [observe]; returns true once the read-only socket is ready. */
|
||||
suspend fun observeAwait(): Boolean = try {
|
||||
connectMutex.withLock { ensureConnected() }
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Gateway observation warmup skipped: ${e.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* Suspending [prewarm]: establishes the socket and (when [storedSessionId]
|
||||
* is non-null) resumes the existing session, returning only once that work
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
@@ -24,7 +25,6 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
@@ -71,7 +71,6 @@ import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
@@ -173,26 +172,26 @@ fun HermesCardBubble(
|
||||
),
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(IntrinsicSize.Min),
|
||||
) {
|
||||
// Accent stripe — runs full card height so tall cards keep the
|
||||
// color tie. Using the SAME tertiary accent strategy as the
|
||||
// voice/phone-action bubble marker in MessageBubble.kt so the
|
||||
// visual language stays consistent.
|
||||
Box(
|
||||
modifier = Modifier.matchParentSize(),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(3.dp)
|
||||
.fillMaxHeight()
|
||||
.background(accentColor),
|
||||
)
|
||||
}
|
||||
modifier = Modifier
|
||||
.width(3.dp)
|
||||
.fillMaxHeight()
|
||||
.background(accentColor),
|
||||
)
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 15.dp, top = 12.dp, end = 12.dp, bottom = 12.dp),
|
||||
.padding(12.dp),
|
||||
) {
|
||||
// Header
|
||||
Row(
|
||||
@@ -427,19 +426,6 @@ private fun CardInputSlot(
|
||||
input.kind != HermesCardInput.Kinds.CONFIRM)
|
||||
)
|
||||
|
||||
val submitFreeText = {
|
||||
val customAnswer = answerText.trim()
|
||||
if (customAnswer.isNotEmpty()) {
|
||||
onSubmit(
|
||||
if (isMultiSelect) {
|
||||
encodeClarifyMultiSelectAnswer(selectedChoices + customAnswer)
|
||||
} else {
|
||||
customAnswer
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
// Choice chips
|
||||
if (input.choices.isNotEmpty()) {
|
||||
@@ -529,16 +515,11 @@ private fun CardInputSlot(
|
||||
InlineAnswerField(
|
||||
value = answerText,
|
||||
onValueChange = { answerText = it },
|
||||
placeholder = stringResource(
|
||||
if (input.choices.isNotEmpty()) R.string.card_other_answer_placeholder
|
||||
else R.string.card_answer_placeholder,
|
||||
),
|
||||
onSubmit = submitFreeText,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!isMultiSelect) {
|
||||
IconButton(
|
||||
onClick = submitFreeText,
|
||||
onClick = { onSubmit(answerText.trim()) },
|
||||
enabled = answerText.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
@@ -612,8 +593,6 @@ private fun CardInputSlot(
|
||||
private fun InlineAnswerField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
placeholder: String,
|
||||
onSubmit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val shape = appearanceRoundedCornerShape(16.dp)
|
||||
@@ -626,7 +605,7 @@ private fun InlineAnswerField(
|
||||
) {
|
||||
if (value.isEmpty()) {
|
||||
Text(
|
||||
text = placeholder,
|
||||
text = stringResource(R.string.card_answer_placeholder),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
|
||||
)
|
||||
@@ -638,12 +617,8 @@ private fun InlineAnswerField(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||
keyboardActions = KeyboardActions(onSend = { onSubmit() }),
|
||||
maxLines = 3,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.semantics { contentDescription = placeholder },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1119,12 +1119,16 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
// Recover any durable in-flight chat checkpoint whenever Chat returns to
|
||||
// the foreground. On Gateway this also pre-warms/re-attaches the socket;
|
||||
// sessions-SSE falls back to bounded persisted-history reconciliation.
|
||||
// the foreground. setChatVisible owns that edge; an ordinary Gateway open
|
||||
// warms only the observation socket and never attaches a saved session.
|
||||
val appForeground by com.hermesandroid.relay.util.AppForegroundTracker.isForeground.collectAsState()
|
||||
LaunchedEffect(isGatewayTransport, appForeground, chatReady) {
|
||||
chatViewModel.setChatVisible(appForeground && chatReady)
|
||||
if (appForeground && chatReady) {
|
||||
val chatVisible = appForeground && chatReady
|
||||
val visibilityChanged = chatViewModel.setChatVisible(chatVisible)
|
||||
if (isGatewayTransport && chatVisible && !visibilityChanged) {
|
||||
// Gateway availability can settle after Chat was already visible.
|
||||
// Repeat the socket-only warmup for that edge; ordinary observation
|
||||
// still cannot resume or activate a session.
|
||||
chatViewModel.prewarmGateway()
|
||||
}
|
||||
if (isGatewayTransport && appForeground && chatReady) {
|
||||
|
||||
@@ -408,6 +408,9 @@ class ChatViewModel : ViewModel() {
|
||||
private val sessionActivityGeneration = AtomicLong(0L)
|
||||
private val sessionActivityPollMutex = Mutex()
|
||||
private var sessionActivityPollJob: Job? = null
|
||||
private var passiveGatewayHistoryRefreshJob: Job? = null
|
||||
private var passivelyObservedGatewaySessionId: String? = null
|
||||
private var passiveObservationCatchupPendingSessionId: String? = null
|
||||
private var sessionActivityDirectory: Set<SessionActivityOwner> = emptySet()
|
||||
private var lastProjectedProcessIds: Set<String> = emptySet()
|
||||
private var lastProjectedProcessOwner: SessionActivityOwner? = null
|
||||
@@ -2252,6 +2255,8 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
private suspend fun pollSessionActivity(client: GatewayChatClient) {
|
||||
var hasPassiveCurrentLiveWork = false
|
||||
var hasPassiveCatchupPending = false
|
||||
sessionActivityPollMutex.withLock {
|
||||
if (gatewayClient !== client || !chatVisible || streamingEndpoint != "gateway") return
|
||||
val generation = sessionActivityGeneration.get()
|
||||
@@ -2272,6 +2277,43 @@ class ChatViewModel : ViewModel() {
|
||||
when (val result = client.listActiveSessions()) {
|
||||
is GatewayActiveSessionsResult.Success -> {
|
||||
if (gatewayClient !== client || generation != sessionActivityGeneration.get()) return
|
||||
val currentStoredId = currentOwner?.storedSessionId
|
||||
val passiveCurrentRows = if (currentStoredId == null) {
|
||||
emptyList()
|
||||
} else {
|
||||
result.sessions.filter { row ->
|
||||
row.storedSessionId == currentStoredId &&
|
||||
client.knownSessionOwner(row.runtimeSessionId) == null
|
||||
}
|
||||
}
|
||||
hasPassiveCurrentLiveWork = passiveCurrentRows.any { row ->
|
||||
row.status != GatewayActiveSessionStatus.Idle
|
||||
}
|
||||
val initialCatchupPending =
|
||||
passiveObservationCatchupPendingSessionId == currentStoredId
|
||||
val needsFinalPassiveRefresh =
|
||||
passivelyObservedGatewaySessionId == currentStoredId &&
|
||||
!hasPassiveCurrentLiveWork
|
||||
if (hasPassiveCurrentLiveWork) {
|
||||
currentStoredId?.let(::refreshPassivelyObservedGatewayHistory)
|
||||
if (initialCatchupPending) {
|
||||
passiveObservationCatchupPendingSessionId = null
|
||||
}
|
||||
} else if (needsFinalPassiveRefresh || initialCatchupPending) {
|
||||
val scheduled = currentStoredId?.let { storedId ->
|
||||
refreshPassivelyObservedGatewayHistory(
|
||||
storedSessionId = storedId,
|
||||
retryUntilChanged = true,
|
||||
)
|
||||
} == true
|
||||
if (scheduled && initialCatchupPending) {
|
||||
passiveObservationCatchupPendingSessionId = null
|
||||
}
|
||||
}
|
||||
passivelyObservedGatewaySessionId =
|
||||
currentStoredId?.takeIf { hasPassiveCurrentLiveWork }
|
||||
hasPassiveCatchupPending =
|
||||
passiveObservationCatchupPendingSessionId == currentStoredId
|
||||
val resolved = resolveGatewayActiveSessions(
|
||||
sessions = result.sessions,
|
||||
directory = directory,
|
||||
@@ -2333,6 +2375,18 @@ class ChatViewModel : ViewModel() {
|
||||
GatewayActiveSessionsResult.Unsupported,
|
||||
is GatewayActiveSessionsResult.TransientFailure -> {
|
||||
if (gatewayClient !== client || generation != sessionActivityGeneration.get()) return
|
||||
val currentStoredId = currentOwner?.storedSessionId
|
||||
if (passiveObservationCatchupPendingSessionId == currentStoredId) {
|
||||
val scheduled = currentStoredId?.let { storedId ->
|
||||
refreshPassivelyObservedGatewayHistory(
|
||||
storedSessionId = storedId,
|
||||
retryUntilChanged = true,
|
||||
)
|
||||
} == true
|
||||
if (scheduled) passiveObservationCatchupPendingSessionId = null
|
||||
}
|
||||
hasPassiveCatchupPending =
|
||||
passiveObservationCatchupPendingSessionId == currentStoredId
|
||||
val scopes = directory.mapTo(mutableSetOf()) {
|
||||
SessionActivityScope.of(it.connectionId, it.profile)
|
||||
}.apply { add(currentScope) }
|
||||
@@ -2351,7 +2405,9 @@ class ChatViewModel : ViewModel() {
|
||||
record.freshness == SessionActivityFreshness.Confirmed &&
|
||||
record.phase(System.currentTimeMillis()) != SessionActivityPhase.Idle
|
||||
}
|
||||
val delayMs = if (hasConfirmedLiveWork) 1_500L else 30_000L
|
||||
val delayMs = if (
|
||||
hasConfirmedLiveWork || hasPassiveCurrentLiveWork || hasPassiveCatchupPending
|
||||
) 1_500L else 30_000L
|
||||
sessionActivityPollJob = viewModelScope.launch {
|
||||
delay(delayMs)
|
||||
if (gatewayClient === client && chatVisible) pollSessionActivity(client)
|
||||
@@ -2424,6 +2480,10 @@ class ChatViewModel : ViewModel() {
|
||||
clearProjectedBackgroundProcesses()
|
||||
sessionActivityPollJob?.cancel()
|
||||
sessionActivityPollJob = null
|
||||
passiveGatewayHistoryRefreshJob?.cancel()
|
||||
passiveGatewayHistoryRefreshJob = null
|
||||
passivelyObservedGatewaySessionId = null
|
||||
passiveObservationCatchupPendingSessionId = null
|
||||
sessionActivityGeneration.incrementAndGet()
|
||||
sessionActivityDirectory = emptySet()
|
||||
lastLocalActivityOwner = null
|
||||
@@ -2509,30 +2569,6 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
is GatewayBackgroundInteractionEvent.Expired -> {
|
||||
if (key != null) {
|
||||
val checkpoint = backgroundTurnCheckpoints[key]
|
||||
val checkpointAsk = checkpoint?.pendingAsk
|
||||
if (checkpoint != null && checkpointAsk != null &&
|
||||
checkpointAsk.kind == event.ask.kind.name &&
|
||||
(event.ask.kind == GatewayAsk.Kind.APPROVAL ||
|
||||
checkpointAsk.requestId == event.ask.requestId)
|
||||
) {
|
||||
val updated = checkpoint.copy(
|
||||
pendingAsk = null,
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
)
|
||||
// Recovery consults memory before disk, so retire the
|
||||
// stale card synchronously before a navigation can
|
||||
// reclaim this turn. Persist the same exact owner so
|
||||
// process restart cannot resurrect it either.
|
||||
backgroundTurnCheckpoints[key] = updated
|
||||
chatTurnCheckpointStore?.let { store ->
|
||||
viewModelScope.launch {
|
||||
checkpointMutex.withLock {
|
||||
runCatching { store.write(updated) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
backgroundNeedsInputKeys -= key
|
||||
backgroundPendingInteractions.computeIfPresent(key) { _, current ->
|
||||
if (current.ask.kind == event.ask.kind &&
|
||||
@@ -2567,8 +2603,9 @@ class ChatViewModel : ViewModel() {
|
||||
// Foreground can race OkHttp's delayed close callback:
|
||||
// the first prewarm sees the old socket as Ready, then
|
||||
// the callback moves it to Idle. Re-run from this exact
|
||||
// client transition so the visible durable session is
|
||||
// resumed and its authoritative history reconciled.
|
||||
// client transition so the observation socket is
|
||||
// restored; only an exact Android checkpoint may
|
||||
// resume/activate a live runtime.
|
||||
prewarmGateway()
|
||||
}
|
||||
}
|
||||
@@ -3023,6 +3060,103 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh a Desktop/TUI-owned turn through the profile-scoped history
|
||||
* surface without attaching its live runtime. `session.active_list` drives
|
||||
* the bounded cadence; one final read follows Working/Waiting -> Idle.
|
||||
*/
|
||||
private fun refreshPassivelyObservedGatewayHistory(
|
||||
storedSessionId: String,
|
||||
retryUntilChanged: Boolean = false,
|
||||
): Boolean {
|
||||
if (passiveGatewayHistoryRefreshJob?.isActive == true) return false
|
||||
if (_isLoadingHistory.value) return false
|
||||
val handler = chatHandler ?: return false
|
||||
val contextKey = activeProfileContextKey
|
||||
val profileName = currentSessionProfileName()
|
||||
val refreshJob = viewModelScope.launch(start = CoroutineStart.LAZY) {
|
||||
try {
|
||||
repeat(if (retryUntilChanged) 8 else 1) { attempt ->
|
||||
val serverMessages = runCatching {
|
||||
loadGatewaySessionHistory(
|
||||
sessionId = storedSessionId,
|
||||
requireProfileScope = true,
|
||||
profileName = profileName,
|
||||
)
|
||||
}.getOrNull() ?: return@launch
|
||||
if (
|
||||
chatHandler !== handler ||
|
||||
activeProfileContextKey != contextKey ||
|
||||
currentSessionProfileName() != profileName ||
|
||||
handler.currentSessionId.value != storedSessionId ||
|
||||
_isLoadingHistory.value ||
|
||||
activeStream != null ||
|
||||
handler.isStreaming.value
|
||||
) return@launch
|
||||
|
||||
val visibleSignature = handler.messages.value
|
||||
.filterNot { it.clientOnly }
|
||||
.map { message ->
|
||||
Triple(
|
||||
message.role.name.lowercase(),
|
||||
message.content,
|
||||
message.thinkingContent,
|
||||
)
|
||||
}
|
||||
val serverSignature = serverMessages.map { message ->
|
||||
Triple(
|
||||
message.role.lowercase(),
|
||||
message.contentText.orEmpty(),
|
||||
message.resolvedReasoning.orEmpty(),
|
||||
)
|
||||
}
|
||||
if (visibleSignature != serverSignature) {
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
refreshSessions()
|
||||
scheduleTitleReconcile(storedSessionId)
|
||||
return@launch
|
||||
}
|
||||
if (attempt < 7 && retryUntilChanged) delay(250L)
|
||||
}
|
||||
} finally {
|
||||
if (passiveGatewayHistoryRefreshJob === coroutineContext[Job]) {
|
||||
passiveGatewayHistoryRefreshJob = null
|
||||
}
|
||||
}
|
||||
}
|
||||
passiveGatewayHistoryRefreshJob = refreshJob
|
||||
refreshJob.start()
|
||||
return true
|
||||
}
|
||||
|
||||
/** Open the read-only socket off Main, then publish observation ownership on Main. */
|
||||
private fun observeGatewaySession(
|
||||
client: GatewayChatClient?,
|
||||
handler: ChatHandler,
|
||||
storedSessionId: String,
|
||||
) {
|
||||
val observer = client ?: return
|
||||
val contextKey = activeProfileContextKey
|
||||
val profileName = currentSessionProfileName()
|
||||
observer.observe {
|
||||
if (
|
||||
chatVisible &&
|
||||
gatewayClient === observer &&
|
||||
chatHandler === handler &&
|
||||
activeProfileContextKey == contextKey &&
|
||||
currentSessionProfileName() == profileName &&
|
||||
handler.currentSessionId.value == storedSessionId
|
||||
) {
|
||||
passiveObservationCatchupPendingSessionId = storedSessionId
|
||||
refreshPassivelyObservedGatewayHistory(
|
||||
storedSessionId = storedSessionId,
|
||||
retryUntilChanged = true,
|
||||
)
|
||||
requestSessionActivityRefresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot `config.get personality` over a ready socket → drives the collector. */
|
||||
private fun seedServerPersonality(client: GatewayChatClient) {
|
||||
viewModelScope.launch {
|
||||
@@ -3033,11 +3167,11 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm the gateway socket (and resume the current session) when the chat
|
||||
* surface is visible and the gateway is the resolved transport, so the
|
||||
* first send is warm instead of paying the cold connect + `session.resume`
|
||||
* on the send path. No-op without a gateway client; idempotent when warm.
|
||||
* Driven by a foreground/visibility effect in ChatScreen.
|
||||
* Warm the Gateway socket when Chat is visible without claiming a runtime
|
||||
* that may belong to Desktop/TUI. Exact Android-owned checkpoints recover
|
||||
* through `session.activate`/`session.resume`; an ordinary open observes
|
||||
* through REST history and `session.active_list` until the user performs
|
||||
* an explicit action that needs session ownership.
|
||||
*/
|
||||
fun prewarmGateway() {
|
||||
val client = gatewayClient
|
||||
@@ -3045,17 +3179,16 @@ class ChatViewModel : ViewModel() {
|
||||
val sessionId = handler.currentSessionId.value
|
||||
selectBackgroundProcessSession(sessionId)
|
||||
if (sessionId == null) {
|
||||
client?.prewarm(null)
|
||||
client?.observe()
|
||||
} else {
|
||||
// Preserve the original warm-up path before persistence wiring is
|
||||
// available (early composition and JVM tests). Production installs
|
||||
// the store from initializeMedia before Chat becomes ready.
|
||||
if (chatTurnCheckpointStore == null) {
|
||||
val gateway = client ?: return
|
||||
// GatewayChatClient owns an IO scope, so this can progress even
|
||||
// while a paused/blocked UI dispatcher is being recreated.
|
||||
// Its cold-ready listener performs history/process refresh.
|
||||
gateway.prewarm(sessionId)
|
||||
// GatewayChatClient owns the socket IO scope, so the dial can
|
||||
// progress while a paused UI dispatcher is being recreated.
|
||||
observeGatewaySession(gateway, handler, sessionId)
|
||||
return
|
||||
}
|
||||
if (activeStream == null && (streamRecovery == null || client != null)) {
|
||||
@@ -3067,26 +3200,29 @@ class ChatViewModel : ViewModel() {
|
||||
chatHandler === handler &&
|
||||
handler.currentSessionId.value == sessionId
|
||||
) {
|
||||
if (client?.prewarmAwait(sessionId) == true) {
|
||||
gatewayProcessController.sessionReady(sessionId)
|
||||
}
|
||||
observeGatewaySession(client, handler, sessionId)
|
||||
}
|
||||
checkpointRecoveryJob = null
|
||||
}
|
||||
return
|
||||
}
|
||||
// prewarm() only emits the existing "cold ready" callback when it
|
||||
// had to resume. An already-live session still needs its initial
|
||||
// process snapshot when Chat opens, so confirm it explicitly.
|
||||
viewModelScope.launch {
|
||||
if (
|
||||
client?.prewarmAwait(sessionId) == true &&
|
||||
gatewayClient === client &&
|
||||
chatHandler === handler &&
|
||||
handler.currentSessionId.value == sessionId
|
||||
) {
|
||||
gatewayProcessController.sessionReady(sessionId)
|
||||
// A locally-owned live mapper may revalidate its existing binding.
|
||||
// A passive transcript must remain socket-only: resuming it here
|
||||
// can replace another client's transport and turn Android teardown
|
||||
// into a later session.interrupt.
|
||||
if (client?.hasActiveTurnForSession(sessionId) == true) {
|
||||
viewModelScope.launch {
|
||||
if (client.prewarmAwait(sessionId) &&
|
||||
gatewayClient === client &&
|
||||
chatHandler === handler &&
|
||||
handler.currentSessionId.value == sessionId
|
||||
) {
|
||||
gatewayProcessController.sessionReady(sessionId)
|
||||
requestSessionActivityRefresh()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
observeGatewaySession(client, handler, sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3096,7 +3232,7 @@ class ChatViewModel : ViewModel() {
|
||||
* Gateway chat owns automatic idle-socket reattachment; other tabs and a
|
||||
* backgrounded app retain the normal no-reconnect behavior.
|
||||
*/
|
||||
fun setChatVisible(visible: Boolean) {
|
||||
fun setChatVisible(visible: Boolean): Boolean {
|
||||
val changed = chatVisible != visible
|
||||
chatVisible = visible
|
||||
if (visible && changed) {
|
||||
@@ -3105,7 +3241,12 @@ class ChatViewModel : ViewModel() {
|
||||
} else if (!visible) {
|
||||
sessionActivityPollJob?.cancel()
|
||||
sessionActivityPollJob = null
|
||||
passiveGatewayHistoryRefreshJob?.cancel()
|
||||
passiveGatewayHistoryRefreshJob = null
|
||||
passivelyObservedGatewaySessionId = null
|
||||
passiveObservationCatchupPendingSessionId = null
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// === Gateway desktop-parity state ===
|
||||
@@ -4489,7 +4630,9 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
if (stillCurrent()) {
|
||||
handler.loadMessageHistory(messages)
|
||||
if (streamingEndpoint == "gateway") gatewayClient?.prewarm(sessionId)
|
||||
if (streamingEndpoint == "gateway") {
|
||||
observeGatewaySession(gatewayClient, handler, sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
@@ -5000,7 +5143,9 @@ class ChatViewModel : ViewModel() {
|
||||
handler.currentSessionId.value == sessionId
|
||||
) {
|
||||
handler.loadMessageHistory(messages)
|
||||
if (streamingEndpoint == "gateway") gatewayClient?.prewarm(sessionId)
|
||||
if (streamingEndpoint == "gateway") {
|
||||
observeGatewaySession(gatewayClient, handler, sessionId)
|
||||
}
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
@@ -6590,6 +6735,10 @@ class ChatViewModel : ViewModel() {
|
||||
* SSE cannot, so it retains the existing interrupt/cancel behavior.
|
||||
*/
|
||||
private fun releaseTurnForNavigation(handler: ChatHandler) {
|
||||
passiveGatewayHistoryRefreshJob?.cancel()
|
||||
passiveGatewayHistoryRefreshJob = null
|
||||
passivelyObservedGatewaySessionId = null
|
||||
passiveObservationCatchupPendingSessionId = null
|
||||
val gateway = gatewayClient
|
||||
val canBackground = streamingEndpoint == "gateway" &&
|
||||
activeStreamIsGateway && activeStream != null && gateway != null
|
||||
|
||||
@@ -3263,7 +3263,6 @@
|
||||
<string name="card_send_answer_a11y">Enviar resposta</string>
|
||||
<string name="card_submit">Enviar</string>
|
||||
<string name="card_answer_placeholder">Digite uma resposta…</string>
|
||||
<string name="card_other_answer_placeholder">Outra (digite sua resposta)…</string>
|
||||
<string name="session_ttl_title">Manter este pareamento por…</string>
|
||||
<string name="session_ttl_intro">Seu celular se reconectará automaticamente durante este período. Você pode revogar o pareamento a qualquer momento.</string>
|
||||
<string name="session_ttl_stays_paired">Este dispositivo permanecerá pareado até você revogá-lo.</string>
|
||||
|
||||
@@ -3363,7 +3363,6 @@
|
||||
<string name="card_send_answer_a11y">发送回答</string>
|
||||
<string name="card_submit">提交</string>
|
||||
<string name="card_answer_placeholder">输入回答…</string>
|
||||
<string name="card_other_answer_placeholder">其他(输入自定义回答)…</string>
|
||||
<string name="session_ttl_title">保持配对的时长…</string>
|
||||
<string name="session_ttl_intro">在此时间内,手机会自动重新连接。您可以随时撤销配对。</string>
|
||||
<string name="session_ttl_stays_paired">此设备会保持配对,直到您主动撤销。</string>
|
||||
|
||||
@@ -3431,7 +3431,6 @@
|
||||
<string name="card_send_answer_a11y">Antwort senden</string>
|
||||
<string name="card_submit">Absenden</string>
|
||||
<string name="card_answer_placeholder">Antwort eingeben…</string>
|
||||
<string name="card_other_answer_placeholder">Andere (eigene Antwort eingeben)…</string>
|
||||
<string name="session_ttl_title">Diese Kopplung behalten für…</string>
|
||||
<string name="session_ttl_intro">Dein Smartphone verbindet sich in diesem Zeitraum automatisch erneut. Du kannst die Kopplung jederzeit widerrufen.</string>
|
||||
<string name="session_ttl_stays_paired">Dieses Gerät bleibt gekoppelt, bis du es widerrufst.</string>
|
||||
|
||||
@@ -3094,7 +3094,6 @@
|
||||
<string name="card_send_answer_a11y">Enviar respuesta</string>
|
||||
<string name="card_submit">Entregar</string>
|
||||
<string name="card_answer_placeholder">Escribe una respuesta...</string>
|
||||
<string name="card_other_answer_placeholder">Otra (escribe tu respuesta)…</string>
|
||||
<string name="session_ttl_title">Mantenga este emparejamiento para...</string>
|
||||
<string name="session_ttl_intro">Su teléfono se volverá a conectar automáticamente durante esta ventana. Puedes revocar el emparejamiento en cualquier momento.</string>
|
||||
<string name="session_ttl_stays_paired">Este dispositivo permanecerá emparejado hasta que lo revoques.</string>
|
||||
|
||||
@@ -3439,7 +3439,6 @@
|
||||
<string name="card_send_answer_a11y">回答を送信する</string>
|
||||
<string name="card_submit">提出する</string>
|
||||
<string name="card_answer_placeholder">答えを入力してください…</string>
|
||||
<string name="card_other_answer_placeholder">その他(自由回答を入力)…</string>
|
||||
<string name="session_ttl_title">このペアリングをしばらく保持してください…</string>
|
||||
<string name="session_ttl_intro">この期間中に電話は自動的に再接続します。ペアリングはいつでも取り消すことができます。</string>
|
||||
<string name="session_ttl_stays_paired">このデバイスは、取り消すまでペアリングされたままになります。</string>
|
||||
|
||||
@@ -3298,7 +3298,6 @@
|
||||
<string name="card_send_answer_a11y">Отправить ответ</string>
|
||||
<string name="card_submit">Отправить</string>
|
||||
<string name="card_answer_placeholder">Введите ответ…</string>
|
||||
<string name="card_other_answer_placeholder">Другое (введите свой ответ)…</string>
|
||||
<string name="session_ttl_title">Сохранить это сопряжение на…</string>
|
||||
<string name="session_ttl_intro">Ваш телефон будет автоматически переподключаться в течение этого периода. Вы можете отозвать сопряжение в любой момент.</string>
|
||||
<string name="session_ttl_stays_paired">Это устройство останется сопряженным, пока вы не отзовёте его.</string>
|
||||
|
||||
@@ -3754,7 +3754,6 @@
|
||||
<string name="card_send_answer_a11y">Send answer</string>
|
||||
<string name="card_submit">Submit</string>
|
||||
<string name="card_answer_placeholder">Type an answer…</string>
|
||||
<string name="card_other_answer_placeholder">Other (type your answer)…</string>
|
||||
<string name="session_ttl_title">Keep this pairing for…</string>
|
||||
<string name="session_ttl_intro">Your phone will reconnect automatically during this window. You can revoke the pairing at any time.</string>
|
||||
<string name="session_ttl_stays_paired">This device will stay paired until you revoke it.</string>
|
||||
|
||||
+29
-1
@@ -231,11 +231,14 @@ class GatewayClientHarness(
|
||||
val suppressAckMethods: MutableSet<String> = ConcurrentHashMap.newKeySet()
|
||||
val pendingAcks = LinkedBlockingQueue<PendingAck>()
|
||||
|
||||
@Volatile
|
||||
var suppressGatewayReady: Boolean = false
|
||||
|
||||
private val wsListener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
|
||||
serverSockets.add(webSocket)
|
||||
allServerSockets.add(webSocket)
|
||||
webSocket.send(eventFrame("gateway.ready", null, null))
|
||||
if (!suppressGatewayReady) sendGatewayReady(webSocket)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
@@ -627,6 +630,10 @@ class GatewayClientHarness(
|
||||
fun awaitServerSocket(): WebSocket =
|
||||
serverSockets.poll(5, TimeUnit.SECONDS) ?: error("server socket never opened")
|
||||
|
||||
fun sendGatewayReady(webSocket: WebSocket) {
|
||||
webSocket.send(eventFrame("gateway.ready", null, null))
|
||||
}
|
||||
|
||||
fun awaitRpc(method: String): JsonObject {
|
||||
val deadline = System.currentTimeMillis() + 5_000
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
@@ -1407,6 +1414,27 @@ class GatewayChatClientTest {
|
||||
assertEquals(listOf("stored-session"), resumedSessions.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `observation warmup never claims or interrupts a foreign runtime`() = runBlocking {
|
||||
val registrations = AtomicInteger(0)
|
||||
client.setUnsolicitedTurnProvider {
|
||||
registrations.incrementAndGet()
|
||||
GatewayInboundTurnRegistration(Recorder().callbacks) { true }
|
||||
}
|
||||
|
||||
assertTrue(client.observeAwait())
|
||||
val serverWs = harness.awaitServerSocket()
|
||||
serverWs.send(harness.eventFrame("message.start", null, "foreign-runtime"))
|
||||
delay(100)
|
||||
client.shutdown()
|
||||
|
||||
assertEquals(0, registrations.get())
|
||||
assertFalse(harness.rpcLog.any { it.first == "session.resume" })
|
||||
assertFalse(harness.rpcLog.any { it.first == "session.activate" })
|
||||
assertFalse(harness.rpcLog.any { it.first == "session.interrupt" })
|
||||
assertFalse(harness.rpcLog.any { it.first == "prompt.submit" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `newer prewarm selection wins when an older resume completes late`() = runBlocking {
|
||||
harness.suppressAckMethods += "session.resume"
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.test.hasScrollAction
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.test.swipeUp
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
import com.hermesandroid.relay.data.HermesCardInput
|
||||
import com.hermesandroid.relay.ui.components.HermesCardBubble
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import java.io.File
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class ClarifyCardScreenshotTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w320dp-h568dp-xhdpi")
|
||||
fun compactPhoneLongOptions() = capture("01-compact-phone-long-options.png", 1f)
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w320dp-h568dp-xhdpi")
|
||||
fun compactPhoneLargeText() = capture("02-compact-phone-font-1_5.png", 1.5f)
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w720dp-h360dp-xhdpi")
|
||||
fun landscape() = capture("03-landscape-720x360.png", 1f)
|
||||
|
||||
@Test
|
||||
@Config(qualifiers = "w330dp-h720dp-xhdpi")
|
||||
fun foldablePaneWidth() = capture("04-foldable-narrow-pane.png", 1.3f)
|
||||
|
||||
private fun capture(fileName: String, fontScale: Float) {
|
||||
compose.setContent {
|
||||
val density = LocalDensity.current
|
||||
CompositionLocalProvider(
|
||||
LocalDensity provides Density(density.density, fontScale),
|
||||
) {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
LazyColumn(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
item {
|
||||
HermesCardBubble(
|
||||
card = clarifyCard(),
|
||||
cardKey = "clarify-render",
|
||||
dispatches = emptyList(),
|
||||
onActionTap = { _, _ -> },
|
||||
onInputSubmit = { _, _ -> },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("Other (type your answer)…").assertExists()
|
||||
repeat(4) { compose.onNode(hasScrollAction()).performTouchInput { swipeUp() } }
|
||||
val evidenceDir = File("build/ui-evidence/clarify-card")
|
||||
evidenceDir.mkdirs()
|
||||
compose.onRoot().captureRoboImage(File(evidenceDir, fileName).path)
|
||||
}
|
||||
|
||||
private fun clarifyCard() = HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_CLARIFY,
|
||||
title = "Hermes needs clarification",
|
||||
body = "Which deployment approach should I use for the migration?",
|
||||
input = HermesCardInput(
|
||||
kind = HermesCardInput.Kinds.CHOICE,
|
||||
choices = listOf(
|
||||
"Migrate everything immediately and accept a short maintenance window",
|
||||
"Keep both systems running while traffic moves in measured stages",
|
||||
"Pause until every downstream consumer has been verified",
|
||||
"Use a reversible canary rollout with automatic rollback thresholds",
|
||||
),
|
||||
allowFreeText = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
-82
@@ -13,10 +13,7 @@ import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.click
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performImeAction
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.compose.ui.test.performTouchInput
|
||||
import androidx.compose.ui.test.swipeDown
|
||||
import androidx.compose.ui.test.swipeUp
|
||||
@@ -150,74 +147,6 @@ class HermesApprovalCardInteractionTest {
|
||||
compose.runOnIdle { assertEquals(listOf("[\"prod\",\"dev\"]"), answers) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `custom clarify answer uses IME send and trims exactly once`() {
|
||||
val answers = mutableListOf<String>()
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
HermesCardBubble(
|
||||
card = clarifyCard(),
|
||||
cardKey = "clarify-custom",
|
||||
dispatches = emptyList(),
|
||||
onActionTap = { _, _ -> },
|
||||
onInputSubmit = { _, value -> answers += value },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val field = compose.onNodeWithContentDescription("Other (type your answer)…")
|
||||
field.performTextInput(" use a hybrid rollout ")
|
||||
field.performImeAction()
|
||||
|
||||
compose.runOnIdle { assertEquals(listOf("use a hybrid rollout"), answers) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blank custom clarify answer cannot submit from icon or IME`() {
|
||||
val answers = mutableListOf<String>()
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
HermesCardBubble(
|
||||
card = clarifyCard(),
|
||||
cardKey = "clarify-blank",
|
||||
dispatches = emptyList(),
|
||||
onActionTap = { _, _ -> },
|
||||
onInputSubmit = { _, value -> answers += value },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val field = compose.onNodeWithContentDescription("Other (type your answer)…")
|
||||
field.performTextInput(" ")
|
||||
compose.onNodeWithContentDescription("Send answer").assertIsNotEnabled()
|
||||
field.performImeAction()
|
||||
|
||||
compose.runOnIdle { assertEquals(emptyList<String>(), answers) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `multi select IME submission combines choices and custom answer`() {
|
||||
val answers = mutableListOf<String>()
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
HermesCardBubble(
|
||||
card = clarifyCard(multiSelect = true),
|
||||
cardKey = "clarify-multi-custom",
|
||||
dispatches = emptyList(),
|
||||
onActionTap = { _, _ -> },
|
||||
onInputSubmit = { _, value -> answers += value },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("stage").performTouchInput { click() }
|
||||
val field = compose.onNodeWithContentDescription("Other (type your answer)…")
|
||||
field.performTextInput("canary first")
|
||||
field.performImeAction()
|
||||
|
||||
compose.runOnIdle { assertEquals(listOf("[\"stage\",\"canary first\"]"), answers) }
|
||||
}
|
||||
|
||||
private fun approvalCard() = HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_APPROVAL,
|
||||
title = "Approval requested",
|
||||
@@ -244,17 +173,6 @@ class HermesApprovalCardInteractionTest {
|
||||
id = CARD_KEY,
|
||||
)
|
||||
|
||||
private fun clarifyCard(multiSelect: Boolean = false) = HermesCard(
|
||||
type = HermesCard.BuiltInTypes.ASK_CLARIFY,
|
||||
title = "Choose environments",
|
||||
input = HermesCardInput(
|
||||
kind = HermesCardInput.Kinds.CHOICE,
|
||||
choices = listOf("dev", "stage", "prod"),
|
||||
multiSelect = multiSelect,
|
||||
allowFreeText = true,
|
||||
),
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val CARD_KEY = "approval-session-a"
|
||||
}
|
||||
|
||||
+186
-85
@@ -11,7 +11,6 @@ import com.hermesandroid.relay.data.ChatTurnCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
|
||||
import com.hermesandroid.relay.data.ChatTurnToolCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
import com.hermesandroid.relay.data.HermesCardDispatch
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
@@ -993,11 +992,12 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition { handler.messages.value.any { it.content == "Partial A" } }
|
||||
|
||||
viewModel.switchSession(secondSession)
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
awaitCondition { handler.currentSessionId.value == secondSession && !handler.isStreaming.value }
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "session.resume" })
|
||||
assertTrue(gatewayHarness.rpcLog.none { it.first == "session.interrupt" })
|
||||
|
||||
viewModel.sendMessage("Run task B")
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
gatewayHarness.awaitRpcCount("prompt.submit", 2)
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
@@ -1050,65 +1050,6 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
assertTrue(gatewayHarness.rpcLog.none { it.first == "session.interrupt" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detachedClarifyExpiryCannotRestoreAStaleCardAfterNavigation() {
|
||||
val secondSession = "stored-session-b"
|
||||
val contextKey = AgentDisplay.profileContextKey("connection-a", null)
|
||||
val checkpointStore = MemoryCheckpointStore()
|
||||
gatewayHarness.resumeLiveSessionIds[secondSession] = "live-b"
|
||||
viewModel.setChatTurnCheckpointStore(checkpointStore)
|
||||
viewModel.switchProfileContext(contextKey, STORED_SESSION_ID)
|
||||
|
||||
viewModel.sendMessage("Ask before continuing")
|
||||
gatewayHarness.awaitRpc("prompt.submit")
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"clarify.request",
|
||||
buildJsonObject {
|
||||
put("request_id", "clarify-detached")
|
||||
put("question", "Which rollout?")
|
||||
put("choices", buildJsonArray {
|
||||
add(JsonPrimitive("canary"))
|
||||
add(JsonPrimitive("all at once"))
|
||||
})
|
||||
},
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { viewModel.pendingAsk.value?.ask?.requestId == "clarify-detached" }
|
||||
|
||||
viewModel.switchSession(secondSession)
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
awaitCondition { handler.currentSessionId.value == secondSession }
|
||||
awaitCondition { checkpointStore.checkpoint?.pendingAsk?.requestId == "clarify-detached" }
|
||||
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"clarify.expire",
|
||||
buildJsonObject { put("request_id", "clarify-detached") },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition {
|
||||
checkpointStore.checkpoint != null && checkpointStore.checkpoint?.pendingAsk == null
|
||||
}
|
||||
|
||||
gatewayHarness.recoveryRunning = true
|
||||
gatewayHarness.recoveryAssistant = "Waiting for rollout choice"
|
||||
viewModel.switchSession(STORED_SESSION_ID)
|
||||
gatewayHarness.awaitRpc("session.activate")
|
||||
awaitCondition {
|
||||
handler.currentSessionId.value == STORED_SESSION_ID && handler.isStreaming.value
|
||||
}
|
||||
|
||||
assertNull(viewModel.pendingAsk.value)
|
||||
assertTrue(
|
||||
handler.messages.value.flatMap { it.cards }
|
||||
.none { it.type == HermesCard.BuiltInTypes.ASK_CLARIFY },
|
||||
)
|
||||
assertTrue(gatewayHarness.rpcLog.none { it.first == "clarify.respond" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stopOnUnsolicitedTurnInterruptsTheGatewaySession() {
|
||||
serverWs.send(gatewayHarness.eventFrame("message.start", null, "live-resumed"))
|
||||
@@ -1884,11 +1825,12 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
awaitCondition { viewModel.queuedMessages.value == listOf("Follow up A") }
|
||||
|
||||
viewModel.switchSession(secondSession)
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
awaitCondition { handler.currentSessionId.value == secondSession && !handler.isStreaming.value }
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "session.resume" })
|
||||
assertTrue("session B must not show A's queue", viewModel.queuedMessages.value.isEmpty())
|
||||
|
||||
viewModel.sendMessage("Run task B")
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
gatewayHarness.awaitRpcCount("prompt.submit", 2)
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
@@ -2091,13 +2033,16 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
serverWs.close(1012, "test disconnect")
|
||||
awaitCondition { gatewayClient.connectionState.value == GatewayConnectionState.Idle }
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
viewModel.prewarmGateway()
|
||||
gatewayHarness.awaitServerSocket()
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
|
||||
awaitCondition {
|
||||
handler.messages.value.singleOrNull()?.content == BACKGROUND_ANSWER
|
||||
}
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "session.resume" })
|
||||
assertEquals(0, gatewayHarness.rpcLog.count { it.first == "session.activate" })
|
||||
assertEquals(0, gatewayHarness.rpcLog.count { it.first == "session.interrupt" })
|
||||
assertFalse(handler.isStreaming.value)
|
||||
}
|
||||
|
||||
@@ -2108,16 +2053,19 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
|
||||
// Foreground arrives while OkHttp still reports the old socket ready,
|
||||
// so the one-shot prewarm is an intentional no-op. The delayed close
|
||||
// callback must itself trigger an exact-session reattach.
|
||||
// callback must itself restore the observation socket and catch up
|
||||
// history without attaching the live session.
|
||||
viewModel.prewarmGateway()
|
||||
serverWs.close(1012, "late background close")
|
||||
|
||||
awaitCondition { gatewayHarness.ticketMints.get() >= 2 }
|
||||
serverWs = gatewayHarness.awaitServerSocket()
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
awaitCondition {
|
||||
handler.messages.value.singleOrNull()?.content == BACKGROUND_ANSWER
|
||||
}
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "session.resume" })
|
||||
assertEquals(0, gatewayHarness.rpcLog.count { it.first == "session.activate" })
|
||||
assertEquals(0, gatewayHarness.rpcLog.count { it.first == "session.interrupt" })
|
||||
assertFalse(handler.isStreaming.value)
|
||||
}
|
||||
|
||||
@@ -2426,36 +2374,189 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconnectAfterMissedStartRecoversOnExactSessionCompletion() {
|
||||
fun reconnectCatchupClosesCompletionBetweenFirstReadAndIdleSnapshot() {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
awaitCondition { !viewModel.isLoadingHistory.value }
|
||||
val firstReadStarted = CompletableDeferred<Unit>()
|
||||
val releaseFirstRead = CompletableDeferred<Unit>()
|
||||
val readCount = AtomicInteger(0)
|
||||
viewModel.setProfileMessageLoader {
|
||||
if (readCount.incrementAndGet() == 1) {
|
||||
firstReadStarted.complete(Unit)
|
||||
releaseFirstRead.await()
|
||||
Result.success(emptyList())
|
||||
} else {
|
||||
Result.success(persistedHistory)
|
||||
}
|
||||
}
|
||||
serverWs.close(1012, "missed start")
|
||||
awaitCondition { gatewayClient.connectionState.value == GatewayConnectionState.Idle }
|
||||
viewModel.setChatVisible(true)
|
||||
viewModel.prewarmGateway()
|
||||
serverWs = gatewayHarness.awaitServerSocket()
|
||||
gatewayHarness.awaitRpcCount("session.resume", 2)
|
||||
|
||||
// Reconnected midway through the synthetic turn: no message.start is
|
||||
// replayed, so the delta is intentionally ignored and completion drives
|
||||
// authoritative history recovery.
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", BACKGROUND_ANSWER) },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
awaitCondition { firstReadStarted.isCompleted }
|
||||
// Completion persists after the reconnect's first catch-up read began,
|
||||
// while the first active-list snapshot is already empty/idle. The
|
||||
// pending final-read marker must close this exact ordering window.
|
||||
persistedHistory = persistedAnswerHistory()
|
||||
serverWs.send(
|
||||
gatewayHarness.eventFrame(
|
||||
"message.complete",
|
||||
buildJsonObject { put("text", BACKGROUND_ANSWER) },
|
||||
"live-resumed",
|
||||
),
|
||||
)
|
||||
releaseFirstRead.complete(Unit)
|
||||
|
||||
awaitCondition { handler.messages.value.any { it.content == BACKGROUND_ANSWER } }
|
||||
assertEquals(1, gatewayHarness.rpcLog.count { it.first == "session.resume" })
|
||||
assertEquals(0, gatewayHarness.rpcLog.count { it.first == "session.activate" })
|
||||
assertEquals(0, gatewayHarness.rpcLog.count { it.first == "session.interrupt" })
|
||||
assertFalse(handler.isStreaming.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passiveForegroundObservationNeverClaimsOrInterruptsDesktopTurn() {
|
||||
val observerProfile = Profile(
|
||||
name = "observer",
|
||||
model = "model-a",
|
||||
description = "Observer",
|
||||
)
|
||||
viewModel.setSelectedProfileProvider { observerProfile }
|
||||
viewModel.setSessionProfileNameProvider { observerProfile.name }
|
||||
viewModel.setProfileMessageLoaderWithMode { profileName, sessionId, _ ->
|
||||
assertEquals(STORED_SESSION_ID, sessionId)
|
||||
Result.success(
|
||||
if (profileName == observerProfile.name) {
|
||||
persistedHistory
|
||||
} else {
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "wrong-profile",
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("Wrong profile history"),
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
viewModel.switchProfileContext(
|
||||
AgentDisplay.profileContextKey("connection-a", observerProfile.name),
|
||||
STORED_SESSION_ID,
|
||||
)
|
||||
awaitCondition { !viewModel.isLoadingHistory.value }
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val ownershipMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
val baseline = ownershipMethods.associateWith { method ->
|
||||
gatewayHarness.rpcLog.count { it.first == method }
|
||||
}
|
||||
val baselineActiveList = gatewayHarness.rpcLog.count { it.first == "session.active_list" }
|
||||
gatewayHarness.activeSessionListPayload = activeSessionPayload("working")
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = gatewayHarness.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = OkHttpClient(),
|
||||
),
|
||||
okHttpClient = OkHttpClient(),
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(MemoryCheckpointStore())
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
viewModel.prewarmGateway()
|
||||
awaitCondition {
|
||||
gatewayHarness.rpcLog.count { it.first == "session.active_list" } > baselineActiveList
|
||||
}
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = "desktop-answer",
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("Desktop completed without Android attachment."),
|
||||
),
|
||||
)
|
||||
awaitCondition {
|
||||
handler.messages.value.singleOrNull()?.content ==
|
||||
"Desktop completed without Android attachment."
|
||||
}
|
||||
ownershipMethods.forEach { method ->
|
||||
assertEquals(
|
||||
"passive foreground sent $method",
|
||||
baseline.getValue(method),
|
||||
gatewayHarness.rpcLog.count { it.first == method },
|
||||
)
|
||||
}
|
||||
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
assertEquals(
|
||||
"observer teardown interrupted the Desktop turn",
|
||||
baseline.getValue("session.interrupt"),
|
||||
gatewayHarness.rpcLog.count { it.first == "session.interrupt" },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun observerReadyAfterChatHidesCannotRestartPassiveWork() {
|
||||
viewModel.switchProfileContext(PROFILE_CONTEXT, STORED_SESSION_ID)
|
||||
awaitCondition { !viewModel.isLoadingHistory.value }
|
||||
viewModel.setChatVisible(false)
|
||||
viewModel.updateGatewayClient(null)
|
||||
gatewayClient.shutdown()
|
||||
gatewayScope.cancel()
|
||||
|
||||
val historyReads = AtomicInteger(0)
|
||||
viewModel.setProfileMessageLoader {
|
||||
historyReads.incrementAndGet()
|
||||
Result.success(persistedHistory)
|
||||
}
|
||||
val controlMethods = setOf(
|
||||
"session.resume",
|
||||
"session.activate",
|
||||
"session.interrupt",
|
||||
"prompt.submit",
|
||||
)
|
||||
val baseline = controlMethods.associateWith { method ->
|
||||
gatewayHarness.rpcLog.count { it.first == method }
|
||||
}
|
||||
val baselineActiveList = gatewayHarness.rpcLog.count { it.first == "session.active_list" }
|
||||
gatewayHarness.suppressGatewayReady = true
|
||||
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
gatewayClient = GatewayChatClient(
|
||||
initialDashboardClient = DashboardApiClient(
|
||||
baseUrl = gatewayHarness.server.url("/").toString().trimEnd('/'),
|
||||
okHttpClient = OkHttpClient(),
|
||||
),
|
||||
okHttpClient = OkHttpClient(),
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
scope = gatewayScope,
|
||||
)
|
||||
viewModel.setChatTurnCheckpointStore(MemoryCheckpointStore())
|
||||
viewModel.updateGatewayClient(gatewayClient)
|
||||
|
||||
viewModel.setChatVisible(true)
|
||||
val delayedSocket = gatewayHarness.awaitServerSocket()
|
||||
viewModel.setChatVisible(false)
|
||||
gatewayHarness.sendGatewayReady(delayedSocket)
|
||||
shadowOf(Looper.getMainLooper()).idleFor(500, TimeUnit.MILLISECONDS)
|
||||
Thread.sleep(100)
|
||||
|
||||
assertEquals(0, historyReads.get())
|
||||
assertEquals(
|
||||
baselineActiveList,
|
||||
gatewayHarness.rpcLog.count { it.first == "session.active_list" },
|
||||
)
|
||||
controlMethods.forEach { method ->
|
||||
assertEquals(baseline.getValue(method), gatewayHarness.rpcLog.count { it.first == method })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staleHistoryReadCannotEraseATurnCompletedDuringTheFetch() {
|
||||
val loadCount = AtomicInteger(0)
|
||||
|
||||
@@ -3977,3 +3977,36 @@ disappearance, client-side profile isolation, and method-not-found; physical
|
||||
and current-host certification remains tracked in `TODO.md`. An upstream
|
||||
profile field/filter or explicitly owned aggregate activity route would remove
|
||||
the remaining ambiguity for multi-profile clients.
|
||||
|
||||
---
|
||||
|
||||
## ADR 69 — Passive Android observation never attaches another client's Gateway turn
|
||||
|
||||
**Status:** Accepted (2026-08-28).
|
||||
|
||||
**Context.** `session.resume` and `session.activate` are live-runtime attachment
|
||||
operations, not read-only subscriptions. Android previously called
|
||||
`session.resume` while opening or foregrounding Chat and after loading a saved
|
||||
session's history. When Desktop/TUI already owned a running turn, that passive
|
||||
prewarm could rebind the runtime transport to Android. A later Android socket,
|
||||
route, or client teardown could then strand the producer or promote the foreign
|
||||
turn into an Android `GatewayTurn` whose cancellation sends `session.interrupt`.
|
||||
The issue was distinct from the earlier stale-view and missing-terminal recovery
|
||||
paths, which concern exact Android-owned checkpoints.
|
||||
|
||||
**Decision.** Ordinary visibility, foreground restoration, Idle-socket recovery,
|
||||
and saved-session selection establish only the shared Gateway socket. They use
|
||||
profile-scoped REST history plus process-wide `session.active_list`; while an
|
||||
unowned row with the selected durable id is live, Android performs bounded
|
||||
history refreshes and one final read after settlement. These observer paths send
|
||||
no `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`.
|
||||
Exact Android-owned checkpoints retain `session.activate` with durable-resume
|
||||
fallback, and explicit send or session-config actions may resume because the user
|
||||
is intentionally taking control of that destination.
|
||||
|
||||
**Consequences.** Opening Android cannot replace, stop, or later cancel a turn
|
||||
already running in Desktop/TUI. Live token frames remain with the producing
|
||||
client; Android observes durable progress and final history without inventing a
|
||||
multi-subscriber Gateway contract. The first explicit Android mutation may pay
|
||||
the resume latency that passive prewarm previously hid. Cross-client fixtures
|
||||
and Android lifecycle coverage enforce the no-control-RPC observation boundary.
|
||||
|
||||
@@ -41,6 +41,7 @@ the upstream contract identifiers it depends on.
|
||||
| `active_status_lifecycle` | `session.active_list` reports starting, working, waiting, and idle, then a complete empty process-wide snapshot permits removal of unambiguously owned prior rows |
|
||||
| `active_status_profile_scope` | A row has no profile metadata and a caller profile hint has no effect; the client must use exact client-held ownership and reject invented attribution |
|
||||
| `active_status_unsupported` | An older Gateway returns JSON-RPC method-not-found; the client retains Unknown rather than inventing Idle or Working |
|
||||
| `cross_client_observation` | A second client observes a Desktop-owned working session through active status and history without resume, activate, submit, or interrupt; the producing client receives the terminal event |
|
||||
|
||||
Fixture evidence is a bounded metadata-only ring. It records sequence,
|
||||
connection number, RPC method, event type, scope classification, and outcome.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "f300cbaf71e3600130e51120b76272fbcdd5ea1d073c95c684d054ced457747d",
|
||||
"main": "28d58a3b9803968124ea6581fd9dbb3a0ce2a9ee1c946228bb6f0b79f987a24a",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -48,7 +48,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "f300cbaf71e3600130e51120b76272fbcdd5ea1d073c95c684d054ced457747d",
|
||||
"main": "28d58a3b9803968124ea6581fd9dbb3a0ce2a9ee1c946228bb6f0b79f987a24a",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -72,7 +72,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "f300cbaf71e3600130e51120b76272fbcdd5ea1d073c95c684d054ced457747d",
|
||||
"main": "28d58a3b9803968124ea6581fd9dbb3a0ce2a9ee1c946228bb6f0b79f987a24a",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -96,7 +96,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "f300cbaf71e3600130e51120b76272fbcdd5ea1d073c95c684d054ced457747d",
|
||||
"main": "28d58a3b9803968124ea6581fd9dbb3a0ce2a9ee1c946228bb6f0b79f987a24a",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -120,7 +120,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "f300cbaf71e3600130e51120b76272fbcdd5ea1d073c95c684d054ced457747d",
|
||||
"main": "28d58a3b9803968124ea6581fd9dbb3a0ce2a9ee1c946228bb6f0b79f987a24a",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -135,7 +135,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "f300cbaf71e3600130e51120b76272fbcdd5ea1d073c95c684d054ced457747d",
|
||||
"main": "28d58a3b9803968124ea6581fd9dbb3a0ce2a9ee1c946228bb6f0b79f987a24a",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
|
||||
+1
-1
@@ -481,7 +481,7 @@ Bottom navigation bar with 4 tabs:
|
||||
- **Bot group projection** — Android merges the bounded `ui_meta["hermes-bots-groups"]` v3 projection across gateways by durable room identity and newest revision. Rooms and recent messages are visibly read-only; Android does not create, rename, disband, join, send, coordinate member turns, or become a second room-log authority. Binary room images are ignored at this metadata boundary.
|
||||
- **Session drawer** (swipe from left or hamburger icon) — session list with title, timestamp, message count. Create, switch, rename, delete, pin/unpin, and archive/restore. The process-owned conversation binding is the single connection/profile/session identity for Chat; selecting an All Profiles row atomically makes its owner the selected agent and persists that profile/session, while merely browsing All Profiles changes no agent state. Lifecycle or locale-driven Activity recreation cannot replace an explicit binding with stale persisted state, and asynchronous list/history/mutation work is accepted only for the binding's exact namespace. A profile lock hides All Profiles and rejects stale/deep-linked cross-profile opens. The All Profiles browser mode otherwise survives Activity state restoration and refetches its rows after recreation. Pin and archive are durable upstream session fields loaded and patched through the owning connection/profile's Dashboard session API; Android does not keep a second local flag registry. Archived rows are requested explicitly so they remain restorable after recreation. Failed mutations roll back the optimistic row, while refresh and deletion reconcile from server truth. When a persisted title is absent, use upstream's first-user-message `preview`, matching the Hermes Desktop session picker; show "Untitled" only when neither value exists.
|
||||
- **Authoritative session activity** — one composite registry keyed by connection, normalized profile, and durable session id drives the drawer, filters, grouping, animation, accessibility, and the visible composer. Exact pending approval/clarify/sudo/secret/MCP requests produce **Needs input**; the Gateway's process-wide `session.active_list` supplies **Starting**, **Working**, and **Idle**; exact terminal or `session.info {running:false}` can settle the matching generation. Because active-list rows normally have no profile metadata, Android assigns a row only through exact foreground/detached ownership already held by that client, or explicit profile metadata if a future upstream sends it. A bounded REST directory never proves global uniqueness. Unresolved rows create no status. Resolved rows from a partial snapshot may update their exact owners, but disappearance settles a scope only when the successful process-wide snapshot was completely and unambiguously resolved for it. Restart/checkpoint recovery is **Checking**; a failed or unsupported live refresh is **Unavailable**, never inferred Idle. REST `is_active` remains recency metadata only. `process.list` may add a separate **Background work** indicator and never keeps the parent conversation Working. Old socket generations, bare session ids from another profile, and delayed snapshots cannot revive newer settled state.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible turn without sending `session.interrupt`; each running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Explicit Stop still interrupts. SSE fallback stays single-stream and cancels on navigation.
|
||||
- **Concurrent Gateway chats** — switching sessions, profiles, drafts, or Threads detaches the visible Android-owned turn without sending `session.interrupt`; each Android-owned running chat keeps a connection/profile/session-scoped checkpoint and reattaches to its live Gateway session when reopened. Opening, foregrounding, or selecting a saved session without that exact checkpoint is read-only observation: Android warms only the socket, reads profile-scoped history, and polls `session.active_list` without `session.resume`, `session.activate`, `prompt.submit`, or `session.interrupt`. A Desktop/TUI-owned turn therefore remains owned by its producing client; Android refreshes persisted progress and performs one final history read when the runtime settles. Explicit send/config actions may resume the destination session, explicit Stop still interrupts, and SSE fallback stays single-stream and cancels on navigation.
|
||||
- **Queued Gateway follow-ups** — every local queued item is immutably scoped to its originating connection, profile, stored session, transport, and run generation; only that run's completion can make it eligible, and switching sessions shows only that session's queue. Restored text queues retain the same scope, while unavailable/deleted destinations and non-restorable attachment queues fail visibly instead of following the current composer. Drained messages add `queued: true` to `prompt.submit`; ordinary sends omit the field. Authoritative submit rejections (`4004`, `4018`, `4028`, `4029`, `4030`, `4090`, `5008`, `5070`, and `5071`) preserve the server message and never fall through to API-server SSE.
|
||||
- **Durable composer drafts** — each connection/profile/session owns one app-private draft containing text, quote/edit context, and pending attachment bytes. Metadata and content-addressed blobs live under Android's no-backup directory, are capped at 64 drafts and 128 MB of retained blobs outside the active draft, flush when Chat backgrounds, and are removed after a successful send. Session/profile/connection navigation saves the previous owner before restoring the destination; an opened cross-profile session uses its actual owning profile rather than the global picker.
|
||||
- **Large paste review** — a default-on Chat setting converts any single insertion of at least 5,000 characters into a visible `pasted-text.txt` attachment before the normal message-length limit rejects it. Gateway uses upstream `file.attach`; API-server SSE and proactive Thread paths materialize the same UTF-8 text into the outgoing prompt and remove only the synthetic attachment from that transport, so the behavior never requires Relay or silently drops content.
|
||||
|
||||
@@ -100,6 +100,47 @@ class FixtureTestCase(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(["user", "assistant"], [row["role"] for row in history["messages"]])
|
||||
self.assertEqual(2, history["pagination"]["returned"])
|
||||
|
||||
async def test_cross_client_observer_never_claims_or_interrupts_producer(self) -> None:
|
||||
fixture, base_url = await self.start("cross_client_observation")
|
||||
producer, _ = await self.connect(base_url)
|
||||
await self.rpc(producer, 1, "session.resume", {"session_id": fixture.scenario.stored_session_id})
|
||||
await producer.receive_json()
|
||||
await self.rpc(producer, 2, "prompt.submit", {"text": "producer-only content"})
|
||||
producer_frames = await self.frames_until(
|
||||
producer,
|
||||
lambda frame: frame.get("params", {}).get("type") == "message.delta",
|
||||
)
|
||||
|
||||
observer, _ = await self.connect(base_url)
|
||||
await self.rpc(observer, 3, "session.active_list")
|
||||
active = (await observer.receive_json())["result"]["sessions"]
|
||||
self.assertEqual("working", active[0]["status"])
|
||||
async with self.session.get(
|
||||
f"{base_url}/api/sessions/{fixture.scenario.stored_session_id}/messages",
|
||||
params={"profile": "default", "limit": 500, "offset": 0, "order": "asc"},
|
||||
) as response:
|
||||
self.assertEqual(200, response.status)
|
||||
self.assertIsInstance((await response.json())["messages"], list)
|
||||
await observer.close()
|
||||
|
||||
producer_frames += await self.frames_until(
|
||||
producer,
|
||||
lambda frame: frame.get("params", {}).get("type") == "message.complete",
|
||||
)
|
||||
self.assertIn(
|
||||
"message.complete",
|
||||
[frame.get("params", {}).get("type") for frame in producer_frames],
|
||||
)
|
||||
async with self.session.get(f"{base_url}/__fixture__/evidence") as response:
|
||||
evidence = await response.json()
|
||||
observer_methods = [
|
||||
entry.get("method")
|
||||
for entry in evidence["entries"]
|
||||
if entry.get("kind") == "rpc" and entry.get("connection") == 2
|
||||
]
|
||||
self.assertEqual(["session.active_list"], observer_methods)
|
||||
self.assertNotIn("session.interrupt", observer_methods)
|
||||
|
||||
async def test_rapid_chunks_tools_and_interims_keep_wire_order(self) -> None:
|
||||
_, base_url = await self.start("rapid_tools_interims")
|
||||
ws, _ = await self.connect(base_url)
|
||||
@@ -265,6 +306,7 @@ class ScenarioTestCase(unittest.TestCase):
|
||||
"active_status_lifecycle",
|
||||
"active_status_profile_scope",
|
||||
"active_status_unsupported",
|
||||
"cross_client_observation",
|
||||
"ordinary_turn",
|
||||
"rapid_tools_interims",
|
||||
"terminal_gap_activate",
|
||||
@@ -304,6 +346,10 @@ class ScenarioTestCase(unittest.TestCase):
|
||||
("gateway.settled_session_info",),
|
||||
load_scenario("terminal_gap_session_info").contract_requirements,
|
||||
)
|
||||
self.assertEqual(
|
||||
("gateway.message_complete", "gateway.session_active_list"),
|
||||
load_scenario("cross_client_observation").contract_requirements,
|
||||
)
|
||||
|
||||
def test_tls_arguments_must_be_paired(self) -> None:
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "cross_client_observation",
|
||||
"live_session_id": "fixture-desktop-live",
|
||||
"stored_session_id": "fixture-shared-session",
|
||||
"profile": "default",
|
||||
"contract_requirements": [
|
||||
"gateway.message_complete",
|
||||
"gateway.session_active_list"
|
||||
],
|
||||
"initial_history": [],
|
||||
"turns": [
|
||||
{
|
||||
"steps": [
|
||||
{"op": "event", "type": "message.start"},
|
||||
{"op": "event", "type": "message.delta", "payload": {"text": "Desktop still owns this turn."}},
|
||||
{"op": "sleep", "milliseconds": 250},
|
||||
{
|
||||
"op": "persist",
|
||||
"messages": [
|
||||
{"id": 1, "role": "user", "content": "Desktop prompt.", "timestamp": 1.0},
|
||||
{"id": 2, "role": "assistant", "content": "Desktop still owns this turn.", "timestamp": 2.0, "finish_reason": "stop"}
|
||||
]
|
||||
},
|
||||
{"op": "set_running", "value": false},
|
||||
{"op": "event", "type": "message.complete", "payload": {"text": "Desktop still owns this turn.", "status": "complete"}}
|
||||
]
|
||||
}
|
||||
],
|
||||
"active_list": {
|
||||
"supported": true,
|
||||
"snapshots": [
|
||||
[
|
||||
{"id": "fixture-desktop-live", "session_key": "fixture-shared-session", "status": "working", "current": false}
|
||||
],
|
||||
[
|
||||
{"id": "fixture-desktop-live", "session_key": "fixture-shared-session", "status": "idle", "current": false}
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user