@@ -20,6 +20,7 @@ import kotlinx.serialization.json.JsonObject
2020import kotlinx.serialization.json.JsonPrimitive
2121import org.junit.Assert.assertEquals
2222import org.junit.Assert.assertFalse
23+ import org.junit.Assert.assertNull
2324import org.junit.Assert.assertTrue
2425import org.junit.Test
2526import java.util.UUID
@@ -54,6 +55,7 @@ class ChatControllerOutboxTest {
5455 var acceptedStatusUpdateFailure: Throwable ? = null
5556 var queuedStatusUpdateFailure: Throwable ? = null
5657 var sendingStatusUpdateFailure: Throwable ? = null
58+ var pinSessionKeyFailure: Throwable ? = null
5759 var claimGate: CompletableDeferred <Unit >? = null
5860 var deleteFailure: Throwable ? = null
5961 var deleteOnFailedStatus = false
@@ -159,6 +161,7 @@ class ChatControllerOutboxTest {
159161 id : String ,
160162 sessionKey : String ,
161163 ) {
164+ pinSessionKeyFailure?.let { throw it }
162165 val current = rows[id] ? : return
163166 rows[id] = current.copy(sessionKey = sessionKey)
164167 }
@@ -1922,6 +1925,122 @@ class ChatControllerOutboxTest {
19221925 assertTrue(outbox.rows.values.none { it.status == ChatOutboxStatus .Failed })
19231926 }
19241927
1928+ @Test
1929+ fun flushedSendAckedUnderDifferentRunIdResolvesWithTheLiveRun () =
1930+ runTest {
1931+ val gateway = FakeGateway ()
1932+ val outbox = FakeCommandOutbox ()
1933+ val chat = controller(this , gateway, outbox)
1934+ gateway.sendResponse = { _ -> """ {"runId":"gw-run-9","status":"started"}""" }
1935+ gateway.echoDeliveredSendsInHistory = false
1936+ chat.load(" main" )
1937+ advanceUntilIdle()
1938+
1939+ // Captured offline, delivered by the reconnect flush under a divergent acked run id.
1940+ chat.sendMessageAwaitAcceptance(message = " queued turn" , thinkingLevel = " off" , attachments = emptyList())
1941+ gateway.online = true
1942+ chat.handleGatewayEvent(" health" , null )
1943+ advanceTimeBy(5_000 )
1944+ assertEquals(listOf (" queued turn" ), gateway.sentMessages)
1945+ assertEquals(
1946+ ChatOutboxStatus .Accepted ,
1947+ outbox.rows.values
1948+ .single()
1949+ .status,
1950+ )
1951+
1952+ // The run completes under the acknowledged id and its turn becomes visible in
1953+ // canonical history. The adopted send must resolve with the live run: without the
1954+ // ownership transfer the row-id pending run times out and surfaces a spurious error
1955+ // for a turn that was delivered.
1956+ gateway.echoDeliveredSendsInHistory = true
1957+ chat.handleGatewayEvent(" chat" , chatTerminalPayload(" main" , " gw-run-9" , seq = 1 , state = " final" , assistantText = " done" ))
1958+ advanceTimeBy(130_000 )
1959+ assertEquals(0 , chat.pendingRunCount.value)
1960+ assertTrue(outbox.rows.isEmpty())
1961+ assertNull(chat.errorText.value)
1962+ }
1963+
1964+ @Test
1965+ fun failedSessionPinKeepsTheRowQueuedInsteadOfDispatching () =
1966+ runTest {
1967+ val gateway = FakeGateway ()
1968+ val outbox = FakeCommandOutbox ()
1969+ val chat = controller(this , gateway, outbox)
1970+ outbox.seed(
1971+ ChatOutboxItem (
1972+ id = " alias-row" ,
1973+ sessionKey = " main" ,
1974+ text = " captured pre-hello" ,
1975+ thinkingLevel = " off" ,
1976+ createdAtMs = System .currentTimeMillis(),
1977+ status = ChatOutboxStatus .Queued ,
1978+ retryCount = 0 ,
1979+ lastError = null ,
1980+ ),
1981+ )
1982+ chat.load(" main" )
1983+ chat.applyMainSessionKey(" agent:work:main" )
1984+ advanceUntilIdle()
1985+
1986+ // The durable pin is the only record of the alias resolution; if it cannot persist,
1987+ // dispatching anyway would let a retry after a default change target another session.
1988+ outbox.pinSessionKeyFailure = IllegalStateException (" storage unavailable" )
1989+ gateway.online = true
1990+ chat.handleGatewayEvent(" health" , null )
1991+ advanceUntilIdle()
1992+ assertTrue(gateway.sentMessages.isEmpty())
1993+ assertEquals(ChatOutboxStatus .Queued , outbox.rows.getValue(" alias-row" ).status)
1994+ assertFalse(chat.healthOk.value)
1995+
1996+ // Storage recovers; the next health transition pins and delivers exactly once.
1997+ outbox.pinSessionKeyFailure = null
1998+ chat.handleGatewayEvent(" health" , null )
1999+ advanceUntilIdle()
2000+ assertEquals(listOf (" agent:work:main" ), gateway.sentSessionKeys)
2001+ assertTrue(outbox.rows.values.none { it.sessionKey == " main" })
2002+ }
2003+
2004+ @Test
2005+ fun reconcileParkWriteFailureFailsClosedThenParksAfterRecovery () =
2006+ runTest {
2007+ val gateway = FakeGateway ()
2008+ val outbox = FakeCommandOutbox ()
2009+ val chat = controller(this , gateway, outbox)
2010+ gateway.echoDeliveredSendsInHistory = false
2011+ outbox.seed(
2012+ ChatOutboxItem (
2013+ id = " orphan-row" ,
2014+ sessionKey = " main" ,
2015+ text = " ambiguous send" ,
2016+ thinkingLevel = " off" ,
2017+ createdAtMs = System .currentTimeMillis(),
2018+ status = ChatOutboxStatus .Accepted ,
2019+ retryCount = 0 ,
2020+ lastError = null ,
2021+ ),
2022+ )
2023+ chat.load(" main" )
2024+ advanceUntilIdle()
2025+
2026+ // Two sightings without proof want to park the row, but the write fails: health drops
2027+ // instead of the reconciler claiming a change it never persisted.
2028+ outbox.failedStatusUpdateFailure = IllegalStateException (" storage unavailable" )
2029+ gateway.online = true
2030+ chat.handleGatewayEvent(" health" , null )
2031+ advanceUntilIdle()
2032+ assertEquals(ChatOutboxStatus .Accepted , outbox.rows.getValue(" orphan-row" ).status)
2033+ assertFalse(chat.healthOk.value)
2034+
2035+ // Storage recovers; the next pass parks the orphan for manual review.
2036+ outbox.failedStatusUpdateFailure = null
2037+ chat.handleGatewayEvent(" health" , null )
2038+ advanceUntilIdle()
2039+ val parked = outbox.rows.getValue(" orphan-row" )
2040+ assertEquals(ChatOutboxStatus .Failed , parked.status)
2041+ assertEquals(OUTBOX_DELIVERY_UNCONFIRMED_ERROR , parked.lastError)
2042+ }
2043+
19252044 @Test
19262045 fun staleGatedParkFailureFailsClosedInsteadOfSpinning () =
19272046 runTest {
0 commit comments