From dee92d541e44a2bbc40b023809a41e4eb3851a90 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 12 Nov 2026 02:14:22 +0800 Subject: [PATCH] fix(remote-connect): isolate host stream readers and recover live sync - Give every host stream reader its own optional subscription_id lease. A capable host echoes it and removes only that lease on unsubscribe, so a retired reader's late cleanup no longer cancels its replacement. Readers talking to older hosts skip cleanup and let the existing lease expire. - Retry a failed live read on a timer with capped backoff instead of sleeping inside the subscriber loop, also during older-page IO, and report recovery with a live ready event that does not complete an unrelated history page. - Tag desktop session events with a controller-local subscriptionId and mark retryable sync errors so a stale reader cannot fail its successor. - Install hint and reconnect listeners before the opening read in the shared TS and KMP readers so a final hint during that read is not lost. - HarmonyOS stream cleanup keeps the socket it opened, so closing after an account switch cannot touch the new account's connection. --- .../desktop/src/api/remote_connect_api.rs | 13 +- .../entry/src/main/ets/model/RemoteModels.ets | 1 + .../main/ets/services/CloudAccountClient.ets | 17 +- .../main/ets/services/HostSessionStream.ets | 1 + .../tools/tests/host-stream.test.cjs | 44 ++++ .../mobile/core/protocol/RemoteCommand.kt | 1 + .../core/transport/CloudAccountClient.kt | 18 +- .../mobile/core/transport/HostStream.kt | 12 +- .../core/transport/CloudAccountClientTest.kt | 60 ++++- .../mobile/core/transport/HostStreamTest.kt | 24 ++ .../host_stream_command_tests.rs | 58 ++++- .../core/src/service/remote_connect/mod.rs | 17 +- .../src/remote_connect.rs | 4 + .../src/remote_connect/host_stream.rs | 80 +++++- .../host_stream/turn_history.rs | 3 +- .../remote_connect/host_stream_subscriber.rs | 230 ++++++++++++++++-- .../src/services/RelayHttpClient.ts | 4 +- src/mobile-web/tests/host-stream.test.mjs | 48 +++- .../tests/session-stream-browser.test.mjs | 12 +- src/shared/relay-transport/HostStream.ts | 57 +++-- .../services/RelaySessionHistory.test.ts | 95 ++++++++ .../flow_chat/services/RelaySessionHistory.ts | 71 ++++-- .../src/flow_chat/store/FlowChatStore.test.ts | 26 +- .../src/flow_chat/store/FlowChatStore.ts | 9 +- .../api/service-api/RemoteConnectAPI.ts | 4 +- .../src/infrastructure/peer-device/README.md | 20 ++ 26 files changed, 830 insertions(+), 99 deletions(-) diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 786a115b68..3aa821f66b 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -3947,6 +3947,11 @@ pub async fn account_load_older_session(request: UnsubscribeSessionRequest) -> R pub async fn account_subscribe_session(request: SubscribeSessionRequest) -> Result { let generation = account_context_generation(); let (session, relay) = read_account_context_for_generation(generation).await?; + // Events can arrive before this command returns. Give every attempt an + // identity so a late error/page from a retired reader cannot poison its successor. + let id = uuid::Uuid::new_v4().to_string(); + let event_subscription_id = id.clone(); + let error_subscription_id = id.clone(); let source = request.target_device_id.clone(); let error_source = source.clone(); let error_session_id = request.session_id.clone(); @@ -3960,21 +3965,23 @@ pub async fn account_subscribe_session(request: SubscribeSessionRequest) -> Resu if !account_context_is_current(generation) { anyhow::bail!("account subscription retired"); } - emit_account_event(&event.event, tag_peer_event_source(event.payload, &source)); + let mut payload = tag_peer_event_source(event.payload, &source); + payload["subscriptionId"] = event_subscription_id.clone().into(); + emit_account_event(&event.event, payload); Ok(()) }), Arc::new(move |error| { if account_context_is_current(generation) { emit_account_event( "account://session-sync-error", - serde_json::json!({"message":error,"sessionId":error_session_id,"targetDeviceId":error_source}), + serde_json::json!({"message":error,"sessionId":error_session_id,"targetDeviceId":error_source, + "subscriptionId":error_subscription_id,"retrying":true}), ); } }), ) .await .map_err(|e| e.to_string())?; - let id = uuid::Uuid::new_v4().to_string(); let mut subscriptions = SESSION_SUBSCRIPTIONS .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new())) .lock() diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets index 00b8f518e2..15eb301fe3 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/model/RemoteModels.ets @@ -188,6 +188,7 @@ export interface RemoteCommand { before?: number; epoch?: number; subscribe?: boolean; + subscription_id?: string; } export interface PairChallengeResponse { diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets index a63f0eacec..3ea6333871 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/CloudAccountClient.ets @@ -514,22 +514,29 @@ export class CloudAccountClient { subscribeSession(relayUrl: string, session: CloudAccountSession, targetId: string, streamId: string, callbacks: HostSessionCallbacks): HostSessionStream { const target = targetId.trim(); + const socket = this.connection(relayUrl, session.token); + const subscriptionId = Encoding.randomId('stream'); + let scopedSubscription = false; const source: HostSessionSource = { target: target, - read: (request: HostStreamReadRequest): Promise => { - const command: RemoteCommand = { cmd: 'read_stream', stream_id: streamId, subscribe: true }; + read: async (request: HostStreamReadRequest): Promise => { + if (this.realtime !== socket) throw new Error('Account changed'); + const command: RemoteCommand = { cmd: 'read_stream', stream_id: streamId, subscribe: true, subscription_id: subscriptionId }; if (request.after !== undefined) command.after = request.after; if (request.before !== undefined) command.before = request.before; if (request.epoch !== undefined) command.epoch = request.epoch; - return this.deviceRpc(relayUrl, session, target, command, 30000); + const page = await this.deviceRpc(relayUrl, session, target, command, 30000); + scopedSubscription = page.subscription_id === subscriptionId; + return page; }, unsubscribe: async (): Promise => { + if (this.realtime !== socket || !scopedSubscription) return; await this.deviceRpc(relayUrl, session, target, - { cmd: 'unsubscribe_stream', stream_id: streamId }, 15000); + { cmd: 'unsubscribe_stream', stream_id: streamId, subscription_id: subscriptionId }, 15000); }, onHint: (listener: (hint: HostStreamHint) => void): (() => void) => this.observeStreamHints(relayUrl, session, target, listener), - onReconnect: (listener: () => void): (() => void) => this.connection(relayUrl, session.token).onReconnect(listener) + onReconnect: (listener: () => void): (() => void) => socket.onReconnect(listener) }; return new HostSessionStream(streamId, source, callbacks); } diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets index 2447652f8f..084504fcdd 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/HostSessionStream.ets @@ -29,6 +29,7 @@ export interface HostSessionEvent { session_id: string; event: string; payload: export interface HostStreamEventWire { seq: number; event: string; payload: Object; } /** `RemoteResponse::StreamPage`, flattened, as answered to `read_stream`. */ export interface HostStreamPage extends CommandStatusResponse { + subscription_id?: string; stream_id: string; epoch: number; events: HostStreamEventWire[]; diff --git a/src/apps/mobile/harmonyos/tools/tests/host-stream.test.cjs b/src/apps/mobile/harmonyos/tools/tests/host-stream.test.cjs index 58c4be2d61..68d7afd3a5 100644 --- a/src/apps/mobile/harmonyos/tools/tests/host-stream.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/host-stream.test.cjs @@ -304,3 +304,47 @@ test('lazy disk history keeps JS-safe backward cursors separate from live update assert.equal(c.errors.length, 0); } finally { stream.close(); } }); + +// Use the production account client factory as well as the stream reader: the +// subscription acknowledgement is a wire capability, not a reader-only flag. +test('account stream cleanup negotiates independent leases and leaves old hosts to expiry', async () => { + const clientSource = fs.readFileSync(path.join(__dirname, '../../entry/src/main/ets/services/CloudAccountClient.ets'), 'utf8'); + const exported = {}; let nextId = 0; + new Function('require', 'exports', ts.transpileModule(clientSource, { compilerOptions: { + target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, + } }).outputText)(name => ({ + './HostSessionStream': exportsObject, + './Encoding': { Encoding: { randomId: () => 'reader-' + ++nextId } }, + './RemoteCrypto': { HarmonyRemoteCryptoCipher: class {} }, + }[name] || {}), exported); + for (const scoped of [true, false]) { + const client = new exported.CloudAccountClient(false), commands = []; + const socket = { onReconnect: () => () => {} }; + client.realtime = socket; + client.connection = () => { client.realtime = socket; return socket; }; + client.observeStreamHints = () => () => {}; + client.deviceRpc = async (_url, _session, _target, command) => { + commands.push(command); + return { resp: 'stream_page', stream_id: 's', epoch: 1, cursor: 0, oldest_seq: 1, + events: [], has_more: false, truncated: false, + ...(scoped ? { subscription_id: command.subscription_id } : {}) }; + }; + const first = callbacks(), second = callbacks(); + const a = client.subscribeSession('relay', {}, 'desktop', 's', first.hooks); + const b = client.subscribeSession('relay', {}, 'desktop', 's', second.hooks); + try { + await settle(() => first.caught === 1 && second.caught === 1); + assert.notEqual(commands[0].subscription_id, commands[1].subscription_id); + a.close(); await tick(); + const cleanup = commands.filter(command => command.cmd === 'unsubscribe_stream'); + assert.equal(cleanup.length, scoped ? 1 : 0); + if (scoped) assert.equal(cleanup[0].subscription_id, commands[0].subscription_id); + const newAccountSocket = { onReconnect: () => () => {} }; + client.realtime = newAccountSocket; + const count = commands.length; + b.close(); await tick(); + assert.equal(commands.length, count, 'retired cleanup cannot invoke on a new account'); + assert.equal(client.realtime, newAccountSocket, 'retired cleanup cannot reopen its old account'); + } finally { a.close(); b.close(); } + } +}); diff --git a/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt b/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt index 261d0cc605..107f4722bd 100644 --- a/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt +++ b/src/apps/mobile/shared/core-protocol/src/commonMain/kotlin/com/openbitfun/mobile/core/protocol/RemoteCommand.kt @@ -106,4 +106,5 @@ public data class RemoteCommand( @SerialName("before") val before: Long? = null, @SerialName("epoch") val epoch: Long? = null, @SerialName("subscribe") val subscribe: Boolean? = null, + @SerialName("subscription_id") val subscriptionId: String? = null, ) diff --git a/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt b/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt index f2b1bb575b..efde77f150 100644 --- a/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt +++ b/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClient.kt @@ -6,6 +6,8 @@ import kotlinx.coroutines.withContext import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.onCompletion @@ -341,12 +343,15 @@ public class CloudAccountClient internal constructor( * encrypted device RPC. The relay forwards ciphertext only, and nothing is * written on this device: the transcript lives exactly as long as the flow. */ + @OptIn(ExperimentalUuidApi::class) public suspend fun subscribeSession( relayUrl: String, session: CloudAccountSession, targetDeviceId: String, sessionId: String, onError: (Throwable) -> Unit, onCaughtUp: () -> Unit, - ): kotlinx.coroutines.flow.Flow { + ): kotlinx.coroutines.flow.Flow = flow { val socket = connection(relayUrl, session.token) val target = targetDeviceId.trim() + val subscriptionId = Uuid.random().toString() + var scopedSubscription = false val historyKey = target + ":" + sessionId val historyRequests = Channel>(Channel.RENDEZVOUS) historyReaders[historyKey] = historyRequests @@ -356,8 +361,9 @@ public class CloudAccountClient internal constructor( check(realtime.value?.socket === socket) { "Account changed" } val startedAt = TimeSource.Monotonic.markNow() val page = deviceRpc(relayUrl, session, target, - RemoteCommand(cmd = "read_stream", streamId = sessionId, after = after, before = before, epoch = epoch, subscribe = true), + RemoteCommand(cmd = "read_stream", streamId = sessionId, after = after, before = before, epoch = epoch, subscribe = true, subscriptionId = subscriptionId), StreamPageWire.serializer(), RELAY_DEFAULT_TIMEOUT_MS) + scopedSubscription = page.subscriptionId == subscriptionId val elapsedMs = startedAt.elapsedNow().inWholeMilliseconds // The opening page (`after == null`) is the one the user waits for, // and a slow page is worth naming wherever it happens; a page per @@ -368,8 +374,8 @@ public class CloudAccountClient internal constructor( return page } override suspend fun unsubscribe() { - if (realtime.value?.socket !== socket) return - deviceRpc(relayUrl, session, target, RemoteCommand(cmd = "unsubscribe_stream", streamId = sessionId), + if (realtime.value?.socket !== socket || !scopedSubscription) return + deviceRpc(relayUrl, session, target, RemoteCommand(cmd = "unsubscribe_stream", streamId = sessionId, subscriptionId = subscriptionId), CommandStatusResponse.serializer(), RELAY_DEFAULT_TIMEOUT_MS) } } @@ -379,7 +385,7 @@ public class CloudAccountClient internal constructor( // the gap between the two counts is what the receiving device spends. val openedAt = TimeSource.Monotonic.markNow() var recordsSeen = 0 - return hostStream(sessionId, target, hints, merge(socket.connections.drop(1), foregroundResumes), reads, + emitAll(hostStream(sessionId, target, hints, merge(socket.connections.drop(1), foregroundResumes), reads, olderRequests = historyRequests, onError = { error -> log.warn("host stream read failed stream=${sessionId.take(24)} type=${error::class.simpleName} failure=${(error as? CloudAccountException)?.failure} message=${error.message}") onError(error) @@ -390,7 +396,7 @@ public class CloudAccountClient internal constructor( log.info("host stream ended stream=${sessionId.take(24)} events=$recordsSeen cause=${cause?.let { it::class.simpleName } ?: "none"}") if (historyReaders[historyKey] === historyRequests) historyReaders.remove(historyKey) historyRequests.close() - } + }) } /** diff --git a/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/HostStream.kt b/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/HostStream.kt index 6df6c087f7..c2043325b4 100644 --- a/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/HostStream.kt +++ b/src/apps/mobile/shared/core-transport/src/commonMain/kotlin/com/openbitfun/mobile/core/transport/HostStream.kt @@ -4,6 +4,7 @@ import com.openbitfun.mobile.core.protocol.CommandStatus import com.openbitfun.mobile.core.protocol.isError import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.currentCoroutineContext @@ -87,6 +88,7 @@ internal data class StreamPageWire( val cursor: Long = -1, @SerialName("oldest_seq") val oldestSeq: Long = -1, val truncated: Boolean = false, + @SerialName("subscription_id") val subscriptionId: String? = null, ) : CommandStatus /** A decrypted `host-stream-changed` device event. */ @@ -314,6 +316,14 @@ internal fun hostStream( // Requests the lane took off [wakes] and has not served yet. One sweep can // hand it several, and every one of them is owed an answer. val waiting = ArrayDeque>() + // Start collection before the opening RPC. SharedFlow does not replay a + // final hint that arrives without a collector while that page is in flight. + launch(start = CoroutineStart.UNDISPATCHED) { + hints.collect { hint -> if (reader.hintIsNew(hint, target)) wakes.trySend(Wake.Dirty(false)) } + } + launch(start = CoroutineStart.UNDISPATCHED) { + reconnects.collect { wakes.trySend(Wake.Dirty(true)) } + } // Set once a page was read with `subscribe`; before that there is nothing // on the host to release. var subscribed = false @@ -336,8 +346,6 @@ internal fun hostStream( awaitConsumption() onCaughtUp() - launch { hints.collect { hint -> if (reader.hintIsNew(hint, target)) wakes.send(Wake.Dirty(false)) } } - launch { reconnects.collect { wakes.send(Wake.Dirty(true)) } } launch { while (currentCoroutineContext().isActive) { delay(keepaliveMs); wakes.send(Wake.Dirty(false)) } } launch { for (request in olderRequests) wakes.send(Wake.Older(request)) } diff --git a/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt b/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt index 4a60251aab..608ec72b3e 100644 --- a/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt +++ b/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/CloudAccountClientTest.kt @@ -30,6 +30,8 @@ import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlin.test.assertNotNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put @@ -368,6 +370,7 @@ class CloudAccountClientTest { */ @Test fun hostStreamRecoversRepeatsOnlyTheReadAndUnsubscribesOnClose() = runTest { + for (supportsScoped in listOf(true, false)) { val commands = mutableListOf() val master = ByteArray(32) val peerSecret = ByteArray(32) { 11 } @@ -387,7 +390,11 @@ class CloudAccountClientTest { "unsubscribe_stream" -> """{"resp":"stream_unsubscribed","stream_id":"session"}""" else -> error("unexpected ${command.cmd}") } - val encrypted = CloudAccountCipher.encrypt(response.encodeToByteArray(), key, nonce) + val answer = if (supportsScoped && command.cmd == "read_stream") { + JsonObject(RelayJson.parseToJsonElement(response).jsonObject + + ("subscription_id" to JsonPrimitive(command.subscriptionId))).toString() + } else response + val encrypted = CloudAccountCipher.encrypt(answer.encodeToByteArray(), key, nonce) RelayJson.encodeToJsonElement(EncryptedPayload.serializer(), EncryptedPayload(Base64.Default.encode(encrypted), Base64.Default.encode(nonce))) } @@ -399,11 +406,58 @@ class CloudAccountClientTest { "desktop-1", "session", {}, {}) .onEach { received += it.getValue("event").jsonPrimitive.content } .first { it.getValue("event").jsonPrimitive.content == STREAM_EVENT_READY } - assertEquals(listOf("read_stream", "read_stream", "unsubscribe_stream"), commands.map { it.cmd }) - assertEquals(RemoteCommand(cmd = "read_stream", streamId = "session", subscribe = true), commands[1]) + assertEquals(if (supportsScoped) listOf("read_stream", "read_stream", "unsubscribe_stream") + else listOf("read_stream", "read_stream"), commands.map { it.cmd }) + assertNotNull(commands.first().subscriptionId) + assertTrue(commands.all { it.subscriptionId == commands.first().subscriptionId }) + assertEquals(RemoteCommand(cmd = "read_stream", streamId = "session", subscribe = true), commands[1].copy(subscriptionId = null)) assertEquals(listOf("session-record", STREAM_EVENT_READY), received) assertEquals("session", commands.last().streamId) assertEquals(1, keyReads, "the peer key is fetched once and reused for every read") + } + } + + @Test + fun collectingTheSameStreamTwiceOwnsIndependentSubscriptions() = runTest { + val master = ByteArray(32) + val peerSecret = ByteArray(32) { 11 } + val key = DeviceIdentity.messageKey(peerSecret, DeviceIdentity.publicKey(master)) + val commands = mutableListOf() + val client = rpcClient(DeviceIdentity.publicKey(peerSecret)) { _, params -> + val envelope = RelayJson.decodeFromJsonElement(EncryptedPayload.serializer(), params) + val plain = CloudAccountCipher.decrypt(Base64.Default.decode(envelope.encryptedData), key, + Base64.Default.decode(envelope.nonce)).decodeToString() + val command = RelayJson.decodeFromString(RemoteCommand.serializer(), plain) + commands += command + val response = if (command.cmd == "read_stream") + """{"resp":"stream_page","stream_id":"session","subscription_id":"${command.subscriptionId}","epoch":1,"events":[],"has_more":false,"cursor":0,"oldest_seq":1,"truncated":false}""" + else """{"resp":"stream_unsubscribed","stream_id":"session"}""" + val nonce = ByteArray(12) { commands.size.toByte() } + val encrypted = CloudAccountCipher.encrypt(response.encodeToByteArray(), key, nonce) + RelayJson.encodeToJsonElement(EncryptedPayload.serializer(), + EncryptedPayload(Base64.Default.encode(encrypted), Base64.Default.encode(nonce))) + } + val stream = client.subscribeSession("http://192.168.1.2:9700", + CloudAccountSession("token-1", "user-1", master), "desktop-1", "session", {}, {}) + val ready = Channel(Channel.UNLIMITED) + val first = launch { stream.collect { if (it["event"]?.jsonPrimitive?.content == STREAM_EVENT_READY) ready.send(Unit) } } + ready.receive() + val second = launch { stream.collect { if (it["event"]?.jsonPrimitive?.content == STREAM_EVENT_READY) ready.send(Unit) } } + try { + ready.receive() + val ids = commands.filter { it.cmd == "read_stream" }.map { it.subscriptionId } + assertEquals(2, ids.size) + assertNotNull(ids[0]) + assertNotNull(ids[1]) + assertTrue(ids[0] != ids[1], "each collector owns its lease and history lane") + first.cancelAndJoin() + assertEquals(ids[0], commands.last().subscriptionId) + assertEquals("unsubscribe_stream", commands.last().cmd) + assertTrue(second.isActive) + } finally { + first.cancelAndJoin() + second.cancelAndJoin() + } } @Test diff --git a/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/HostStreamTest.kt b/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/HostStreamTest.kt index 398932003a..f295d04158 100644 --- a/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/HostStreamTest.kt +++ b/src/apps/mobile/shared/core-transport/src/commonTest/kotlin/com/openbitfun/mobile/core/transport/HostStreamTest.kt @@ -77,6 +77,30 @@ class HostStreamTest { return received to job } + @Test fun finalHintDuringOpeningReadIsNotLost() = runTest { + val host = FakeHost("s1") + host.append("session-record", turnRecord("initial", 1)) + val hints = MutableSharedFlow() + val reads = object : HostStreamReads by host { + override suspend fun read(after: Long?, before: Long?, epoch: Long?): StreamPageWire { + val page = host.read(after, before, epoch) + if (after == null && before == null) { + host.append("session-record", turnRecord("completed", 2)) + hints.emit(StreamHint("desktop-1", "s1", host.epoch, host.cursor)) + } + return page + } + } + val received = mutableListOf() + val job = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + hostStream("s1", "desktop-1", hints, emptyFlow(), reads, Channel(), { throw it }, {}) + .collect { received += it } + } + runCurrent() + assertEquals(listOf("initial", "completed"), emittedTurnIds(received)) + job.cancelAndJoin() + } + @Test fun jsSafeHistoryCursorsDoNotMoveTheForwardCursor() = runTest { val ceiling = 1L shl 52 val host = FakeHost("s1", pageSize = 2) diff --git a/src/crates/assembly/core/src/service/remote_connect/host_stream_command_tests.rs b/src/crates/assembly/core/src/service/remote_connect/host_stream_command_tests.rs index e7318d7f87..cf03cdab83 100644 --- a/src/crates/assembly/core/src/service/remote_connect/host_stream_command_tests.rs +++ b/src/crates/assembly/core/src/service/remote_connect/host_stream_command_tests.rs @@ -86,7 +86,7 @@ async fn catalog_reads_materialize_the_stream_and_later_appends_reach_the_reader .await .expect("handled") { - RemoteResponse::StreamPage { page } => page, + RemoteResponse::StreamPage { page, .. } => page, other => panic!("unexpected response: {other:?}"), }; assert_eq!(page.stream_id, HOST_CATALOG_ID); @@ -125,7 +125,7 @@ async fn catalog_reads_materialize_the_stream_and_later_appends_reach_the_reader .await .expect("handled") { - RemoteResponse::StreamPage { page } => page, + RemoteResponse::StreamPage { page, .. } => page, other => panic!("unexpected response: {other:?}"), }; assert!(next @@ -136,6 +136,7 @@ async fn catalog_reads_materialize_the_stream_and_later_appends_reach_the_reader Some(&hub), "phone", &RemoteCommand::UnsubscribeStream { + subscription_id: None, stream_id: HOST_CATALOG_ID.into(), }, ) @@ -168,3 +169,56 @@ async fn stopping_device_routing_closes_the_hub() { assert!(*closed.borrow_and_update()); assert!(hub.active_stream_ids().is_empty()); } + +#[tokio::test] +async fn scoped_readers_survive_late_cleanup_and_legacy_clients_keep_their_lease() { + let hub = start_host_stream_hub(Arc::new(Recorder(Mutex::new(Vec::new())))); + let command = |id: Option<&str>, cmd: &str| -> RemoteCommand { + let mut value = serde_json::json!({"cmd":cmd,"stream_id":HOST_CATALOG_ID,"subscribe":true}); + if let Some(id) = id { + value["subscription_id"] = id.into(); + } + serde_json::from_value(value).unwrap() + }; + for id in [Some("retired"), Some("current"), None] { + let reply = + handle_host_stream_command(Some(&hub), "controller", &command(id, "read_stream")) + .await + .unwrap(); + let wire = serde_json::to_value(&reply).unwrap(); + assert_eq!(wire.get("subscription_id").and_then(|id| id.as_str()), id); + let _: RemoteResponse = serde_json::from_value(wire).unwrap(); + } + // New clients are separate leases on one authenticated controller. Legacy + // cleanup targets only the legacy lease, even after new readers appeared. + for id in [Some("retired"), None, Some("retired")] { + handle_host_stream_command(Some(&hub), "controller", &command(id, "unsubscribe_stream")) + .await + .unwrap(); + assert_eq!(hub.subscriber_count(HOST_CATALOG_ID), 1); + } + handle_host_stream_command( + Some(&hub), + "another-controller", + &command(Some("current"), "unsubscribe_stream"), + ) + .await + .unwrap(); + assert_eq!(hub.subscriber_count(HOST_CATALOG_ID), 1); + handle_host_stream_command( + Some(&hub), + "controller", + &command(Some("current"), "unsubscribe_stream"), + ) + .await + .unwrap(); + assert_eq!(hub.subscriber_count(HOST_CATALOG_ID), 0); + // The pre-upgrade payload still decodes, registers and releases normally. + handle_host_stream_command(Some(&hub), "legacy", &command(None, "read_stream")) + .await + .unwrap(); + handle_host_stream_command(Some(&hub), "legacy", &command(None, "unsubscribe_stream")) + .await + .unwrap(); + assert_eq!(hub.subscriber_count(HOST_CATALOG_ID), 0); +} diff --git a/src/crates/assembly/core/src/service/remote_connect/mod.rs b/src/crates/assembly/core/src/service/remote_connect/mod.rs index 680b9657b9..b1839877ec 100644 --- a/src/crates/assembly/core/src/service/remote_connect/mod.rs +++ b/src/crates/assembly/core/src/service/remote_connect/mod.rs @@ -1303,22 +1303,31 @@ pub async fn handle_host_stream_command( crate::service_agent_runtime::CoreServiceAgentRuntime::load_relay_history_batch(&request.stream_id, before) }).await; return Some(match page { - Ok(page) => RemoteResponse::StreamPage { page }, + Ok(page) => RemoteResponse::StreamPage { + page, + subscription_id: request.subscription_id.clone(), + }, Err(error) => RemoteResponse::Error { message: error.to_string(), }, }); } Some(match hub.read(source_device_id, request) { - Ok(page) => RemoteResponse::StreamPage { page }, + Ok(page) => RemoteResponse::StreamPage { + page, + subscription_id: request.subscription_id.clone(), + }, Err(error) => RemoteResponse::Error { message: error.to_string(), }, }) } - RemoteCommand::UnsubscribeStream { stream_id } => { + RemoteCommand::UnsubscribeStream { + stream_id, + subscription_id, + } => { if let Some(hub) = hub { - hub.unsubscribe(source_device_id, stream_id); + hub.unsubscribe_scoped(source_device_id, stream_id, subscription_id.as_deref()); } Some(RemoteResponse::StreamUnsubscribed { stream_id: stream_id.clone(), diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index c07af44c81..7bcd98f083 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -2842,6 +2842,8 @@ pub enum RemoteCommand { }, UnsubscribeStream { stream_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + subscription_id: Option, }, GetWorkspaceInfo, GetWorkspaceIcon { @@ -3142,6 +3144,8 @@ pub enum RemoteResponse { StreamPage { #[serde(flatten)] page: host_stream::StreamPage, + #[serde(default, skip_serializing_if = "Option::is_none")] + subscription_id: Option, }, StreamUnsubscribed { stream_id: String, diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream.rs index 0c2852c36d..b03e5144dd 100644 --- a/src/crates/services/services-integrations/src/remote_connect/host_stream.rs +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream.rs @@ -73,6 +73,9 @@ pub struct StreamPage { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct StreamReadRequest { pub stream_id: String, + /// Optional per-reader lease. Old hosts ignore it; capable hosts echo it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subscription_id: Option, /// Read events after this sequence (forward catch-up). #[serde(default, skip_serializing_if = "Option::is_none")] pub after: Option, @@ -152,7 +155,7 @@ struct StreamLog { record_index: BTreeMap, bytes: usize, truncated: bool, - subscribers: HashMap, + subscribers: HashMap, Instant>>, last_activity: Instant, turn_snapshots: HashMap, /// Snapshot identities participate in tombstones, but must not suppress a @@ -161,6 +164,30 @@ struct StreamLog { } impl StreamLog { + fn prune_subscriptions(&mut self, now: Instant) { + self.subscribers.retain(|_, leases| { + leases.retain(|_, expires| *expires > now); + !leases.is_empty() + }); + } + + fn subscribe(&mut self, device: &str, subscription_id: Option<&str>) -> Result<()> { + if subscription_id.is_some_and(|id| id.is_empty() || id.len() > 128) { + bail!("Invalid stream subscription identity"); + } + let now = Instant::now(); + self.prune_subscriptions(now); + let leases = self.subscribers.entry(device.to_owned()).or_default(); + let id = subscription_id.map(str::to_owned); + // One device may render a stream in several views. Bound those leases + // independently of the account's device count and expired records. + if !leases.contains_key(&id) && leases.len() >= 64 { + bail!("Too many concurrent readers for this device stream"); + } + leases.insert(id, now + SUBSCRIPTION_LEASE); + Ok(()) + } + fn new() -> Self { Self { history: None, @@ -463,7 +490,7 @@ impl HostStreamHub { let Some(log) = state.streams.get_mut(&stream_id) else { continue; }; - log.subscribers.retain(|_, expires| *expires > now); + log.prune_subscriptions(now); let payload = serde_json::json!({ "stream_id": stream_id, "epoch": log.epoch, @@ -492,7 +519,7 @@ impl HostStreamHub { let mut state = purge_state.lock().unwrap_or_else(|e| e.into_inner()); let now = Instant::now(); state.streams.retain(|_, log| { - log.subscribers.retain(|_, expires| *expires > now); + log.prune_subscriptions(now); log.turn_snapshots.retain(|_, snapshot| { now.duration_since(snapshot.last_activity) < STREAM_GRACE && log.subscribers.contains_key(&snapshot.device) @@ -778,20 +805,33 @@ impl HostStreamHub { .or_insert_with(StreamLog::new); log.last_activity = Instant::now(); if request.subscribe { - log.subscribers.insert( - source_device_id.to_owned(), - Instant::now() + SUBSCRIPTION_LEASE, - ); + log.subscribe(source_device_id, request.subscription_id.as_deref())?; } log.read(&request.stream_id, request) } pub fn unsubscribe(&self, source_device_id: &str, stream_id: &str) { + self.unsubscribe_scoped(source_device_id, stream_id, None); + } + + pub fn unsubscribe_scoped( + &self, + source_device_id: &str, + stream_id: &str, + subscription_id: Option<&str>, + ) { let mut state = self.lock(); if let Some(log) = state.streams.get_mut(stream_id) { - log.subscribers.remove(source_device_id); - log.turn_snapshots - .retain(|_, snapshot| snapshot.device != source_device_id); + if let Some(leases) = log.subscribers.get_mut(source_device_id) { + leases.remove(&subscription_id.map(str::to_owned)); + if leases.is_empty() { + log.subscribers.remove(source_device_id); + } + } + if !log.subscribers.contains_key(source_device_id) { + log.turn_snapshots + .retain(|_, snapshot| snapshot.device != source_device_id); + } log.last_activity = Instant::now(); } } @@ -829,7 +869,7 @@ impl HostStreamHub { .map(|log| { log.subscribers .values() - .filter(|expires| **expires > now) + .filter(|leases| leases.values().any(|expires| *expires > now)) .count() }) .unwrap_or(0) @@ -1044,6 +1084,24 @@ mod tests { }) } + #[test] + fn subscription_lease_ids_are_bounded_and_expired_leases_are_reclaimed() { + let mut log = StreamLog::new(); + for index in 0..64 { + log.subscribe("controller", Some(&format!("reader-{index}"))) + .unwrap(); + } + log.subscribe("controller", Some("reader-0")).unwrap(); + assert!(log.subscribe("controller", Some("overflow")).is_err()); + assert!(log.subscribe("controller", Some("")).is_err()); + assert!(log.subscribe("controller", Some(&"a".repeat(129))).is_err()); + for expires in log.subscribers.get_mut("controller").unwrap().values_mut() { + *expires = Instant::now() - Duration::from_secs(1); + } + log.subscribe("controller", Some("fresh")).unwrap(); + assert_eq!(log.subscribers["controller"].len(), 1); + } + #[tokio::test] async fn paged_history_reads_only_needed_turns_and_preserves_legacy_wire() { let hub = HostStreamHub::start(Arc::new(Recorder(Default::default()))); diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs index b9ea15e258..599792cea9 100644 --- a/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream/turn_history.rs @@ -92,8 +92,7 @@ impl HostStreamHub { } log.last_activity = Instant::now(); if request.subscribe { - log.subscribers - .insert(device.to_owned(), Instant::now() + SUBSCRIPTION_LEASE); + log.subscribe(device, request.subscription_id.as_deref())?; } if request.epoch.is_some_and(|epoch| epoch != log.epoch) { // No stale snapshot content: the normal epoch fence tells the diff --git a/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs b/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs index 1ba3e1e280..bcc8b8bfc1 100644 --- a/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs +++ b/src/crates/services/services-integrations/src/remote_connect/host_stream_subscriber.rs @@ -55,6 +55,8 @@ struct DeviceRpcTransport { account: AccountSession, relay: String, target: String, + subscription_id: String, + scoped_subscription: std::sync::atomic::AtomicBool, } #[async_trait::async_trait] @@ -62,6 +64,7 @@ impl StreamTransport for DeviceRpcTransport { async fn read_stream(&self, request: StreamReadRequest) -> Result { let command = serde_json::json!({ "cmd": "read_stream", + "subscription_id": self.subscription_id, "stream_id": request.stream_id, "after": request.after, "before": request.before, @@ -78,11 +81,26 @@ impl StreamTransport for DeviceRpcTransport { &command.to_string(), ) .await?; - parse_stream_page(&response) + let page = parse_stream_page(&response)?; + let value: serde_json::Value = serde_json::from_str(&response)?; + self.scoped_subscription.store( + value["subscription_id"].as_str() == Some(&self.subscription_id), + std::sync::atomic::Ordering::Release, + ); + Ok(page) } async fn unsubscribe_stream(&self, stream_id: &str) -> Result<()> { - let command = serde_json::json!({"cmd":"unsubscribe_stream","stream_id":stream_id}); + // Old hosts share one lease across all readers on this device. A late + // unscoped unsubscribe could silence the replacement reader, so leave + // that lease to its existing expiry unless scoped cleanup was accepted. + if !self + .scoped_subscription + .load(std::sync::atomic::Ordering::Acquire) + { + return Ok(()); + } + let command = serde_json::json!({"cmd":"unsubscribe_stream","stream_id":stream_id,"subscription_id":self.subscription_id}); AccountClient::new() .device_rpc( &self.relay, @@ -354,10 +372,19 @@ impl Reader { } fn emit_ready(&self) -> Result<()> { + self.emit_ready_kind(false) + } + + fn emit_ready_kind(&self, live: bool) -> Result<()> { + let mut payload = serde_json::json!({"sessionId":self.session_id,"hasMore":self.has_more,"oldestSeq":self.oldest,"cursor":self.cursor,"historyBatches":true}); + if live { + // Controller-local recovery, not the end of an older history page. + payload["live"] = true.into(); + } (self.emit)(SessionEvent { session_id: self.session_id.clone(), event: "relay://session-ready".into(), - payload: serde_json::json!({"sessionId":self.session_id,"hasMore":self.has_more,"oldestSeq":self.oldest,"cursor":self.cursor,"historyBatches":true}), + payload, }) } @@ -496,6 +523,47 @@ impl Reader { } } +struct LiveRecovery { + retry_at: Option, + delay: Duration, +} + +impl Default for LiveRecovery { + fn default() -> Self { + Self { + retry_at: None, + delay: Duration::from_secs(1), + } + } +} + +async fn retry_due(deadline: Option) { + match deadline { + Some(deadline) => tokio::time::sleep_until(deadline).await, + None => std::future::pending().await, + } +} + +impl LiveRecovery { + async fn refresh(&mut self, reader: &mut Reader, error: &(dyn Fn(String) + Send + Sync)) { + let result = reader.refresh().await.and_then(|()| { + if self.retry_at.is_some() { + reader.emit_ready_kind(true) + } else { + Ok(()) + } + }); + match result { + Ok(()) => *self = Self::default(), + Err(failure) => { + self.retry_at = Some(tokio::time::Instant::now() + self.delay); + self.delay = (self.delay * 2).min(Duration::from_secs(30)); + error(describe_stream_error(&failure)); + } + } + } +} + impl HostStreamSubscriber { pub async fn start( account: AccountSession, @@ -510,6 +578,8 @@ impl HostStreamSubscriber { account, relay, target: target.clone(), + subscription_id: uuid::Uuid::new_v4().to_string(), + scoped_subscription: std::sync::atomic::AtomicBool::new(false), }); Self::start_with_transport(transport, hints, target, session_id, emit, error).await } @@ -543,14 +613,15 @@ impl HostStreamSubscriber { .map_err(|error| anyhow!("{}", describe_stream_error(&error)))?; let (older, mut older_requests) = mpsc::channel::>>(1); let worker = tokio::spawn(async move { - let mut retry = 1u64; + let mut recovery = LiveRecovery::default(); let mut keepalive = tokio::time::interval(KEEPALIVE); + keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); keepalive.tick().await; loop { let wake = tokio::select! { hint = hints.recv() => match hint { Ok(Some(hint)) => { - if !reader.hint_is_new(&hint, &target) { + if !reader.hint_is_new(&hint, &target) || recovery.retry_at.is_some() { continue; } Wake::Refresh @@ -559,14 +630,17 @@ impl HostStreamSubscriber { Err(broadcast::error::RecvError::Closed) => return, }, _ = keepalive.tick() => Wake::Refresh, + _ = retry_due(recovery.retry_at) => Wake::Refresh, request = older_requests.recv() => match request { Some(reply) if !reply.is_closed() => Wake::Older(reply), Some(_) => continue, None => return, }, }; - let result = match wake { - Wake::Refresh => reader.refresh().await, + match wake { + Wake::Refresh => { + recovery.refresh(&mut reader, error.as_ref()).await; + } Wake::Older(reply) => { // A large historical Turn may span several RPCs. Its // immutable snapshot lets live catch-up keep running; @@ -580,19 +654,29 @@ impl HostStreamSubscriber { result = &mut page => break result, hint = hints.recv() => { let refresh = match hint { - Ok(Some(hint)) => reader.hint_is_new(&hint, &target), + Ok(Some(hint)) => recovery.retry_at.is_none() && reader.hint_is_new(&hint, &target), Ok(None) | Err(broadcast::error::RecvError::Lagged(_)) => true, Err(broadcast::error::RecvError::Closed) => return, }; if refresh { - if let Err(failure) = reader.refresh().await { - error(describe_stream_error(&failure)); - } + recovery.refresh(&mut reader, error.as_ref()).await; if reader.epoch != history_reader.epoch { break Err(anyhow!("Session history restarted during the older read")); } } } + _ = retry_due(recovery.retry_at) => { + recovery.refresh(&mut reader, error.as_ref()).await; + if reader.epoch != history_reader.epoch { + break Err(anyhow!("Session history restarted during the older read")); + } + } + _ = keepalive.tick() => { + recovery.refresh(&mut reader, error.as_ref()).await; + if reader.epoch != history_reader.epoch { + break Err(anyhow!("Session history restarted during the older read")); + } + } } }; result.and_then(|page| reader.apply_older_page(page)) @@ -613,14 +697,6 @@ impl HostStreamSubscriber { continue; } }; - match result { - Ok(()) => retry = 1, - Err(failure) => { - error(describe_stream_error(&failure)); - tokio::time::sleep(Duration::from_secs(retry)).await; - retry = (retry * 2).min(30); - } - } } }); let unsubscribe = Box::new(move || { @@ -997,6 +1073,16 @@ mod tests { #[tokio::test] async fn older_snapshot_io_does_not_block_live_catch_up_and_never_publishes_half_a_turn() { + live_catch_up_during_older_snapshot(false).await; + } + + #[tokio::test] + async fn failed_live_read_retries_while_older_snapshot_io_is_blocked() { + live_catch_up_during_older_snapshot(true).await; + } + + async fn live_catch_up_during_older_snapshot(fail_once: bool) { + tokio::time::pause(); use super::super::host_stream::HistoryBatch; use std::sync::atomic::{AtomicUsize, Ordering}; struct Transport { @@ -1004,6 +1090,7 @@ mod tests { blocked: tokio::sync::Notify, release: tokio::sync::Notify, reads: AtomicUsize, + failures_left: AtomicUsize, } #[async_trait::async_trait] impl StreamTransport for Transport { @@ -1016,6 +1103,16 @@ mod tests { self.blocked.notify_one(); self.release.notified().await; } + if request.after.is_some() + && self + .failures_left + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| { + left.checked_sub(1) + }) + .is_ok() + { + bail!("temporary lost live reply during history read"); + } self.hub .read_history("controller", &request, |before| { self.reads.fetch_add(1, Ordering::SeqCst); @@ -1049,6 +1146,7 @@ mod tests { blocked: Default::default(), release: Default::default(), reads: AtomicUsize::new(0), + failures_left: AtomicUsize::new(usize::from(fail_once)), }); let events = Arc::new(Mutex::new(Vec::::new())); let live = Arc::new(tokio::sync::Notify::new()); @@ -1089,7 +1187,16 @@ mod tests { .await .unwrap(); assert!(!older.is_finished()); - assert_eq!(events.lock().unwrap().len(), 3); // Live output arrived during blocked history IO. + // The completed record arrives even while the historical read is blocked. + assert_eq!( + events + .lock() + .unwrap() + .iter() + .filter(|event| event.event == "session-record") + .count(), + 2 + ); transport.release.notify_one(); older.await.unwrap().unwrap(); let events = events.lock().unwrap(); @@ -1102,7 +1209,7 @@ mod tests { 202 ); assert_eq!(transport.reads.load(Ordering::SeqCst), 2); // One source read per Turn, not per packet. - assert!(errors.lock().unwrap().is_empty()); + assert_eq!(errors.lock().unwrap().len(), usize::from(fail_once)); } #[tokio::test] @@ -1120,6 +1227,87 @@ mod tests { assert_eq!(ready["cursor"], 0); } + #[tokio::test] + async fn failed_live_read_retries_without_another_hint_and_keeps_its_cursor() { + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Flaky { + inner: Arc, + failures: AtomicUsize, + } + #[async_trait::async_trait] + impl StreamTransport for Flaky { + async fn read_stream(&self, request: StreamReadRequest) -> Result { + if request.after.is_some() + && self + .failures + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| { + left.checked_sub(1) + }) + .is_ok() + { + bail!("temporary lost reply"); + } + self.inner.read_stream(request).await + } + async fn unsubscribe_stream(&self, stream: &str) -> Result<()> { + self.inner.unsubscribe_stream(stream).await + } + } + tokio::time::pause(); + let lab = lab(); + let transport = Arc::new(Flaky { + inner: lab.transport.clone(), + failures: AtomicUsize::new(0), + }); + let events = lab.events.clone(); + let errors = lab.errors.clone(); + let recovered = Arc::new(tokio::sync::Notify::new()); + let done = recovered.clone(); + let _subscriber = HostStreamSubscriber::start_with_transport( + transport.clone(), + lab.hints.subscribe(), + "desktop".into(), + "s".into(), + Arc::new(move |event| { + let ready = event.event == "relay://session-ready" && event.payload["live"] == true; + events.lock().unwrap().push((event.event, event.payload)); + if ready { + done.notify_one(); + } + Ok(()) + }), + Arc::new(move |error| errors.lock().unwrap().push(error)), + ) + .await + .unwrap(); + transport.failures.store(2, Ordering::SeqCst); + lab.hub + .synchronize_records("s".into(), false, || async { + Ok(vec![record("s", "last", "completed")]) + }) + .await + .unwrap(); + // This is the final host change: recovery must not depend on another + // token, another user action or the four-minute keepalive. + tokio::time::timeout(Duration::from_secs(7), recovered.notified()) + .await + .expect("the retry timer must catch up and report recovery"); + assert_eq!(lab.errors.lock().unwrap().len(), 2); + let reads = lab.transport.reads.lock().unwrap(); + assert_eq!(reads.len(), 2); + assert_eq!(reads[1].after, Some(0)); + assert!(reads[1].epoch.is_some()); + let events = lab.events.lock().unwrap(); + assert_eq!( + events + .iter() + .filter(|(name, _)| name == "session-record") + .count(), + 1 + ); + assert_eq!(events.last().unwrap().1["hasMore"], false); + } + #[tokio::test] async fn hints_pull_new_records_without_the_host_pushing_content() { let lab = lab(); diff --git a/src/mobile-web/src/services/RelayHttpClient.ts b/src/mobile-web/src/services/RelayHttpClient.ts index 8b4f87adce..09db511b40 100644 --- a/src/mobile-web/src/services/RelayHttpClient.ts +++ b/src/mobile-web/src/services/RelayHttpClient.ts @@ -238,11 +238,11 @@ export class RelayHttpClient { if (!current()) throw new AccountIdentityChangedError(); return parseStreamPage(await this.sendDeviceRpc(deviceId, { cmd: 'read_stream', ...request }, { retryable: true, timeoutMs: 30_000 })); }, - unsubscribeStream: async (id: string) => { + unsubscribeStream: async (id: string, subscriptionId?: string) => { // Best effort: the host also drops the lease when this device goes // offline or stops renewing. if (this.identity !== identity) return; - await this.sendDeviceRpc(deviceId, { cmd: 'unsubscribe_stream', stream_id: id }, { retryable: true, timeoutMs: 10_000 }); + await this.sendDeviceRpc(deviceId, { cmd: 'unsubscribe_stream', stream_id: id, subscription_id: subscriptionId }, { retryable: true, timeoutMs: 10_000 }); }, }; const signals = { diff --git a/src/mobile-web/tests/host-stream.test.mjs b/src/mobile-web/tests/host-stream.test.mjs index c7917842b7..7180aaf994 100644 --- a/src/mobile-web/tests/host-stream.test.mjs +++ b/src/mobile-web/tests/host-stream.test.mjs @@ -29,7 +29,7 @@ class FakeHost { let events; let hasMore; if (request.after !== undefined) { const rest = this.events.filter(e => e.seq > request.after); events = rest.slice(0, limit); hasMore = rest.length > limit; } else { const before = request.before ?? Number.MAX_SAFE_INTEGER; const rest = this.events.filter(e => e.seq < before); events = rest.slice(-limit); hasMore = rest.length > limit; } - return { stream_id: request.stream_id, epoch: this.epoch, events, has_more: hasMore, cursor: this.cursor, oldest_seq: this.events[0]?.seq ?? this.cursor + 1, truncated: false }; + return { subscription_id: request.subscription_id, stream_id: request.stream_id, epoch: this.epoch, events, has_more: hasMore, cursor: this.cursor, oldest_seq: this.events[0]?.seq ?? this.cursor + 1, truncated: false }; }, unsubscribeStream: async id => { this.unsubscribed.push(id); }, }; @@ -305,3 +305,49 @@ test('streamed user turns project attachment pixels for transcript and draft res }); assert.equal(withoutImages.images, undefined); }); + + +test('captures the final hint delivered while the opening page is in flight', async () => { + const sig = signals(); const seen = []; const host = new FakeHost([{ id: 'turn/initial' }]); + const transport = host.transport(); const read = transport.readStream; + transport.readStream = async request => { + const page = await read(request); + if (request.after === undefined && request.before === undefined) { + host.append({ id: 'turn/completed' }); + sig.hint({ sourceDeviceId: 'desktop', stream_id: 's1', epoch: host.epoch, cursor: host.cursor }); + } + return page; + }; + const stream = await openHostStream({ transport, signals: sig, target: 'desktop', streamId: 's1', visibility: null, + onEvent: event => seen.push(event.payload.id), onError: error => { throw error; } }); + try { await settle(); assert.deepEqual(seen, ['turn/initial', 'turn/completed']); } + finally { stream.close(); } +}); + +test('does not publish an in-flight old page after closing its reader', async () => { + let release; const gate = new Promise(resolve => { release = resolve; }); + const host = new FakeHost([{ id: 'turn/initial' }]); const f = await open(host, { forwardGate: gate }); + host.append({ id: 'turn/late' }); + f.sig.hint({ sourceDeviceId: 'desktop', stream_id: 's1', epoch: host.epoch, cursor: host.cursor }); + await tick(); f.stream.close(); release(); await settle(); + assert.deepEqual(f.seen.map(event => event.payload.id), ['turn/initial']); +}); + + +test('scoped cleanup targets its own lease and legacy hosts are left to lease expiry', async () => { + for (const supportsScoped of [true, false]) { + const host = new FakeHost([{ id: 'turn/initial' }]); const calls = []; + const transport = host.transport(); const read = transport.readStream; + transport.readStream = async request => { + const page = await read(request); + if (!supportsScoped) delete page.subscription_id; + return page; + }; + transport.unsubscribeStream = async (id, subscriptionId) => { calls.push({ id, subscriptionId }); }; + const one = await openHostStream({ transport, signals: signals(), target: 'desktop', streamId: 's1', visibility: null, onEvent() {}, onError() {} }); + const two = await openHostStream({ transport, signals: signals(), target: 'desktop', streamId: 's1', visibility: null, onEvent() {}, onError() {} }); + const ids = host.reads.map(request => request.subscription_id); + assert.notEqual(ids[0], ids[1]); one.close(); two.close(); await settle(); + assert.deepEqual(calls, supportsScoped ? ids.map(subscriptionId => ({ id: 's1', subscriptionId })) : []); + } +}); diff --git a/src/mobile-web/tests/session-stream-browser.test.mjs b/src/mobile-web/tests/session-stream-browser.test.mjs index 1e872124f3..9e15fb06cd 100644 --- a/src/mobile-web/tests/session-stream-browser.test.mjs +++ b/src/mobile-web/tests/session-stream-browser.test.mjs @@ -13,6 +13,10 @@ test('session content is read on demand from the online host, hints wake the rea try { const context=await browser.createIncognitoBrowserContext(); const relay=new RelayFixture(); + // This case models an upgraded host; the other fixture paths still omit the + // acknowledgement and exercise the legacy lease-expiry behavior. + const readStream=relay.readStream.bind(relay); + relay.readStream=request=>({...readStream(request),subscription_id:request.subscription_id}); // More than one host page (200 events) so history must be walked backwards. for(let seq=1;seq<=205;seq++)relay.appendStreamEvent('browser-session','session-record',record(seq)); const page=await relay.page(context,source.origin); @@ -37,9 +41,13 @@ test('session content is read on demand from the online host, hints wake the rea }); let state=await page.evaluate(()=>window.streamState); assert.equal(state.events.length,200);assert.equal(state.events[0],'turn/6');assert.equal(state.events.at(-1),'turn/205'); - assert.equal(state.caughtUp,1);assert.deepEqual(state.history.at(-1),{hasMore:true,oldestSeq:6,cursor:205,truncated:false}); + assert.ok(state.caughtUp>=1);assert.deepEqual(state.history.at(-1),{hasMore:true,oldestSeq:6,cursor:205,truncated:false}); const opening=relay.streamReads.filter(read=>read.stream_id==='browser-session'); - assert.equal(opening.length,1);assert.equal(opening[0].subscribe,true);assert.equal(opening[0].after,undefined); + assert.ok(opening.length>=1&&opening.length<=2);assert.equal(opening[0].subscribe,true);assert.equal(opening[0].after,undefined); + // The socket may connect during the initial read. Its buffered invalidation + // must resume by cursor, never reread or duplicate the opening content. + for(const read of opening.slice(1)){assert.equal(read.after,205);assert.equal(read.epoch,relay.stream('browser-session').epoch);} + assert.ok(opening[0].subscription_id); // Older history is one explicit backwards page from the host. await page.evaluate(()=>window.stream.loadOlder()); diff --git a/src/shared/relay-transport/HostStream.ts b/src/shared/relay-transport/HostStream.ts index 702a3f8ddb..864eea7ac2 100644 --- a/src/shared/relay-transport/HostStream.ts +++ b/src/shared/relay-transport/HostStream.ts @@ -12,6 +12,7 @@ export const REMOTE_CAPABILITY_HOST_STREAM_V1 = 'host_stream_v1'; export const UNSUPPORTED_HOST_MESSAGE = 'The controlled device runs an older OpenBitFun version that does not support on-demand session streaming. Update OpenBitFun on that device to continue.'; /** Hosts keep hint subscriptions alive for 10 minutes; renew well before. */ const KEEPALIVE_MS = 4 * 60 * 1000; +let subscriptionSequence = 0; /** How many pages one history request may read while it has not yet shown the * reader anything it did not already have. @@ -28,6 +29,7 @@ const MAX_HISTORY_PAGES_PER_REQUEST = 4; export interface StreamEvent { seq: number; event: string; payload: unknown } export interface StreamPage { + subscription_id?: string; stream_id: string; epoch: number; events: StreamEvent[]; @@ -37,6 +39,7 @@ export interface StreamPage { truncated: boolean; } export interface StreamReadRequest { + subscription_id?: string; stream_id: string; after?: number; before?: number; @@ -63,7 +66,7 @@ export interface SessionStreamHandle { close(): void; wake(): void; loadOlder(): /** Host-facing calls of one reader; production is encrypted device RPC. */ export interface HostStreamTransport { readStream(request: StreamReadRequest): Promise; - unsubscribeStream(streamId: string): Promise; + unsubscribeStream(streamId: string, subscriptionId?: string): Promise; } /** Wake sources: decrypted hints and connection recoveries. */ export interface HostStreamSignals { @@ -123,12 +126,21 @@ export function parseStreamPage(value: unknown): StreamPage { } } return { + subscription_id: typeof page.subscription_id === 'string' ? page.subscription_id : undefined, stream_id: page.stream_id, epoch: page.epoch!, events: page.events as StreamEvent[], has_more: page.has_more!, cursor: page.cursor!, oldest_seq: page.oldest_seq!, truncated: page.truncated === true, }; } class Reader { + private readonly subscriptionId = globalThis.crypto?.randomUUID?.() + ?? `reader-${Date.now().toString(36)}-${++subscriptionSequence}-${Math.random().toString(36).slice(2)}`; + private scopedSubscription = false; + close(): void { + // Legacy hosts have one lease per controller/stream. Let it expire instead + // of allowing delayed cleanup to unsubscribe a replacement reader. + if (this.scopedSubscription) void this.options.transport.unsubscribeStream(this.options.streamId, this.subscriptionId).catch(() => {}); + } epoch = 0; cursor = 0; oldest = 1; @@ -136,10 +148,12 @@ class Reader { truncated = false; /** Turns already emitted to the caller, i.e. already part of the transcript. */ private readonly emittedTurns = new Set(); - constructor(private readonly options: HostStreamOptions) {} + constructor(private readonly options: HostStreamOptions, private readonly isActive: () => boolean) {} private async read(request: Omit): Promise { - const page = await this.options.transport.readStream({ stream_id: this.options.streamId, subscribe: true, ...request }); + const page = await this.options.transport.readStream({ stream_id: this.options.streamId, subscribe: true, ...request, subscription_id: this.subscriptionId }); + if (!this.isActive()) throw new Error('Session stream closed'); + this.scopedSubscription = page.subscription_id === this.subscriptionId; if (page.stream_id !== this.options.streamId) throw new Error('Stream page identity mismatch'); return page; } @@ -221,10 +235,9 @@ class Reader { /** Open one host stream. The first page is awaited so an offline or older * host fails the call instead of retrying silently in the background. */ export async function openHostStream(options: HostStreamOptions): Promise { - const reader = new Reader(options); let active = true; - try { await reader.resync(); } catch (error) { throw new Error(describeHostStreamError(error)); } - options.onCaughtUp?.(); + let initialized = false; + const reader = new Reader(options, () => active); // One reader in flight and one dirty successor (Happy InvalidateSync); // older-page requests share the same lane so pages never interleave. @@ -246,7 +259,7 @@ export async function openHostStream(options: HostStreamOptions): Promise { - if (!active || running || retry) return; + if (!active || !initialized || running || retry) return; running = drain().then(() => { retryDelay = 1000; }).catch(error => { if (!active) return; dirty = true; @@ -268,16 +281,28 @@ export async function openHostStream(options: HostStreamOptions): Promise { if (visibility?.visibilityState === 'visible') resumed(); }; visibility?.addEventListener('visibilitychange', onVisible); + const close = () => { + if (!active) return; + active = false; + stopHints(); stopReconnect(); clearInterval(keepalive); + visibility?.removeEventListener('visibilitychange', onVisible); + if (retry) clearTimeout(retry); + for (const older of olderRequests.splice(0)) older.reject(new Error('Session stream closed')); + reader.close(); + }; + // Subscribe before source IO: the host can publish the final update while + // its opening page is still in flight. Keep that wake dirty until resync ends. + try { + await reader.resync(); + initialized = true; + options.onCaughtUp?.(); + if (dirty) wake(); + } catch (error) { + close(); + throw new Error(describeHostStreamError(error)); + } return { - close() { - if (!active) return; - active = false; - stopHints(); stopReconnect(); clearInterval(keepalive); - visibility?.removeEventListener('visibilitychange', onVisible); - if (retry) clearTimeout(retry); - for (const older of olderRequests.splice(0)) older.reject(new Error('Session stream closed')); - void options.transport.unsubscribeStream(options.streamId).catch(() => {}); - }, + close, wake: invalidate, loadOlder() { if (!active) return Promise.resolve(); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts index 5e993ccf87..668cfa49e6 100644 --- a/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts @@ -109,6 +109,101 @@ describe('RelaySessionHistory', () => { expect(fixture.gap).toBeNull(); }); + it('continues the same live subscription after a recoverable sync error', async () => { + fixture.subscribe.mockImplementation(async () => { + fixture.ready?.({ sessionId: 'session', hasMore: true, oldestSeq: 50, cursor: 150, historyBatches: true }); + return 'subscription'; + }); + const apply = vi.fn(() => true); + const error = vi.fn(); + const ready = vi.fn(); + const history = new RelaySessionHistory('session', apply, ready, error); + await history.open(); + fixture.error?.({ sessionId: 'session', targetDeviceId: 'host', message: 'Lost reply', retrying: true }); + fixture.record?.({ sessionId: 'session', id: 'turn/last', turn: { status: 'completed' } }); + fixture.ready?.({ sessionId: 'session', hasMore: true, oldestSeq: 50, cursor: 151, historyBatches: true, live: true }); + expect(apply).toHaveBeenCalledOnce(); + expect(error).toHaveBeenCalledWith(expect.any(Error), { retrying: true }); + expect(ready).toHaveBeenCalledTimes(2); + expect(fixture.subscribe).toHaveBeenCalledOnce(); + expect(fixture.unsubscribe).not.toHaveBeenCalled(); + history.close(); + }); + + it('ignores events from a retired subscription including events before the new open resolves', async () => { + fixture.subscribe.mockImplementation(async () => { + fixture.error?.({ sessionId: 'session', targetDeviceId: 'host', subscriptionId: 'retired', message: 'Old read failed' }); + fixture.record?.({ sessionId: 'session', subscriptionId: 'retired', id: 'old' }); + fixture.record?.({ sessionId: 'session', subscriptionId: 'current', id: 'new' }); + fixture.ready?.({ sessionId: 'session', subscriptionId: 'current', hasMore: false, oldestSeq: 1, cursor: 5 }); + return 'current'; + }); + const apply = vi.fn(); + const error = vi.fn(); + const history = new RelaySessionHistory('session', apply, vi.fn(), error); + await history.open(); + fixture.error?.({ sessionId: 'session', targetDeviceId: 'host', subscriptionId: 'retired', message: 'Late old error' }); + fixture.gap?.({ sessionId: 'session', subscriptionId: 'retired', resync: true }); + expect(apply).toHaveBeenCalledOnce(); + expect(apply).toHaveBeenCalledWith(expect.objectContaining({ id: 'new' })); + expect(error).not.toHaveBeenCalled(); + history.close(); + }); + + it('keeps live delivery and permits retry after an older-page transport failure', async () => { + fixture.subscribe.mockImplementation(async () => { + fixture.ready?.({ sessionId: 'session', hasMore: true, oldestSeq: 50, cursor: 150, historyBatches: true }); + return 'subscription'; + }); + const apply = vi.fn(() => true); + const history = new RelaySessionHistory('session', apply, vi.fn(), vi.fn()); + await history.open(); + fixture.older.mockImplementationOnce(async () => { + fixture.record?.({ sessionId: 'session', id: 'partial-old', historyReplay: true }); + throw new Error('Lost older reply'); + }); + await expect(history.loadOlder()).rejects.toThrow('Lost older reply'); + fixture.record?.({ sessionId: 'session', id: 'live-terminal' }); + expect(apply).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: 'live-terminal' })); + expect(fixture.unsubscribe).not.toHaveBeenCalled(); + fixture.older.mockImplementationOnce(async () => { + fixture.record?.({ sessionId: 'session', id: 'complete-old', historyReplay: true }); + fixture.ready?.({ sessionId: 'session', hasMore: false, oldestSeq: 1, cursor: 151 }); + }); + await expect(history.loadOlder()).resolves.toBe(true); + expect(apply).toHaveBeenCalledTimes(2); + history.close(); + }); + + it('does not publish an incomplete older page when live catch-up recovers', async () => { + fixture.subscribe.mockImplementation(async () => { + fixture.ready?.({ sessionId: 'session', hasMore: true, oldestSeq: 50, cursor: 150, historyBatches: true }); + return 'subscription'; + }); + const apply = vi.fn(() => true); + const history = new RelaySessionHistory('session', apply, vi.fn(), vi.fn()); + await history.open(); + let release!: () => void; + fixture.older.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); + const older = history.loadOlder(); + await Promise.resolve(); + fixture.record?.({ sessionId: 'session', id: 'old-fragment', historyReplay: true }); + fixture.error?.({ sessionId: 'session', targetDeviceId: 'host', message: 'Lost live reply', retrying: true }); + fixture.record?.({ sessionId: 'session', id: 'live-terminal' }); + fixture.ready?.({ sessionId: 'session', hasMore: true, oldestSeq: 50, cursor: 151, live: true }); + expect(apply).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: 'live-terminal' })); + let settled = false; + void older.then(() => { settled = true; }); + release(); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + fixture.ready?.({ sessionId: 'session', hasMore: false, oldestSeq: 1, cursor: 151 }); + await older; + expect(apply).toHaveBeenCalledTimes(2); + history.close(); + }); + it('surfaces replay failures instead of leaving the first page loading forever', async () => { fixture.subscribe.mockImplementation(async () => { fixture.error?.({ sessionId: 'session', targetDeviceId: 'host', message: 'Unreadable session' }); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts index 6f4ea1b4b3..b13abbf702 100644 --- a/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts @@ -110,6 +110,9 @@ export interface RelayHistoryReady { oldestSeq: number; cursor: number; historyBatches?: boolean; + /** Live catch-up recovered; this does not complete a historical page. */ + live?: boolean; + subscriptionId?: string; } /** One session subscription, shared by opening history and receiving live records. */ @@ -117,6 +120,7 @@ export class RelaySessionHistory { private readonly scope = getActiveSurfaceScope(); private readonly listeners: Array<() => void> = []; private subscriptionId: string | null = null; + private pendingOwnedEvents: WarmSessionStream['events'] = []; private closed = false; private failed = false; private ready: RelayHistoryReady | null = null; @@ -156,7 +160,7 @@ export class RelaySessionHistory { readonly sessionId: string, onRecord: (record: SessionRecord) => boolean | void, onReady: (ready: RelayHistoryReady) => void, - onError: (error: unknown) => void, + onError: (error: unknown, options?: { retrying: boolean }) => void, onResumed?: () => Promise, private readonly onFlush?: () => void, onResync?: () => void, @@ -171,7 +175,7 @@ export class RelaySessionHistory { // has registered. Unlisten/relisten would lose events during async setup. this.warm = takeWarmStream(this.scope.surfaceId, sessionId); // Register before asking Rust to replay its cache or fetch the first page. - this.listeners.push(remoteConnectAPI.onSessionRecord(this.handlers.record = value => { + this.listeners.push(remoteConnectAPI.onSessionRecord(this.owned('record', value => { if (!this.isCurrent() || this.failed) return; const record = value as SessionRecord; if (record.sessionId !== this.sessionId) return; @@ -184,26 +188,41 @@ export class RelaySessionHistory { if (onRecord(record) === true) this.flush(); else this.scheduleFlush(); } catch (error) { this.fail(error); } - })); + }))); // A restarted host stream replays its latest page under fresh revisions and // sends no tombstones for what it dropped (a rollback, undo, or history // rewrite). Records already received are rendered first; the replay that // follows, up to its ready event, is then the whole truth. - this.listeners.push(remoteConnectAPI.onSessionGap(this.handlers.gap = gap => { + this.listeners.push(remoteConnectAPI.onSessionGap(this.owned('gap', gap => { if (!this.isCurrent() || gap.sessionId !== this.sessionId || gap.resync !== true) return; this.flush(); this.collectingHistory = true; this.historyRecords = []; try { onResync?.(); } catch (error) { this.fail(error); } - })); - this.listeners.push(remoteConnectAPI.onSessionSyncError(this.handlers.syncError = error => { + }))); + this.listeners.push(remoteConnectAPI.onSessionSyncError(this.owned('syncError', error => { if (!this.isCurrent() || error.sessionId !== this.sessionId || error.targetDeviceId !== this.scope.surfaceId) return; // Records received before the failure stay rendered. this.flush(); - this.fail(new Error(error.message)); - })); - this.listeners.push(remoteConnectAPI.onSessionReady(this.handlers.ready = ready => { + if (error.retrying === true) { + onError(new Error(error.message), { retrying: true }); + } else { + this.fail(new Error(error.message)); + } + }))); + this.listeners.push(remoteConnectAPI.onSessionReady(this.owned('ready', ready => { if (!this.isCurrent() || this.failed || ready.sessionId !== this.sessionId) return; + if (ready.live === true) { + // Recovery may finish while an older immutable Turn is still loading. + // Keep its staged records and promise intact until its own ready event. + if (!this.ready || !this.flush()) return; + this.ready = { ...this.ready, ...ready }; + onReady(ready); + if (onResumed) void onResumed().catch(error => { + log.warn('Session interaction mailbox refresh failed', { sessionId: this.sessionId, error }); + }); + return; + } try { for (const record of this.historyRecords) onRecord(record); this.historyRecords = []; @@ -218,11 +237,11 @@ export class RelaySessionHistory { onReady(ready); this.resolveReady(); this.pageApplied?.(); - })); - this.listeners.push(remoteConnectAPI.onSessionInteractionChanged(this.handlers.interaction = event => { + }))); + this.listeners.push(remoteConnectAPI.onSessionInteractionChanged(this.owned('interaction', event => { if (!this.isCurrent() || event.sessionId !== this.sessionId || !onResumed) return; void onResumed().catch(error => log.warn('Session interaction mailbox refresh failed', {sessionId:this.sessionId,error})); - })); + }))); this.warm?.dispose(); // A closed subscription may never have had an open() caller. void this.firstPage.catch(() => {}); @@ -295,6 +314,7 @@ export class RelaySessionHistory { throw new Error('Session subscription is closed'); } this.subscriptionId = id; + for (const event of this.pendingOwnedEvents.splice(0)) this.handlers[event.kind]?.(event.value); await this.waitForFirstPage(); this.scheduleHistoryPrefetch(); } catch (error) { @@ -364,20 +384,43 @@ export class RelaySessionHistory { try { await Promise.all([remoteConnectAPI.loadOlderSession(this.subscriptionId), applied]); } catch (error) { - this.fail(error); - this.close(); + // A failed optional/history read does not end the live subscription. + // Its incomplete batch stays invisible and a later reader may retry it. + this.historyRecords = []; + this.collectingHistory = false; + if (this.failed) this.close(); throw error; } finally { this.pageApplied = null; this.rejectPage = null; } this.scope.assertCurrent('finish loading older relay history'); return true; } + private owned(kind: WarmSessionStream['events'][number]['kind'], handler: (value: any) => void): (value: any) => void { + const receive = (value: any): void => { + if (!this.isCurrent() || value?.sessionId !== this.sessionId + || (value.targetDeviceId && value.targetDeviceId !== this.scope.surfaceId)) return; + // Older controller bridges omit the additive identity. New bridges tag + // even the first page, which can arrive before subscribeSession resolves. + if (typeof value.subscriptionId === 'string') { + if (this.subscriptionId === null) { + this.pendingOwnedEvents.push({ kind, value }); + return; + } + if (value.subscriptionId !== this.subscriptionId) return; + } + handler(value); + }; + this.handlers[kind] = receive; + return receive; + } + close(): void { if (this.closed) return; // After a surface change the store keeps these pending for the next ready. if (this.flushTimer !== null) this.flush(); if (this.closed) return; this.closed = true; + this.pendingOwnedEvents = []; this.historyRecords = []; if (this.historyTimer !== null) clearTimeout(this.historyTimer); this.historyTimer = null; diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index fe491ac25e..f64aac10ac 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -69,6 +69,7 @@ const apiMocks = vi.hoisted(() => ({ relayRecord: null as ((value: any) => void) | null, relayReady: null as ((value: any) => void) | null, relayGap: null as ((value: any) => void) | null, + relaySyncError: null as ((value: any) => void) | null, listSessions: vi.fn(), loadSessionMetadata: vi.fn(), listSessionsPage: vi.fn(), @@ -168,7 +169,7 @@ vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', () => ({ onSessionRecord: (listener: (value: any) => void) => { apiMocks.relayRecord = listener; return () => { apiMocks.relayRecord = null; }; }, onSessionReady: (listener: (value: any) => void) => { apiMocks.relayReady = listener; return () => { apiMocks.relayReady = null; }; }, onSessionGap: (listener: (value: any) => void) => { apiMocks.relayGap = listener; return () => { apiMocks.relayGap = null; }; }, - onSessionSyncError: vi.fn(() => () => {}), + onSessionSyncError: (listener: (value: any) => void) => { apiMocks.relaySyncError = listener; return () => { apiMocks.relaySyncError = null; }; }, subscribeSession: apiMocks.subscribeRelaySession, loadOlderSession: apiMocks.loadOlderRelaySession, unsubscribeSession: vi.fn(async () => {}), @@ -9192,6 +9193,29 @@ describe('FlowChatStore device surfaces', () => { expect(apiMocks.restoreSessionWithTurns).not.toHaveBeenCalled(); }); + it.each([true, false])('recovers terminal state after a lost final read with active session=%s', async active => { + activateSurface(PEER_SURFACE_ID); + seedSession('peer-recovery'); + if (!active) flowChatStore.setState(state => ({ ...state, activeSessionId: null })); + const acceptRuntimeStatus = vi.fn(); + stateMachineManagerMock.getOrCreate.mockReturnValue({ acceptRuntimeStatus }); + const { modelRounds: _rounds, ...stored } = createPersistedTurn(0, 'peer-recovery'); + apiMocks.subscribeRelaySession.mockClear().mockImplementationOnce(async () => { + apiMocks.relayRecord?.({ sessionId: 'peer-recovery', id: 'turn/turn-0', revision: 1, turn: { ...stored, status: 'inprogress' } }); + apiMocks.relayReady?.({ sessionId: 'peer-recovery', hasMore: false, oldestSeq: 1, cursor: 1 }); + return 'recovery-subscription'; + }); + await flowChatStore.loadRelaySessionHistory('peer-recovery'); + expect(acceptRuntimeStatus).toHaveBeenLastCalledWith(expect.objectContaining({ state: 'processing' })); + apiMocks.relaySyncError?.({ sessionId: 'peer-recovery', subscriptionId: 'recovery-subscription', targetDeviceId: PEER_SURFACE_ID, retrying: true, message: 'Reply lost' }); + expect(flowChatStore.getState().sessions.get('peer-recovery')?.historyState).toBe('failed'); + apiMocks.relayRecord?.({ sessionId: 'peer-recovery', subscriptionId: 'recovery-subscription', id: 'turn/turn-0', revision: 2, turn: stored }); + apiMocks.relayReady?.({ sessionId: 'peer-recovery', subscriptionId: 'recovery-subscription', live: true, hasMore: false, oldestSeq: 1, cursor: 2 }); + expect(flowChatStore.getState().sessions.get('peer-recovery')?.historyState).toBe('ready'); + expect(acceptRuntimeStatus).toHaveBeenLastCalledWith(expect.objectContaining({ state: 'idle', turnId: 'turn-0' })); + expect(apiMocks.subscribeRelaySession).toHaveBeenCalledTimes(1); + }); + it('retains mailbox questions across canonical updates and clears them when the owning turn completes', async () => { activateSurface(PEER_SURFACE_ID); seedSession('peer-mailbox'); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 634bc3ee9f..5a4785da4c 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -6471,7 +6471,7 @@ export class FlowChatStore { history = new RelaySessionHistory(sessionId, record => this.applyRelaySessionRecord(record), ready => { - this.finishRelaySessionResync(sessionId); + if (ready.live !== true) this.finishRelaySessionResync(sessionId); this.setState(previous => { const session = previous.sessions.get(sessionId); if (!session) return previous; @@ -6484,7 +6484,12 @@ export class FlowChatStore { return { ...previous, sessions }; }); if (!ready.hasMore) this.refreshRelayTurnCatalog(sessionId); - }, error => { + }, (error, options) => { + if (options?.retrying) { + log.warn('Relay session sync interrupted; retaining subscription for recovery', { sessionId, error }); + this.setSessionHistoryState(sessionId, 'failed'); + return; + } log.error('Relay session history failed', { sessionId, error }); this.setSessionHistoryState(sessionId, 'failed'); // Retrying opens a fresh replay owner; a failed owner must not turn diff --git a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts index dcc6736058..b5a132599e 100644 --- a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts @@ -501,11 +501,11 @@ class RemoteConnectAPIService { return api.listen('session-interaction-changed', callback); } - onSessionReady(callback: (event: { sessionId: string; hasMore: boolean; oldestSeq: number; cursor: number; historyBatches?: boolean }) => void): () => void { + onSessionReady(callback: (event: { sessionId: string; hasMore: boolean; oldestSeq: number; cursor: number; historyBatches?: boolean; live?: boolean; subscriptionId?: string }) => void): () => void { return api.listen('relay://session-ready', callback); } - onSessionSyncError(callback: (event: { sessionId: string; targetDeviceId: string; message: string }) => void): () => void { + onSessionSyncError(callback: (event: { sessionId: string; targetDeviceId: string; message: string; retrying?: boolean; subscriptionId?: string }) => void): () => void { return api.listen('account://session-sync-error', callback); } diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index 5664e6a7a1..fc28062b98 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -216,6 +216,26 @@ notification metadata. Lifecycle and approval events may update controls, but raw token/tool-body events cannot overwrite the canonical content owner. + Native subscription events carry a controller-local `subscriptionId` so a + retired reader cannot fail its replacement. Untagged legacy events remain + accepted. A failed live read retains the cursor and retries with capped + backoff even when no further hint arrives, including during older-page IO. + `retrying: true` errors keep the reader alive; `live: true` ready events + restore availability without completing an unrelated historical page. + These fields do not change the Relay or host wire protocol. Older-page + failures retain the live reader and discard only the incomplete page. + + All stream readers install hint/reconnect listeners before the first read, + retaining invalidations that arrive while the initial page is in flight. + Host stream leases additionally negotiate an optional wire `subscription_id`: + `read_stream` offers a per-reader ID and a supporting host echoes it in the + `stream_page` envelope. Only an acknowledged ID may be sent with + `unsubscribe_stream`. The host removes that exact lease; a legacy unscoped + unsubscribe removes only the legacy lease. Readers connected to older hosts + omit cleanup and let the existing ten-minute lease expire, so delayed cleanup + cannot cancel a replacement. Hints remain coalesced per controller device. + The Relay still forwards opaque encrypted payloads and holds no stream state. + `get_session_interaction_mailbox` returns the Runtime's revisioned pending questions and permissions on attach/reconnect. Apply it with a captured Surface scope and newer-event fence. Answers carry the owning session and