Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(apps): queue messages above the composer, to send now or take back
leepokaie20b1b35f972
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex 4dcf7181..907a2378 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -10,6 +10,7 @@ else a generic "Bug fixes and improvements" line. Delete old sections.## 2.39.0### zh-Hant- 第一次設定時,如果帳號裡已有電腦,可以向它申請訪問,或配對一臺新電腦(例如 VPS)。安裝頁也能一鍵複製網站連結,到電腦上下載。+- bot 工作中送出的訊息會排在輸入框上方,可立即送出或收回。- bot 用了不只一種智慧體時,列表會在頭像左下角標出各自的智慧體標誌,可在「設定 › 外觀」關閉。- 修正與電腦的連線中斷時,app 可能閃退的問題。- 語音通話中語音辨識偶爾出錯時,會送出已聽到的內容並繼續聆聽,不再直接結束通話。@@ -23,6 +24,7 @@ else a generic "Bug fixes and improvements" line. Delete old sections.### en-US- First-time setup offers your account's computers or a new one, plus a website link to copy.+- Messages sent while a bot works wait above the message box: send one now, or take it back.- When bots use different agents, the bot list shows each one's logo (off in Settings › Appearance).- Fixed a crash when the connection dropped.- A one-off speech error no longer ends a voice call.diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.ktindex e47198a8..57b8bd2d 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt@@ -112,6 +112,41 @@ class ChatLayoutTest {compose.onNodeWithText("Copy").assertDoesNotExist()}+ @Test fun queuedMessagesWaitOnTheComposerWithSendNowAndRemove() {+ assumeTrue(Build.PRODUCT.startsWith("sdk"))+ val store = previewStore()+ // Working in a room: its own chat's messages still wait (and the working indicator's animation stays out of the test).+ val bot = Bot("queue-preview", "Scout", status = "working", workingChat = "room-preview")+ val now = System.currentTimeMillis()+ fun user(id: String, seq: Long, text: String, status: String) =+ Entry(id, seq, bot.id, rev = seq, kind = "user", turn = seq, createdAt = now + seq, data = buildJsonObject { put("text", text); put("status", status) })+ val first = "Also update the changelog."+ val second = "And run the linter before you finish."+ val state = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot),+ connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),+ historyComplete = setOf(bot.id), hello = buildJsonObject { put("version", "2.38.1") }, entries = listOf(+ user("asked", 1, "Add a weekly totals helper.", "sent"), user("queued-1", 2, first, "queued"), user("queued-2", 3, second, "queued")))+ compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }+ // Each waits once, on the composer, oldest first; the chat shows only what went out.+ compose.onAllNodesWithText(first).assertCountEquals(1)+ compose.onAllNodesWithText(second).assertCountEquals(1)+ val above = compose.onNodeWithText(first).fetchSemanticsNode().boundsInRoot+ val below = compose.onNodeWithText(second).fetchSemanticsNode().boundsInRoot+ val box = compose.onNodeWithContentDescription("Add files").fetchSemanticsNode().boundsInRoot+ assertTrue(above.bottom <= below.top && below.bottom <= box.top)+ compose.onAllNodesWithContentDescription("Send now").assertCountEquals(2)+ compose.onAllNodesWithContentDescription("Remove").assertCountEquals(2)+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()+ File(compose.activity.cacheDir, "queued-messages-preview.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }+ }+ // An older computer can't take them now or back: they only wait.+ compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state.copy(hello = buildJsonObject { put("version", "2.38.0") }), store, {}) } } }+ compose.onAllNodesWithText(first).assertCountEquals(1)+ compose.onAllNodesWithContentDescription("Send now").assertCountEquals(0)+ compose.onAllNodesWithContentDescription("Remove").assertCountEquals(0)+ }+@Test fun theTitleOpensTheBotsDetailsOnDetails() {assumeTrue(Build.PRODUCT.startsWith("sdk"))val store = previewStore()diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.ktindex 15587e56..73b9084f 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt@@ -66,6 +66,8 @@ class AppStore internal constructor(internal var mirrorBots: List<Bot> = emptyList()/** Section moves shown but not answered yet, oldest first. */internal val pendingSectionMoves = mutableListOf<SectionMove>()+ /** Queued messages taken back here, by the `rev` they had; the state shows them removed until a newer one (`withRemovals`). */+ internal val pendingRemovals = mutableMapOf<String, Long>()internal var pluginsRefreshAgain = false/** The host version an undecodable event already made the mirror fetch everything again for. */internal var rewoundFor: String? = null@@ -113,6 +115,7 @@ class AppStore internal constructor(actions.clear(); sends.clear(); downloadLocks.clear()// A cancelled section move never heard back: it would lie over the next mirror for good.pendingSectionMoves.clear(); mirrorBots = emptyList()+ pendingRemovals.clear()pluginsRefreshAgain = falserewoundFor = nulldraftWriter = null; draftBook = null; savedDrafts = emptyMap()@@ -147,7 +150,7 @@ class AppStore internal constructor(// Like iOS, a screen state this app can't read is a host without remote screen.val screen = snapshot.screen?.let { runCatching { ScreenState.decode(it) }.getOrNull() }mirrorBots = snapshot.bots- mutableState.update { current -> current.copy(bots = withMoves(snapshot.bots, pendingSectionMoves), entries = snapshot.entries,+ mutableState.update { current -> current.copy(bots = withMoves(snapshot.bots, pendingSectionMoves), entries = withRemovals(snapshot.entries, pendingRemovals),pending = snapshot.pending, usage = snapshot.usage, screen = screen, mirrorRevision = snapshot.rev, icons = snapshot.icons,selectedBot = current.selectedBot?.takeIf { id -> snapshot.bots.any { it.id == id } }) }if (voiceBinding != null && snapshot.bots.none { it.id == voiceBinding?.botId && !it.deleted }) endVoice("Voice chat ended because its bot was removed.")diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.ktindex c69c3487..5a535fbc 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt@@ -163,6 +163,27 @@ fun AppStore.respond(entry: Entry, option: String?) = action("permission:" + entdelay(2_000)}+/** A queued message goes now: into the running turn when the agent can take it, else as the next turn (the host decides). */+internal fun AppStore.steer(entry: Entry) = command("steer", body("botId" to entry.botId, "entryId" to entry.id), "steer:" + entry.id)++/** A queued message never goes out: gone at once, back if the computer refuses (its error shows). */+internal fun AppStore.unqueue(entry: Entry) {+ fun show(shown: Entry) = mutableState.update { state -> state.copy(entries = state.entries.map { if (it.id == shown.id) shown else it }) }+ pendingRemovals[entry.id] = entry.rev+ show(entry.markedRemoved())+ command("unqueue", body("botId" to entry.botId, "entryId" to entry.id), "unqueue:" + entry.id, onFailure = {+ pendingRemovals.remove(entry.id)+ show(entry)+ })+}++private fun Entry.markedRemoved() = copy(data = JsonObject(data + ("removed" to JsonPrimitive(true))))++/** [entries] as they show while [pending] messages (with the `rev` each had) wait for the computer: its newer copy of one+ * says what became of it (removed, or sent because the agent had taken it first). */+internal fun withRemovals(entries: List<Entry>, pending: Map<String, Long>): List<Entry> =+ if (pending.isEmpty()) entries else entries.map { if (pending[it.id] == it.rev) it.markedRemoved() else it }+/** Carries on with the bot's current conversation instead of the handoff. */internal fun AppStore.keepConversation(entry: Entry) = command("keepConversation", body("entryId" to entry.id), "handoff:" + entry.id)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.ktindex 24c4699b..77f8f433 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt@@ -74,8 +74,9 @@ internal sealed interface ChatItem {data class Exchanges(override val id: String, val group: BotExchangeGroup) : ChatItem}-/** Chat-visible entries plus time separators (gaps over an hour) and author grouping. */-internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<ChatItem> {+/** Chat-visible entries plus time separators (gaps over an hour) and author grouping. While the bot is [busy], queued+ * messages wait above the composer instead ([queuedMessages]); the send each came from doesn't show again either. */+internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>, busy: Boolean = false): List<ChatItem> {val out = mutableListOf<ChatItem>()var last: Long? = nullvar author: String? = null@@ -83,7 +84,7 @@ internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<Cval units = mutableListOf<Pair<Long, Any>>()var run = mutableListOf<BotExchange>()fun flush() { if (run.isNotEmpty()) { units += run.first().createdAt to BotExchangeGroup(run); run = mutableListOf() } }- for (entry in entries) {+ for (entry in if (busy) entries.filterNot(Entry::isQueued) else entries) {val exchange = BotExchange.of(entry)if (exchange == null) { flush(); units += entry.createdAt to entry; continue }if (run.isNotEmpty() && run.last().peerId != exchange.peerId) flush()@@ -192,7 +193,7 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr.contextActions(reactions = reactionPick(entry, store), onClick = { focus.clearFocus() }, preview = { SelectionContainer { UserText(entry.text, quote) } }) {messageMenu(context, entry, reply, null)}) { UserText(entry.text, quote) }- SendStatusLine(entry.status, state.bots.firstOrNull { it.id == entry.botId }?.status == "working")+ SendStatusLine(entry.status)}}@@ -211,10 +212,9 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr}}-@Composable private fun SendStatusLine(status: String?, botWorking: Boolean) {+@Composable private fun SendStatusLine(status: String?) {val text = when (status) {"sending" -> "Sending…"- "queued" -> if (botWorking) "Queued until this response finishes" else "Queued""cancelled" -> "Not sent — stopped""delivering" -> "Delivered to the computer"else -> nulldiff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.ktindex e05e29f3..6aeb669f 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt@@ -117,7 +117,8 @@ import com.kyant.shapes.Capsule// An artifact's viewer has its own box for the same draft; two would overwrite each other.else if (viewing == null) MessageComposer(bot, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null,onInterrupt = if (state.voice?.botId == bot.id && state.voice.state.phase == VoicePhase.Speaking) store::interruptVoice else null,- replyTo = replyTo, cancelReply = { replyId = null })+ replyTo = replyTo, cancelReply = { replyId = null },+ queued = queuedMessages(state.entries.filter { it.botId == bot.id && it.isChat }.hidingCalls(), bot.isWorking))}}) {Transcript(bot, chatState, store, connect, PaddingValues(start = 16.dp, end = 16.dp, top = top + 60.dp,@@ -205,7 +206,8 @@ import com.kyant.shapes.Capsuleval entries = state.entries.filter { it.botId == bot.id && it.isChat }.hidingCalls()// A call's message that failed to send stays here, to be sent again.val pending = state.pending.filter { it.botId == bot.id && (it.call == null || it.status == SendStatus.Failed) }- val items = chatItems(entries, pending)+ // Messages waiting behind the bot's work show above the composer instead.+ val items = chatItems(entries, pending, busy = bot.isWorking)val working = bot.isWorking(bot.id) && state.connection is LinkState.Readyval more = bot.id !in state.historyCompleteval details by ThinkingDetails.enabled.collectAsStateWithLifecycle()diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.ktindex 2457fd45..790db434 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt@@ -82,12 +82,12 @@ private enum class Trailing { Interrupt, Stop, Call, Send }* trailing button morphs between call, send, stop and interrupt. `onInterrupt` cuts the bot off* while it speaks in a voice call. `replyTo` is the message the next send quotes, shown on top. `about`, in an artifact's* viewer: the artifact's title, which the box names in place of the quote (its card) it sends with; `draftKey` is then the- * artifact's draft, apart from the chat's.+ * artifact's draft, apart from the chat's. `queued`: the user's messages waiting behind the bot's work, shown on top ([QueuedMessages]).*/@OptIn(ExperimentalFoundationApi::class)@Composable fun MessageComposer(bot: Bot, state: AppState, store: AppStore, onCall: (() -> Unit)?,onInterrupt: (() -> Unit)? = null, replyTo: ReplyQuote? = null, cancelReply: () -> Unit = {}, about: String? = null,- draftKey: String = bot.id) {+ draftKey: String = bot.id, queued: List<Entry> = emptyList()) {val draft = state.drafts[draftKey]val text = rememberTextFieldState(initialText = draft?.text.orEmpty())val files = draft?.files.orEmpty()@@ -173,6 +173,8 @@ private enum class Trailing { Interrupt, Stop, Call, Send }if (command != null) run(command) else store.sendDraft(draftKey, bot.id, typed, replyTo) { clear(); cancelReply() }}Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ // Over the box, past the + button.+ QueuedMessages(queued, state, store, Modifier.padding(start = 16.dp + FIELD_HEIGHT + 8.dp, end = 16.dp))AnimatedVisibility(commands.isNotEmpty(), enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {CommandList(commands, ::run, Modifier.padding(horizontal = 16.dp))diff --git a/apps/android/app/src/main/kotlin/com/codync/android/QueuedMessages.kt b/apps/android/app/src/main/kotlin/com/codync/android/QueuedMessages.ktnew file mode 100644index 00000000..678c2575--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/QueuedMessages.kt@@ -0,0 +1,73 @@+package com.codync.android++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.animateContentSize+import androidx.compose.animation.expandVertically+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.shrinkVertically+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.codync.android.core.*+import com.codync.android.design.*+import com.kyant.shapes.RoundedRectangle++/** While the bot works (anywhere: a room, a routine), the user's waiting messages show above the composer instead of in+ * the chat (iOS `queue(working:)`), oldest first. A bot that isn't working starts them at once. */+internal fun queuedMessages(chat: List<Entry>, working: Boolean): List<Entry> =+ if (working) chat.filter(Entry::isQueued).sortedBy(Entry::seq) else emptyList()++/** The first host version that takes a queued message now (`steer`) or back (`unqueue`). */+private const val STEER_HOST = "2.38.1"++/** An older host has neither, so its queued messages only show; before its `hello` (offline) the actions stay hidden too. */+internal val AppState.supportsQueueActions: Boolean+ get() = hello?.text("version")?.let { !AppVersion.isBelow(it, STEER_HOST) } == true++/**+ * The user's messages waiting behind the bot's work, as iOS `QueuedMessages`: each one line, sent now into the running+ * turn ([steer]) or taken back ([unqueue]).+ */+@Composable internal fun QueuedMessages(entries: List<Entry>, state: AppState, store: AppStore, modifier: Modifier = Modifier) {+ // The card keeps its last rows while it folds away.+ var shown by remember { mutableStateOf(entries) }+ if (entries.isNotEmpty() && entries != shown) shown = entries+ val actions = state.supportsQueueActions+ AnimatedVisibility(entries.isNotEmpty(), modifier, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),+ exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(18.dp)).background(Palette.surface).animateContentSize(Motion.layoutSize)+ .padding(vertical = 2.dp)) {+ for (entry in shown) key(entry.id) {+ QueuedRow(entry, actions, steering = "steer:" + entry.id in state.busy, steer = { store.steer(entry) }, remove = { store.unqueue(entry) })+ }+ }+ }+}++@Composable private fun QueuedRow(entry: Entry, actions: Boolean, steering: Boolean, steer: () -> Unit, remove: () -> Unit) {+ Row(Modifier.fillMaxWidth().padding(start = 14.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(messagePreview(entry.replyQuote.text), Modifier.weight(1f).padding(vertical = if (actions) 0.dp else 9.dp),+ style = Type.subheadline, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (actions) {+ IconButton("Send now", "arrow.turn.down.right", enabled = !steering, action = steer)+ IconButton("Remove", "trash", enabled = !steering, action = remove)+ }+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/TraceView.kt b/apps/android/app/src/main/kotlin/com/codync/android/TraceView.ktindex 3d24cfcf..b3ce2d4e 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/TraceView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/TraceView.kt@@ -34,7 +34,7 @@ import kotlinx.serialization.json.jsonPrimitive/** "Full conversation": everything the agent did, grouped by turn (iOS `TraceView`). */@Composable internal fun TraceView(bot: Bot, state: AppState) {val all = state.entries.filter { it.botId == bot.id }- val turns = all.groupBy { it.turn }.toSortedMap().toList()+ val turns = traceTurns(all)// The running turn's thoughts start unfolded.val running = runningTurn(all, bot.isWorking(bot.id))val list = rememberLazyListState()@@ -55,9 +55,14 @@ import kotlinx.serialization.json.jsonPrimitive}}-/** The turn running now while the bot works in this chat; a queued message already holds the next turn. */+/** A chat's entries grouped by turn, oldest turn first; one taken back from the queue never had a turn. */+internal fun traceTurns(entries: List<Entry>): List<Pair<Long, List<Entry>>> =+ entries.filterNot(Entry::isRemoved).groupBy { it.turn }.toSortedMap().toList()++/** The turn running now while the bot works in this chat; a queued message already holds the next turn, and so does one+ * taken back from the queue. */internal fun runningTurn(entries: List<Entry>, working: Boolean): Long? =- if (working) entries.filter { it.status != "queued" }.maxOfOrNull { it.turn } else null+ if (working) entries.filter { it.status != "queued" && !it.isRemoved }.maxOfOrNull { it.turn } else null/** What the running turn has done so far, in order: the steps the working indicator unfolds. */internal fun workingSteps(entries: List<Entry>): List<Entry> {diff --git a/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.ktnew file mode 100644index 00000000..be3ff753--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt@@ -0,0 +1,47 @@+package com.codync.android++import com.codync.android.core.Entry+import com.codync.android.core.PendingSend+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import org.junit.Assert.assertEquals+import org.junit.Test++class QueuedMessagesTest {+ private fun user(id: String, seq: Long, status: String = "sent", nonce: String? = null, removed: Boolean = false) =+ Entry(id, seq, "bot", seq, "user", 1, buildJsonObject {+ put("text", id); put("status", status)+ if (nonce != null) put("clientNonce", nonce)+ if (removed) put("removed", true)+ }, createdAt = seq)++ private fun ids(items: List<ChatItem>) = items.filterIsInstance<ChatItem.Message>().map { it.entry.id }++ @Test fun `while the bot works its queued messages wait above the composer, oldest first`() {+ val chat = listOf(user("later", 3, "queued"), user("sent", 1), user("first", 2, "queued"), user("taken back", 4, "cancelled", removed = true))+ assertEquals(listOf("first", "later"), queuedMessages(chat, working = true).map { it.id })+ // A bot that isn't working starts them at once: they stay in the chat meanwhile.+ assertEquals(emptyList<Entry>(), queuedMessages(chat, working = false))+ }++ @Test fun `the chat leaves out what waits above the composer and what was taken back`() {+ val entries = listOf(user("sent", 1), user("waiting", 2, "queued"), user("taken back", 3, "cancelled", removed = true)).filter { it.isChat }+ assertEquals(listOf("sent"), ids(chatItems(entries, emptyList(), busy = true)))+ assertEquals(listOf("sent", "waiting"), ids(chatItems(entries, emptyList(), busy = false)))+ }++ @Test fun `a message taken back shows removed until the computer's newer copy says what became of it`() {+ val waiting = user("waiting", 2, "queued")+ val removed = withRemovals(listOf(waiting), mapOf("waiting" to waiting.rev)).single()+ assertEquals(true, removed.isRemoved)+ // The agent had already taken it: the host's copy, not removed, brings it back.+ val sent = waiting.copy(rev = waiting.rev + 1, data = user("waiting", 2).data)+ assertEquals(listOf(sent), withRemovals(listOf(sent), mapOf("waiting" to waiting.rev)))+ }++ @Test fun `a send that waits on the computer doesn't show again as this phone's`() {+ val entries = listOf(user("waiting", 2, "queued", nonce = "n"))+ val pending = listOf(PendingSend("n", "bot", "waiting", 1))+ assertEquals(emptyList<ChatItem>(), chatItems(entries, pending, busy = true).filterNot { it is ChatItem.Separator })+ }+}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/TraceTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/TraceTest.ktindex 903f4734..e8abdd20 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/TraceTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/TraceTest.kt@@ -20,6 +20,9 @@ class TraceTest {@Test fun `the trace unfolds the running turn, not a queued message holding the next`() {val entries = listOf(entry("u1", 1), entry("t1", 1), entry("q", 2, status = "queued"))assertEquals(1L, runningTurn(entries, working = true))+ val removed = Entry("r", 0, "bot", 0, "user", 3, buildJsonObject { put("status", "cancelled"); put("removed", true) })+ assertEquals("nor one taken back from the queue", 1L, runningTurn(entries + removed, working = true))+ assertEquals("which is no turn of its own", listOf(1L, 2L), traceTurns(entries + removed).map { it.first })assertNull(runningTurn(entries, working = false))}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.ktindex e1829257..bf78cd09 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt@@ -35,9 +35,13 @@ data class Entry(val files: List<SharedFile> get() = data["files"]?.let { WireJson.decodeFromJsonElement<List<SharedFile>>(it) }.orEmpty()/** The artifact a bot published in this message (an artifact card), read leniently: its text stands in for it. */val artifact: ArtifactCard? get() = (data["artifact"] as? JsonObject)?.let { runCatching { WireJson.decodeFromJsonElement<ArtifactCard>(it) }.getOrNull() }+ /** A message of the user's waiting behind the bot's work: the computer hasn't given it to the agent yet. */+ val isQueued: Boolean get() = kind == "user" && status == "queued" && !isRemoved+ /** A queued message the user took back (`unqueue`): it shows nowhere. */+ val isRemoved: Boolean get() = data["removed"]?.jsonPrimitive?.booleanOrNull == true/** Of memory and context, only a fresh conversation gets a line: memory lives in the bot's memory settings, a* summary keeps the same conversation going, and a kept handoff changed nothing. */- val isChat: Boolean get() = kind in listOf("user", "permission") ||+ val isChat: Boolean get() = !isRemoved && kind in listOf("user", "permission") ||kind == "notice" && "memory" !in data && "memoryFile" !in data && "compaction" !in data &&(data["handoff"] as? JsonObject)?.text("status") != "kept" ||kind == "agent" && data["final"]?.jsonPrimitive?.booleanOrNull == truediff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.ktindex bd9348f2..ab471923 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt@@ -97,8 +97,10 @@ data class Bot(/** A group's bots, in member order, from [bots]. */fun memberBots(bots: List<Bot>): List<Bot> = members.mapNotNull { id -> bots.firstOrNull { it.id == id } }+ /** Working anywhere: its own chat, a room or a routine. */+ val isWorking: Boolean get() = status in listOf("working", "needsInput")/** Working right now in this chat (its own, or a group it's in). */- fun isWorking(chat: String): Boolean = status in listOf("working", "needsInput") && (workingChat ?: id) == chat+ fun isWorking(chat: String): Boolean = isWorking && (workingChat ?: id) == chat}object HostClient {diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.ktindex 88ee2f47..4cb1a32f 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt@@ -14,6 +14,10 @@ class ConversationTest {assertTrue(bot.copy(workingChat = "group").isWorking("group"))assertFalse(bot.copy(workingChat = "group").isWorking("b"))assertFalse(bot.copy(status = "idle").isWorking("b"))+ // Anywhere, for the messages waiting in its own chat.+ assertTrue(bot.copy(workingChat = "group").isWorking)+ assertTrue(bot.copy(status = "needsInput").isWorking)+ assertFalse(bot.copy(status = "idle").isWorking)}@Test fun `users and final replies can be quoted, and the quote reads leniently`() {@@ -65,6 +69,20 @@ class ConversationTest {}}+ @Test fun `a queued message waits above the composer and one taken back shows nowhere`() {+ fun user(status: String, removed: Boolean = false) = Entry("u", 1, "b", rev = 1, kind = "user",+ data = buildJsonObject { put("text", "hi"); put("status", status); if (removed) put("removed", true) })+ assertTrue(user("queued").isQueued)+ assertTrue(user("queued").isChat)+ assertFalse(user("sent").isQueued)+ assertFalse(Entry("n", 1, "b", rev = 1, kind = "notice", data = buildJsonObject { put("status", "queued") }).isQueued)+ val removed = user("cancelled", removed = true)+ assertTrue(removed.isRemoved)+ assertFalse(removed.isChat)+ assertFalse(removed.isQueued)+ assertFalse("still queued, but taken back", user("queued", removed = true).isQueued)+ }+@Test fun `malformed known events fail before a checkpoint while unknown events are ignored`() {assertFails<IllegalArgumentException> { MirrorEvent.decode(buildJsonObject { put("type", "entry"); put("entry", buildJsonObject { put("id", "broken") }) }) }assertEquals(MirrorEvent.Ignored, MirrorEvent.decode(buildJsonObject { put("type", "future"); put("rev", 999) }))diff --git a/apps/desktop/e2e/queue.spec.ts b/apps/desktop/e2e/queue.spec.tsnew file mode 100644index 00000000..4684a8c1--- /dev/null+++ b/apps/desktop/e2e/queue.spec.ts@@ -0,0 +1,72 @@+import { test, expect, type Page } from '@playwright/test'+import { readFileSync } from 'node:fs'+import { homedir } from 'node:os'+import { join, resolve } from 'node:path'+import { SANDBOX_PREFIX } from '../src/shared/dev-sandbox.ts'+import { canSteer } from '../src/renderer/views/thread/queued-messages.ts'+import { attach, sandbox } from './sandbox.ts'++// A scripted agent whose turn waits until a steered message joins it (host/tests/fixtures/steer_agent.py).+const agent = resolve(__dirname, '../../../host/tests/fixtures/steer_agent.py')++async function host<T = Record<string, unknown>>(method: string, body: object): Promise<T> {+ const { name, port } = sandbox()+ const token = readFileSync(join(homedir(), SANDBOX_PREFIX + name, 'token'), 'utf8').trim()+ const res = await fetch(`http://127.0.0.1:${port}/api/${method}`, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify(body),+ })+ if (!res.ok) throw new Error(`${method}: ${await res.text()}`)+ return (await res.json()) as T+}++/** Whether the turn answering `text` has started. */+async function started(botId: string, text: string): Promise<boolean> {+ const { entries } = await host<{ entries: { kind: string; data: { text?: string; status?: string } }[] }>('history', { botId })+ return entries.some((e) => e.kind === 'user' && e.data.text === text && e.data.status === 'sent')+}++async function type(page: Page, text: string) {+ await page.locator('.composer textarea').fill(text)+ await page.locator('.composer textarea').press('Enter')+}++test('a message sent while the bot works waits above the composer, then goes out now or is taken back', async () => {+ const { version } = await host<{ version: string }>('hello', {})+ test.skip(!canSteer(version), `the sandbox host (${version}) can't steer yet`)+ const { browser, page } = await attach()+ const name = `Queue e2e ${Date.now()}`+ const { bot } = await host<{ bot: { id: string } }>('createBot', {+ name, backend: 'custom', command: `python3 -X utf8 -u '${agent}' steer 30`, connectors: [], skills: [], notify: false,+ })+ try {+ await page.locator('.roster-row', { hasText: name }).click()+ const transcript = page.locator('.transcript')+ const queued = page.locator('.queued-row')++ await host('send', { botId: bot.id, text: 'first' })+ await expect.poll(() => started(bot.id, 'first')).toBe(true)+ await type(page, 'second')+ await expect(queued.filter({ hasText: 'second' })).toBeVisible()+ await expect(transcript).not.toContainText('second')+ await queued.filter({ hasText: 'second' }).getByRole('button', { name: 'Send now' }).click()+ // It joined the running turn: the chat shows it, and the reply took it in.+ await expect(queued).toHaveCount(0)+ await expect(transcript).toContainText('second')+ await expect(transcript).toContainText('Got: ')++ await host('send', { botId: bot.id, text: 'third' })+ await expect.poll(() => started(bot.id, 'third')).toBe(true)+ await type(page, 'never sent')+ await queued.filter({ hasText: 'never sent' }).getByRole('button', { name: 'Remove' }).click()+ await expect(queued).toHaveCount(0)+ await expect(transcript).not.toContainText('never sent')+ const { entries } = await host<{ entries: { data: { text?: string; removed?: boolean } }[] }>('history', { botId: bot.id })+ expect(entries.find((e) => e.data.text === 'never sent')?.data.removed).toBe(true)+ } finally {+ await host('stop', { botId: bot.id }).catch(() => {})+ await host('deleteBot', { botId: bot.id }).catch(() => {})+ await browser.close()+ }+})diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex af507c7f..f6d1ed4d 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -254,6 +254,21 @@ export class BotStore extends BotSync {})}+ /** Has a queued message handled now (`steer`): the computer's update takes it out of the queue. */+ steer(entry: Entry) {+ this.answer(entry, 'steer', (c) => c.call('steer', { botId: entry.botId, entryId: entry.id }))+ }++ /** Takes back a queued message (`unqueue`): gone at once, back if the computer refuses. */+ unqueue(entry: Entry) {+ const show = (e: Entry) => {+ this.upsert(e)+ this.changed()+ }+ show({ ...entry, data: { ...entry.data, status: 'cancelled', removed: true } })+ this.perform((c) => c.call('unqueue', { botId: entry.botId, entryId: entry.id }), true, () => show(entry))+ }+/** Saves the user's version of a handoff that hasn't been sent; whether it did. */async editHandoff(entry: Entry, text: string) {try {diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsxindex 207d0146..8a28d1b6 100644--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx@@ -1,7 +1,7 @@import { FileDownloadCard } from './FileDownloadCard'import { ArtifactCard } from '../library/ArtifactCard'import { memo, useRef, useState } from 'react'-import { groupBotReactions, isGroup, isReplyable, isWorking, type Bot, type Entry, type ReplyQuote } from '@shared/models'+import { groupBotReactions, isGroup, isReplyable, type Bot, type Entry, type ReplyQuote } from '@shared/models'import { BotAvatar } from '../../components/Avatar'import { Button, IconButton } from '../../components/Controls'import { Icon } from '../../components/Icon'@@ -42,7 +42,7 @@ export const ChatRow = memo(function ChatRow({ entry, groupStart, chat, openTraccase 'user':return (<VStack align="flex-end" gap={4} className={groupStart ? 'chat-row group-start' : 'chat-row'}>- <UserBubble entry={entry} botWorking={!!chat && isWorking(chat)} reply={reply} />+ <UserBubble entry={entry} reply={reply} /><ReactionsRow entry={entry} /></VStack>)@@ -120,7 +120,7 @@ export function TimeSeparator({ date }: { date: number }) {const fullDate = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' })-export function UserBubble({ entry, botWorking, reply }: { entry: Entry; botWorking: boolean; reply?: () => void }) {+export function UserBubble({ entry, reply }: { entry: Entry; reply?: () => void }) {const store = useStore()const [hovering, setHovering] = useState(false)const status = entry.data.status@@ -142,7 +142,7 @@ export function UserBubble({ entry, botWorking, reply }: { entry: Entry; botWork{entry.data.text}</Bubble>) : null}- {status && status !== 'sent' ? <UserStatus entry={entry} botWorking={botWorking} hovering={hovering} /> : null}+ {status && status !== 'sent' ? <UserStatus entry={entry} hovering={hovering} /> : null}{/* Beside the bubble, inside its hover region: showing them never changes the height. */}<MessageActions className="leading" visible={hovering} reactions={reactionPick(store, entry)} reply={reply} copy={copy} /></div>@@ -150,14 +150,12 @@ export function UserBubble({ entry, botWorking, reply }: { entry: Entry; botWork)}-function UserStatus({ entry, botWorking, hovering }: { entry: Entry; botWorking: boolean; hovering: boolean }) {+function UserStatus({ entry, hovering }: { entry: Entry; hovering: boolean }) {const tr = useTr()const store = useStore()switch (entry.data.status) {case 'sending':return <Text size="caption2" tone="tertiary">{tr(`Sending…`)}</Text>- case 'queued':- return <Text size="caption2" tone="tertiary">{botWorking ? tr(`Queued until this response finishes`) : tr(`Queued`)}</Text>case 'failed':return (<HStack as="span" gap={2}>diff --git a/apps/desktop/src/renderer/views/thread/QueuedMessages.tsx b/apps/desktop/src/renderer/views/thread/QueuedMessages.tsxnew file mode 100644index 00000000..3e093647--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/QueuedMessages.tsx@@ -0,0 +1,79 @@+import { useEffect, useState } from 'react'+import { hidingCalls } from '@shared/calls'+import { isWorking, quoteOf, type Entry } from '@shared/models'+import { IconButton } from '../../components/Controls'+import { usePresence } from '../../components/Overlay'+import { HStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { afterExit } from '../../lib/exit-delay'+import { messagePreview } from '../../lib/message-preview'+import { useStore } from '../../store/context'+import { canSteer, waitingMessages } from './queued-messages'+import './queued-messages.css'++const EXIT_MS = 300++/**+ * The user's messages waiting while the bot works, oldest first, in a tray tucked under the composer's top edge: each+ * can go out now (`steer`) or be taken back (`unqueue`). A host older than steering only lists them.+ */+export function QueuedMessages({ botId }: { botId: string }) {+ const store = useStore()+ const bot = store.bots.get(botId)+ const waiting = waitingMessages(hidingCalls(store.allEntries(botId)), !!bot && isWorking(bot))+ const rows = useLeaving(waiting)+ const tray = usePresence(waiting.length > 0, EXIT_MS)+ const actions = canSteer(store.hostVersion?.version)+ if (!tray.mounted) return null+ return (+ <div className={`queued-tray ${tray.shown ? 'shown' : ''}`} inert={waiting.length === 0}>+ <div>+ <div className="queued-list" role="list" aria-label="Queued messages">+ {rows.map(({ entry, leaving }) => (+ <QueuedRow key={entry.id} entry={entry} leaving={leaving} actions={actions} />+ ))}+ </div>+ </div>+ </div>+ )+}++function QueuedRow({ entry, leaving, actions }: { entry: Entry; leaving: boolean; actions: boolean }) {+ const store = useStore()+ const { shown } = usePresence(!leaving, EXIT_MS)+ const answering = store.answering.has(entry.id)+ return (+ <div className={`queued-row ${shown ? 'shown' : ''}`} role="listitem" inert={leaving}>+ <div>+ <HStack gap={2} className="queued-row-body">+ <Text size="callout" tone="secondary" truncate grow>{messagePreview(quoteOf(entry).text)}</Text>+ {actions ? (+ <>+ <IconButton title="Send now" icon="arrow.turn.down.right" size={26} disabled={answering} onClick={() => store.steer(entry)} />+ <IconButton title="Remove" icon="trash" size={26} disabled={answering} onClick={() => store.unqueue(entry)} />+ </>+ ) : null}+ </HStack>+ </div>+ </div>+ )+}++/** `items` plus the ones that just left, kept in their places until their row has folded away. */+function useLeaving(items: Entry[]): { entry: Entry; leaving: boolean }[] {+ const [previous, setPrevious] = useState(items)+ const [leaving, setLeaving] = useState<{ entry: Entry; index: number }[]>([])+ const keys = items.map((e) => e.id)+ // Worked out while rendering, so a row that leaves never unmounts before it folds away.+ if (keys.join('\n') !== previous.map((e) => e.id).join('\n')) {+ const gone = previous.flatMap((entry, index) => (keys.includes(entry.id) ? [] : [{ entry, index }]))+ setPrevious(items)+ setLeaving((list) => [...list.filter((x) => !keys.includes(x.entry.id)), ...gone])+ }+ useEffect(() => (leaving.length ? afterExit(EXIT_MS, () => setLeaving([])) : undefined), [leaving])+ const rows = items.map((entry) => ({ entry, leaving: false }))+ for (const { entry, index } of leaving) {+ if (!keys.includes(entry.id)) rows.splice(Math.min(index, rows.length), 0, { entry, leaving: true })+ }+ return rows+}diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex 7552520d..ee7e05e2 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -1,5 +1,5 @@import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'-import { draftOf, isGroup, isWorkingIn, type Bot, type BotDraft, type Entry } from '@shared/models'+import { draftOf, isGroup, isWorking, isWorkingIn, type Bot, type BotDraft, type Entry } from '@shared/models'import { BotAvatar, GroupAvatar } from '../../components/Avatar'import { Spinner } from '../../components/Controls'import { Icon } from '../../components/Icon'@@ -20,6 +20,8 @@ import { ChatRow, TimeSeparator } from './ChatRows'import { WorkingTransition } from './WorkingTransition'import { RoutineNotice } from './RoutineNotice'import { Composer } from './Composer'+import { QueuedMessages } from './QueuedMessages'+import { outsideQueue } from './queued-messages'import { ChatSidePanel } from './ChatSidePanel'import { DetailsPanel, type DetailsTab } from './DetailsPanel'import { TraceView } from './TraceView'@@ -191,13 +193,16 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })</div>) : artifactId ? null : (// The artifact over the chat has its own box (two would both take the voice shortcut).- <Composer- botId={botId}- reply={replyTo}- cancelReply={cancelReply}- onCall={!calling && bot ? () => setCalling(true) : null}- onInterrupt={callSpeaking ? () => interruptCall.current?.() : null}- />+ <>+ <QueuedMessages botId={botId} />+ <Composer+ botId={botId}+ reply={replyTo}+ cancelReply={cancelReply}+ onCall={!calling && bot ? () => setCalling(true) : null}+ onInterrupt={callSpeaking ? () => interruptCall.current?.() : null}+ />+ </>)}</div>{calling ? (@@ -286,8 +291,10 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRouconst live = !!bot && isWorkingIn(bot, botId) && !store.isOffline// Rebuilt only when this chat changes: the store replaces a chat's list on every change.const entries = store.allEntries(botId)- // What voice calls carried shows in each call's conversation, not in the chat.- const all = useMemo(() => buildChat(hidingCalls(entries)), [entries])+ // What voice calls carried shows in each call's conversation, not in the chat; what waits for the bot, in the queue.+ const working = !!bot && isWorking(bot)+ const chatOf = useCallback((list: Entry[]) => buildChat(outsideQueue(hidingCalls(list), working)), [working])+ const all = useMemo(() => chatOf(entries), [chatOf, entries])const steps = useMemo(() => workingSteps(entries), [entries])// The newest 40 items first; older pages come in near the top.const [firstShown, setFirstShown] = useState<string | null>(null)@@ -327,7 +334,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRouif (at === 0) {const anchor = list[0]?.idawait store.loadOlder(botId)- list = buildChat(hidingCalls(store.allEntries(botId)))+ list = chatOf(store.allEntries(botId))at = anchor ? Math.max(0, list.findIndex((i) => i.id === anchor)) : 0}if (at > 0) setFirstShown(list[Math.max(0, at - PAGE)]!.id)diff --git a/apps/desktop/src/renderer/views/thread/queued-messages.css b/apps/desktop/src/renderer/views/thread/queued-messages.cssnew file mode 100644index 00000000..74c5416d--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/queued-messages.css@@ -0,0 +1,45 @@+/* The user's messages waiting while the bot works: a tray tucked under the composer's top edge. */+.queued-tray {+ /* How far the composer overlaps it: the composer's top padding plus its corner. */+ --queued-tuck: calc(8px + var(--radius-xl));+ display: grid;+ grid-template-rows: 0fr;+ opacity: 0;+ width: 100%;+ max-width: var(--column);+ margin: 0 auto;+ /* The composer's side padding plus the tray's inset. */+ padding: 0 28px;+ transition: grid-template-rows var(--layout), opacity var(--morph), margin-bottom var(--layout);+}+.queued-tray.shown {+ grid-template-rows: 1fr;+ opacity: 1;+ margin-bottom: calc(-1 * var(--queued-tuck));+}+.queued-tray > div {+ min-height: 0;+ overflow: hidden;+}+.queued-list {+ background: var(--surface);+ border-radius: var(--radius-l) var(--radius-l) 0 0;+ padding: 4px 6px calc(var(--queued-tuck) + 2px) 14px;+}+.queued-row {+ display: grid;+ grid-template-rows: 0fr;+ opacity: 0;+ transition: grid-template-rows var(--layout), opacity var(--morph);+}+.queued-row.shown {+ grid-template-rows: 1fr;+ opacity: 1;+}+.queued-row > div {+ min-height: 0;+ overflow: hidden;+}+.queued-row-body {+ min-height: 32px;+}diff --git a/apps/desktop/src/renderer/views/thread/queued-messages.test.ts b/apps/desktop/src/renderer/views/thread/queued-messages.test.tsnew file mode 100644index 00000000..081a56ea--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/queued-messages.test.ts@@ -0,0 +1,32 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { canSteer, outsideQueue, waitingMessages } from './queued-messages.ts'+import { isChat, type Entry, type EntryData } from '../../../shared/models.ts'++const user = (id: string, status: string, data: EntryData = {}): Entry => ({+ id, seq: 0, botId: 'b', rev: 1, kind: 'user', turn: 1, data: { text: id, status, ...data }, createdAt: 0, updatedAt: 0,+})++test('while the bot works, queued messages leave the chat for the queue, oldest first', () => {+ const entries = [user('sent', 'sent'), user('q1', 'queued'), user('q2', 'queued'), user('local', 'sending'), user('failed', 'failed')]+ assert.deepEqual(waitingMessages(entries, true).map((e) => e.id), ['q1', 'q2'])+ assert.deepEqual(outsideQueue(entries, true).map((e) => e.id), ['sent', 'local', 'failed'])+})++test('an idle bot takes its next message at once: the chat keeps it and the queue stays empty', () => {+ const entries = [user('q', 'queued')]+ assert.deepEqual(waitingMessages(entries, false), [])+ assert.deepEqual(outsideQueue(entries, false).map((e) => e.id), ['q'])+})++test('a message taken back is gone from the chat', () => {+ assert.equal(isChat(user('removed', 'cancelled', { removed: true })), false)+ assert.equal(isChat(user('stopped', 'cancelled')), true, 'one Stop dropped still says it wasn’t sent')+})++test('only a host that steers gets the queue’s buttons', () => {+ assert.equal(canSteer(undefined), false)+ assert.equal(canSteer('2.38.0'), false)+ assert.equal(canSteer('2.38.1'), true)+ assert.equal(canSteer('2.40.2'), true)+})diff --git a/apps/desktop/src/renderer/views/thread/queued-messages.ts b/apps/desktop/src/renderer/views/thread/queued-messages.tsnew file mode 100644index 00000000..177b3f36--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/queued-messages.ts@@ -0,0 +1,26 @@+import { isBelow } from '../../../shared/compat.ts'+import type { Entry } from '../../../shared/models.ts'++/** The first host that steers a queued message (`steer`) and takes one back (`unqueue`). */+export const STEER_HOST = '2.38.1'++/** Whether the computer's host can steer and take back queued messages; an older one only queues them. */+export function canSteer(hostVersion: string | undefined): boolean {+ return !!hostVersion && !isBelow(hostVersion, STEER_HOST)+}++/** One of the user's messages queued behind the bot's work. */+const waits = (e: Entry) => e.kind === 'user' && e.data.status === 'queued'++/**+ * The user's messages waiting while the bot works, oldest first: the queue above the composer shows them instead of+ * the chat. An idle bot takes its next message at once, so the chat keeps showing that one (no flicker).+ */+export function waitingMessages(entries: Entry[], botWorking: boolean): Entry[] {+ return botWorking ? entries.filter(waits) : []+}++/** The chat's entries without the ones the queue shows. */+export function outsideQueue(entries: Entry[], botWorking: boolean): Entry[] {+ return botWorking ? entries.filter((e) => !waits(e)) : entries+}diff --git a/apps/desktop/src/renderer/views/thread/trace-turns.test.ts b/apps/desktop/src/renderer/views/thread/trace-turns.test.tsindex b3c4b113..77eb2db3 100644--- a/apps/desktop/src/renderer/views/thread/trace-turns.test.ts+++ b/apps/desktop/src/renderer/views/thread/trace-turns.test.ts@@ -37,6 +37,13 @@ test('the running turn is the newest one, not a queued message waiting for the nassert.equal(runningTurn(entries, false), undefined)})+test('a message taken back from the queue doesn’t move the running turn on', () => {+ const entries = [entry('u1', 1, 'user'), entry('t1', 1, 'thought'), entry('gone', 2, 'user', 'cancelled', { removed: true })]+ assert.equal(runningTurn(entries, true), 1)+ assert.deepEqual(workingSteps(entries).map((e) => e.id), ['t1'])+ assert.deepEqual(traceTurns(entries).map(([turn]) => turn), [1], 'nor shows as a turn of its own')+})+test('the trace follows new steps only while scrolled to the end', () => {assert.equal(scrolledToEnd({ scrollHeight: 1000, scrollTop: 600, clientHeight: 400 }), true)assert.equal(scrolledToEnd({ scrollHeight: 1000, scrollTop: 595, clientHeight: 400 }), true)diff --git a/apps/desktop/src/renderer/views/thread/trace-turns.ts b/apps/desktop/src/renderer/views/thread/trace-turns.tsindex 9565e5cc..dfb80094 100644--- a/apps/desktop/src/renderer/views/thread/trace-turns.ts+++ b/apps/desktop/src/renderer/views/thread/trace-turns.ts@@ -1,16 +1,16 @@import type { Entry } from '../../../shared/models.ts'-/** A bot's entries grouped by turn, oldest turn first, each turn's entries in their order. */+/** A bot's entries grouped by turn, oldest turn first, each turn's entries in their order; one taken back from the queue never had a turn. */export function traceTurns(entries: Entry[]): [number, Entry[]][] {const turns = new Map<number, Entry[]>()- for (const e of entries) turns.set(e.turn, [...(turns.get(e.turn) ?? []), e])+ for (const e of entries) if (!e.data.removed) turns.set(e.turn, [...(turns.get(e.turn) ?? []), e])return [...turns.entries()].sort((a, b) => a[0] - b[0])}-/** The turn running now while the bot works in this chat; a queued message already holds the next turn. */+/** The turn running now while the bot works in this chat; a queued message (or one taken back) holds the next turn. */export function runningTurn(entries: Entry[], working: boolean): number | undefined {if (!working) return undefined- return entries.reduce((t, e) => (e.data.status === 'queued' ? t : Math.max(t, e.turn)), -1)+ return entries.reduce((t, e) => (e.data.status === 'queued' || e.data.removed ? t : Math.max(t, e.turn)), -1)}/** What the running turn has done so far, in order: the steps the working indicator unfolds. */diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex e04ad211..6bc8b260 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -308,6 +308,8 @@ export interface EntryData {final?: boolean/** user: queued | sent | cancelled | failed · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expired */status?: string+ /** user: taken back from the queue before it went out (`unqueue`); the chat no longer shows it. */+ removed?: booleanclientNonce?: stringtitle?: stringtoolKind?: string@@ -362,6 +364,8 @@ export interface Entry {export function isChat(e: Entry): boolean {switch (e.kind) {case 'user':+ // One the user took back from the queue (`unqueue`) is gone.+ return !e.data.removedcase 'permission':return truecase 'notice':diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 32055fc0..753ab2dc 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -342,6 +342,16 @@ public extension HostClient {let _: Empty = try await call("stop", ["botId": botId])}+ /// A queued message, now: into the running turn when the agent can take it, else as the next one (host 2.38.1).+ func steer(botId: String, entryId: String) async throws {+ let _: Empty = try await call("steer", ["botId": botId, "entryId": entryId])+ }++ /// A queued message taken back: it never goes out (host 2.38.1).+ func unqueue(botId: String, entryId: String) async throws {+ let _: Empty = try await call("unqueue", ["botId": botId, "entryId": entryId])+ }+func respondPermission(entryId: String, optionId: String?) async throws {struct Body: Encodable { var entryId: String; var optionId: String? }let _: Empty = try await call("respondPermission", Body(entryId: entryId, optionId: optionId))diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Entry+Queue.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+Queue.swiftnew file mode 100644index 00000000..dfecdee6--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+Queue.swift@@ -0,0 +1,19 @@+import Foundation++public extension Entry {+ /// A message of the user's waiting behind the bot's work: the computer hasn't given it to the agent yet.+ var isQueued: Bool { kind == "user" && data.status == "queued" && data.removed != true }+}++public extension Array where Element == Entry {+ /// While the bot works, the user's waiting messages show above the composer instead of in the chat (sent now+ /// with `steer`, taken back with `unqueue`), oldest first. A bot that isn't working starts them at once.+ func queue(working: Bool) -> [Entry] {+ working ? filter(\.isQueued).sorted { $0.seq < $1.seq } : []+ }++ /// The chat without the messages `queue(working:)` shows above the composer.+ func hidingQueue(working: Bool) -> [Entry] {+ working ? filter { !$0.isQueued } : self+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swiftindex bf1afd4b..a43c3a29 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swift@@ -21,9 +21,16 @@ public extension Entry {return t.isEmpty || t == "(pass)" || t == "pass"}- /// The turn running now while the bot works in this chat; a queued message already holds the next turn.+ /// A chat's entries grouped by turn, oldest turn first (Full conversation); one taken back from the queue never had+ /// a turn.+ static func traceTurns(_ entries: [Entry]) -> [(key: Int64, value: [Entry])] {+ Dictionary(grouping: entries.filter { $0.data.removed != true }, by: \.turn).sorted { $0.key < $1.key }+ }++ /// The turn running now while the bot works in this chat; a queued message already holds the next turn, and so+ /// does one taken back from the queue.static func runningTurn(_ entries: [Entry], working: Bool) -> Int64? {- working ? entries.filter { $0.data.status != "queued" }.map(\.turn).max() : nil+ working ? entries.filter { $0.data.status != "queued" && $0.data.removed != true }.map(\.turn).max() : nil}/// What the running turn has done so far, in order.diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex e1e507df..28d90d2d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -21,6 +21,8 @@ public struct EntryData: Codable, Hashable, Sendable {public var final: Bool?/// user: queued | sent | cancelled | failed · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expiredpublic var status: String?+ /// user: taken back while it waited (`unqueue`): it never went out, and the chat doesn't show it.+ public var removed: Bool?public var clientNonce: String?public var title: String?public var toolKind: String?diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex c0328fb9..2ffec4b7 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -40,7 +40,8 @@ public struct Entry: Codable, Identifiable, Hashable, Sendable {/// conversation going, and a kept handoff changed nothing.public var isChat: Bool {switch kind {- case "user", "permission": true+ case "user": data.removed != true+ case "permission": truecase "notice": data.memory == nil && data.memoryFile == nil && data.compaction == nil && data.handoff?.status != "kept"case "agent": data.final == truedefault: falsediff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex cc4a85fd..58cc6f2a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} hat dieses iPhone genehmigt","This phone already has approval. If access no longer works, request a new approval on the computer.": "Dieses Telefon ist bereits genehmigt. Falls der Zugang nicht mehr funktioniert, fordere auf dem Computer eine neue Genehmigung an.","This replaces this phone's current approval. The computer must be online to show the new code.": "Das ersetzt die aktuelle Genehmigung dieses Telefons. Der Computer muss online sein, um den neuen Code anzuzeigen.",- "Request new approval": "Neue Genehmigung anfordern"+ "Request new approval": "Neue Genehmigung anfordern",+ "Send now": "Jetzt senden",+ "Sending now…": "Wird jetzt gesendet…",+ "No message waiting": "Keine Nachricht wartet",+ "Removed": "Entfernt",+ "queued": "wartet",+ "S sends now": "S sendet jetzt",+ "D removes": "D entfernt",+ "S sends this now": "S sendet diese jetzt",+ "D removes the last": "D entfernt die letzte",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Aktualisiere Codync auf {host}: Jetzt senden und Zurücknehmen brauchen {version} oder neuer."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 1e871ef8..49db6b2b 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} aprobó este iPhone","This phone already has approval. If access no longer works, request a new approval on the computer.": "Este teléfono ya tiene aprobación. Si el acceso deja de funcionar, solicita una nueva aprobación en la computadora.","This replaces this phone's current approval. The computer must be online to show the new code.": "Esto reemplaza la aprobación actual de este teléfono. La computadora debe estar en línea para mostrar el nuevo código.",- "Request new approval": "Solicitar nueva aprobación"+ "Request new approval": "Solicitar nueva aprobación",+ "Send now": "Enviar ahora",+ "Sending now…": "Enviando ahora…",+ "No message waiting": "Ningún mensaje en espera",+ "Removed": "Eliminado",+ "queued": "en cola",+ "S sends now": "S envía ahora",+ "D removes": "D elimina",+ "S sends this now": "S envía este ahora",+ "D removes the last": "D elimina el último",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Actualiza Codync en {host}: enviar ahora y retirar necesitan {version} o una versión más reciente."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 0f672e0a..7528ef85 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} a approuvé cet iPhone","This phone already has approval. If access no longer works, request a new approval on the computer.": "Ce téléphone est déjà approuvé. Si l’accès ne fonctionne plus, demandez une nouvelle approbation sur l’ordinateur.","This replaces this phone's current approval. The computer must be online to show the new code.": "Cela remplace l’approbation actuelle de ce téléphone. L’ordinateur doit être en ligne pour afficher le nouveau code.",- "Request new approval": "Demander une nouvelle approbation"+ "Request new approval": "Demander une nouvelle approbation",+ "Send now": "Envoyer maintenant",+ "Sending now…": "Envoi immédiat…",+ "No message waiting": "Aucun message en attente",+ "Removed": "Retiré",+ "queued": "en attente",+ "S sends now": "S envoie maintenant",+ "D removes": "D retire",+ "S sends this now": "S envoie celui-ci maintenant",+ "D removes the last": "D retire le dernier",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Mettez à jour Codync sur {host} : l’envoi immédiat et le retrait nécessitent {version} ou une version plus récente."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex fe7fac0c..e84d0664 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} がこの iPhone を承認しました","This phone already has approval. If access no longer works, request a new approval on the computer.": "この電話はすでに承認されています。アクセスできなくなった場合は、コンピュータで新しい承認をリクエストしてください。","This replaces this phone's current approval. The computer must be online to show the new code.": "この電話の現在の承認が置き換えられます。新しいコードを表示するには、コンピュータがオンラインである必要があります。",- "Request new approval": "新しい承認をリクエスト"+ "Request new approval": "新しい承認をリクエスト",+ "Send now": "今すぐ送信",+ "Sending now…": "今すぐ送信中…",+ "No message waiting": "待機中のメッセージはありません",+ "Removed": "削除しました",+ "queued": "待機中",+ "S sends now": "S 今すぐ送信",+ "D removes": "D 削除",+ "S sends this now": "S これを今すぐ送信",+ "D removes the last": "D 最後のものを削除",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "{host} の Codync をアップデートしてください。今すぐ送信と取り消しには {version} 以降が必要です。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 3b185883..57c49bf7 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name}이(가) 이 iPhone을 승인했습니다","This phone already has approval. If access no longer works, request a new approval on the computer.": "이 휴대폰은 이미 승인되었습니다. 접근이 더 이상 되지 않으면 컴퓨터에서 새 승인을 요청하세요.","This replaces this phone's current approval. The computer must be online to show the new code.": "이 휴대폰의 현재 승인을 대체합니다. 새 코드를 표시하려면 컴퓨터가 온라인 상태여야 합니다.",- "Request new approval": "새 승인 요청"+ "Request new approval": "새 승인 요청",+ "Send now": "지금 보내기",+ "Sending now…": "지금 보내는 중…",+ "No message waiting": "대기 중인 메시지 없음",+ "Removed": "제거됨",+ "queued": "대기 중",+ "S sends now": "S 지금 보내기",+ "D removes": "D 제거",+ "S sends this now": "S 이것을 지금 보내기",+ "D removes the last": "D 마지막 것 제거",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "{host}에서 Codync를 업데이트하세요. 지금 보내기와 취소를 쓰려면 {version} 이상이 필요합니다."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.jsonindex b2312c85..c0c31418 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} aprovou este iPhone","This phone already has approval. If access no longer works, request a new approval on the computer.": "Este celular já tem aprovação. Se o acesso parar de funcionar, solicite uma nova aprovação no computador.","This replaces this phone's current approval. The computer must be online to show the new code.": "Isso substitui a aprovação atual deste celular. O computador precisa estar online para mostrar o novo código.",- "Request new approval": "Solicitar nova aprovação"+ "Request new approval": "Solicitar nova aprovação",+ "Send now": "Enviar agora",+ "Sending now…": "Enviando agora…",+ "No message waiting": "Nenhuma mensagem esperando",+ "Removed": "Removida",+ "queued": "na fila",+ "S sends now": "S envia agora",+ "D removes": "D remove",+ "S sends this now": "S envia esta agora",+ "D removes the last": "D remove a última",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Atualize o Codync em {host}: enviar agora e retirar precisam da versão {version} ou mais recente."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.jsonindex afde0f4a..5871eca2 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name}: этот iPhone подтверждён","This phone already has approval. If access no longer works, request a new approval on the computer.": "У этого телефона уже есть подтверждение. Если доступ перестал работать, запросите новое подтверждение на компьютере.","This replaces this phone's current approval. The computer must be online to show the new code.": "Это заменит текущее подтверждение этого телефона. Чтобы показать новый код, компьютер должен быть в сети.",- "Request new approval": "Запросить новое подтверждение"+ "Request new approval": "Запросить новое подтверждение",+ "Send now": "Отправить сейчас",+ "Sending now…": "Отправляем сейчас…",+ "No message waiting": "Нет ожидающих сообщений",+ "Removed": "Убрано",+ "queued": "в очереди",+ "S sends now": "S отправляет сейчас",+ "D removes": "D убирает",+ "S sends this now": "S отправляет это сейчас",+ "D removes the last": "D убирает последнее",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "Обновите Codync на {host}: отправке сейчас и отзыву нужна версия {version} или новее."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex e848215f..8f380f96 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} 已同意这台 iPhone","This phone already has approval. If access no longer works, request a new approval on the computer.": "这台手机已获同意。如果访问不再有效,请重新申请,由电脑同意。","This replaces this phone's current approval. The computer must be online to show the new code.": "这会取代这台手机当前的同意。电脑必须在线才能显示新的码。",- "Request new approval": "重新申请同意"+ "Request new approval": "重新申请同意",+ "Send now": "立即发送",+ "Sending now…": "正在立即发送…",+ "No message waiting": "没有等待中的消息",+ "Removed": "已移除",+ "queued": "排队中",+ "S sends now": "S 立即发送",+ "D removes": "D 移除",+ "S sends this now": "S 立即发送这条",+ "D removes the last": "D 移除最后一条",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "请在 {host} 上更新 Codync:立即发送和收回需要 {version} 或更高版本。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 246fa6c1..e0998907 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1797,5 +1797,15 @@"{name} approved this iPhone": "{name} 已同意這臺 iPhone","This phone already has approval. If access no longer works, request a new approval on the computer.": "這臺手機已獲同意。如果訪問不再有效,請重新申請,由電腦同意。","This replaces this phone's current approval. The computer must be online to show the new code.": "這會取代這臺手機目前的同意。電腦必須在線上才能顯示新的碼。",- "Request new approval": "重新申請同意"+ "Request new approval": "重新申請同意",+ "Send now": "立即送出",+ "Sending now…": "正在立即送出…",+ "No message waiting": "沒有等待中的訊息",+ "Removed": "已移除",+ "queued": "排隊中",+ "S sends now": "S 立即送出",+ "D removes": "D 移除",+ "S sends this now": "S 立即送出這則",+ "D removes the last": "D 移除最後一則",+ "Update Codync on {host}: sending now and taking back need {version} or newer.": "請在 {host} 上更新 Codync:立即送出和收回需要 {version} 或更新的版本。"}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swiftindex 594b5a4b..5f2216e4 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift@@ -107,6 +107,22 @@ extension BotStore {}}+ /// Sends a queued message now: into the bot's running turn when its agent can take it, else as its next turn. It+ /// leaves the queue once the computer says so.+ public func steer(_ entry: Entry) {+ answer(entry, "steer") { try await $0.steer(botId: entry.botId, entryId: entry.id) }+ }++ /// Takes back a queued message, which never goes out: gone at once, back if the computer refuses.+ public func unqueue(_ entry: Entry) {+ let mark = { (removed: Bool?) in+ guard let i = self.entries[entry.botId]?.firstIndex(where: { $0.id == entry.id }) else { return }+ Motion.animate { self.entries[entry.botId]?[i].data.removed = removed }+ }+ mark(true)+ Task { await attempt(undo: { mark(nil) }) { try await $0.unqueue(botId: entry.botId, entryId: entry.id) } }+ }+/// A card's button: `entry` shows `choice` as answering (its spinner) while `op` runs.private func answer(_ entry: Entry, _ choice: String, _ op: @escaping @MainActor (HostClient) async throws -> Void) {guard answering[entry.id] == nil else { return }diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex f3ea386e..d8e62dc4 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -234,6 +234,13 @@ public final class BotStore {static let leadChoiceHost = "2.33.0"+ /// From host 2.38.1 a queued message can be sent now (`steer`) or taken back (`unqueue`); an older host has neither.+ public var supportsQueueActions: Bool {+ hostVersion.map { !AppVersion.isBelow($0.version, Self.queueActionsHost) } ?? false+ }++ static let queueActionsHost = "2.38.1"+static let sectionsHost = "2.32.0"/// Display name for a harness id, as the host reports it (falls back to the built-in list).diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftindex fa4b3afc..ff5dabac 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -25,7 +25,7 @@ struct ChatRow: View {switch entry.kind {case "user":VStack(alignment: .trailing, spacing: 4) {- UserBubble(entry: entry, botWorking: chat?.isWorking == true, reply: reply)+ UserBubble(entry: entry, reply: reply)ReactionsRow(entry: entry)}.animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.reactions)@@ -116,7 +116,6 @@ struct QuoteLine: View {struct UserBubble: View {let entry: Entry- let botWorking: Boolvar reply: (() -> Void)?@Environment(BotStore.self) private var model@@ -156,10 +155,6 @@ struct UserBubble: View {switch entry.data.status {case "sending":Text(L10n.tr("Sending…")).font(.caption2).foregroundStyle(Palette.tertiary)- case "queued":- Text(L10n.tr(botWorking ? "Queued until this response finishes" : "Queued"))- .font(.caption2)- .foregroundStyle(Palette.tertiary)case "failed":HStack(spacing: 10) {Text(L10n.tr("Failed to send")).foregroundStyle(Palette.danger)diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swiftindex e10bfb94..0a8de10d 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift@@ -10,6 +10,8 @@ struct Composer: View {let botId: String/// The message the next send quotes, shown above the field until sent or cancelled.@Binding var replyingTo: Entry?+ /// The user's messages waiting behind the bot's work, shown above the box (`QueuedMessages`).+ var queued: [Entry] = []/// Starts a voice call; while the box is empty it takes the send button's place.var onCall: (() -> Void)?/// Interrupts the bot while it is speaking in a voice call.@@ -85,6 +87,13 @@ struct Composer: View {var body: some View {VStack(alignment: .leading, spacing: 6) {+ if !queued.isEmpty {+ // Over the box, past the + button.+ QueuedMessages(entries: queued)+ .padding(.leading, 16 + (canAttach ? fieldHeight + 8 : 0))+ .padding(.trailing, 16)+ .transition(.move(edge: .bottom).combined(with: .opacity))+ }if !commands.isEmpty {CommandList(commands: commands, pick: run).padding(.horizontal, 16)@@ -109,6 +118,7 @@ struct Composer: View {}.animation(Motion.layout, value: suggestions.map(\.id)).animation(Motion.layout, value: commands.map(\.id))+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: queued.isEmpty)}private var fieldPadding: CGFloat { 10 }diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/QueuedMessages.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/QueuedMessages.swiftnew file mode 100644index 00000000..910bc394--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/QueuedMessages.swift@@ -0,0 +1,41 @@+import CodyncKit+import SwiftUI++/// The user's messages waiting behind the bot's work, above the composer: each one line, sent now into the running+/// turn (`steer`) or taken back. An older computer has neither action, so the rows only show.+struct QueuedMessages: View {+ let entries: [Entry]+ @Environment(BotStore.self) private var model+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ VStack(spacing: 0) {+ ForEach(entries) { entry in+ row(entry).transition(.move(edge: .bottom).combined(with: .opacity))+ }+ }+ .padding(.vertical, 2)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: entries.map(\.id))+ }++ private func row(_ entry: Entry) -> some View {+ HStack(spacing: 2) {+ Text(MessagePreview.text(entry.replyQuote.text))+ .font(.subheadline)+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.vertical, model.supportsQueueActions ? 0 : 9)+ if model.supportsQueueActions {+ Group {+ IconButton("Send now", systemImage: "arrow.turn.down.right") { model.steer(entry) }+ IconButton("Remove", systemImage: "trash") { model.unqueue(entry) }+ }+ .disabled(model.answering[entry.id] != nil)+ }+ }+ .padding(.leading, 14)+ .padding(.trailing, 4)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex 25d23d26..d496c053 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -43,6 +43,7 @@ public struct ThreadView: View {.transition(.opacity)} else {Composer(botId: botId, replyingTo: $replyingTo,+ queued: model.chat(botId).hidingCalls().queue(working: busy),onCall: !calling && bot != nil ? { calling = true } : nil,onInterrupt: callSpeaking ? interruptCall : nil)}@@ -321,13 +322,16 @@ extension ThreadView {}private var working: Bool { bot?.isWorking(in: botId) == true && !model.isOffline }+ /// The bot works anywhere (a room, a routine): the user's messages here wait above the composer.+ private var busy: Bool { bot?.isWorking == true }/// iPhone's messages: all this device has, earlier ones from the computer as the reader/// scrolls up; the chat follows the newest message until they scroll away, and a reply is/// revealed steadily as it's written.var transcript: some View {// What voice calls carried shows in each call's conversation, not in the chat.- let items = ChatItem.build(model.chat(botId).hidingCalls())+ // Messages waiting behind the bot's work show above the composer instead.+ let items = ChatItem.build(model.chat(botId).hidingCalls().hidingQueue(working: busy))var rows: [ConversationRow] = []if moreOnComputer {rows.append(ConversationRow("earlier") {diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swiftindex a51cfe21..f583184d 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swift@@ -11,8 +11,7 @@ public struct TraceView: View {public var body: some View {let all = model.chat(botId)- let turns = Dictionary(grouping: all, by: \.turn)- .sorted { $0.key < $1.key }+ let turns = Entry.traceTurns(all)// The running turn's thoughts start unfolded.let running = Entry.runningTurn(all, working: model.bots[botId]?.isWorking(in: botId) == true)VStack(spacing: 0) {diff --git a/apps/ios/Kit/Tests/CodyncKitTests/QueuedMessagesTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/QueuedMessagesTests.swiftnew file mode 100644index 00000000..b5268a75--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/QueuedMessagesTests.swift@@ -0,0 +1,33 @@+import Foundation+import Testing+@testable import CodyncKit++private func entry(_ id: String, seq: Int64, turn: Int64, _ json: String) throws -> Entry {+ let data = try JSONDecoder().decode(EntryData.self, from: Data(json.utf8))+ return Entry(id: id, seq: seq, botId: "b", rev: 1, kind: "user", turn: turn, data: data, createdAt: seq, updatedAt: seq)+}++@Test func whileTheBotWorksItsWaitingMessagesLeaveTheChatForTheQueue() throws {+ let entries = [+ try entry("asked", seq: 1, turn: 1, #"{"text":"first","status":"sent"}"#),+ try entry("later", seq: 3, turn: 3, #"{"text":"third","status":"queued"}"#),+ try entry("next", seq: 2, turn: 2, #"{"text":"second","status":"queued"}"#),+ try entry("taken", seq: 4, turn: 4, #"{"text":"gone","status":"cancelled","removed":true}"#),+ ]+ #expect(entries.queue(working: true).map(\.id) == ["next", "later"], "oldest first, never a taken-back one")+ #expect(entries.hidingQueue(working: true).map(\.id) == ["asked", "taken"])+ // A bot that isn't working starts a message at once: it stays in the chat.+ #expect(entries.queue(working: false).isEmpty)+ #expect(entries.hidingQueue(working: false).map(\.id) == entries.map(\.id))+}++@Test func aMessageTakenBackShowsNowhereAndHoldsNoTurn() throws {+ let entries = [+ try entry("asked", seq: 1, turn: 1, #"{"text":"first","status":"sent"}"#),+ try entry("taken", seq: 2, turn: 2, #"{"text":"gone","status":"cancelled","removed":true}"#),+ try entry("stopped", seq: 3, turn: 1, #"{"text":"not sent","status":"cancelled"}"#),+ ]+ #expect(entries.map(\.isChat) == [true, false, true])+ #expect(Entry.runningTurn(entries, working: true) == 1)+ #expect(Entry.traceTurns(entries).map(\.key) == [1])+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swiftindex c114c419..976a4200 100644--- a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift@@ -164,6 +164,29 @@ private func rosterBot(_ id: String, pinned: Bool = false, lead: Bool = false, h#expect(store.supportsSections)}+@MainActor @Test func queueActionsNeedAHostThatTakesThem() throws {+ let (store, done) = rosterStore([])+ defer { done() }+ #expect(!store.supportsQueueActions) // The host hasn't answered yet.+ store.hostVersion = HostVersion(version: "2.38.0")+ #expect(!store.supportsQueueActions)+ store.hostVersion = HostVersion(version: "2.38.1")+ #expect(store.supportsQueueActions)+}++@MainActor @Test func aQueuedMessageTakenBackGoesAtOnceAndComesBackWhenRefused() async throws {+ let (store, done) = rosterStore([])+ defer { done() }+ let data = try JSONDecoder().decode(EntryData.self, from: Data(#"{"text":"later","status":"queued"}"#.utf8))+ let entry = Entry(id: "q", seq: 1, botId: "b", rev: 1, kind: "user", turn: 1, data: data, createdAt: 1, updatedAt: 1)+ store.entries["b"] = [entry]+ store.connection = .unauthorized("No access") // Every call fails at once.+ store.unqueue(entry)+ #expect(store.entries["b"]?.first?.isChat == false)+ #expect(await until { store.entries["b"]?.first?.isQueued == true })+ #expect(store.lastError != nil)+}+@MainActor @Test func sectionChangesShowAtOnceAndUndoWhenRefused() async throws {let (store, done) = try rosterStore([rosterBot("a"), rosterBot("b", section: "Work"), rosterBot("c", section: "Home")])defer { done() }diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex 015e7f63..a78b3847 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -9,6 +9,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o## 2.39.0### zh-Hant- 第一次設定時,如果帳號裡已有電腦,可以向它申請訪問,或配對一臺新電腦(例如 VPS)。安裝頁也能一鍵複製網站連結,到電腦上下載。+- bot 工作中送出的訊息會排在輸入框上方:按箭頭立即送給 bot(Claude、Codex 會直接併進正在寫的回覆),按垃圾桶收回。- bot 用了不只一種智慧體時,列表會在頭像左下角標出各自的智慧體標誌,可在「設定 › 外觀」關閉。- 修正語音通話中,bot 唸完回覆、要再聽你說話時 app 可能閃退的問題。- 語音通話的對話紀錄更好讀:最上方顯示是跟哪個 bot、什麼時候、通話多久,語音說的話也更清楚。@@ -23,6 +24,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o### en-US- First-time setup now checks your account: ask a computer already in it for access, or pair a new one, like a VPS. The install page also has a button that copies the website link, to download on your computer.+- Messages you send while a bot works wait above the message box: tap the arrow to hand one over now (Claude and Codex take it into the reply they're writing), or the trash can to take it back.- When your bots use more than one agent, the bot list marks each avatar with its agent's logo. Turn it off in Settings › Appearance.- Fixed a crash in voice calls when the bot finished reading a reply and started listening again.- A call's conversation is easier to read: the bot, when the call ended and how long it lasted sit at the top, and the voice's words are clearer.diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.mdindex f24b933c..389122a8 100644--- a/docs/architecture/conversation-runtime.md+++ b/docs/architecture/conversation-runtime.md@@ -7,5 +7,5 @@- **A session that fails** with an internal error its agent gives no category (JSON-RPC `-32603` without `data.errorKind`) is closed right after the turn, when the agent can close and load sessions: Claude's adapter otherwise answers every later prompt on it with "The Claude Agent session has ended". The next message loads it again and the conversation carries on (`acp::may_end_session`).- **Lead bot**: the host makes the first one per computer (`chat/lead.rs`), and the user may pick another (`setLead`) or delete it; on top of every roster, never hidden; its instructions ask for initiative, the *Check in* routine made with the first runs twice a day, and it opens a call with a turn of its own (`Cmd::Prompt`, no user message): [docs/features/lead-bot.md](../features/lead-bot.md).- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and sends one a request through its actor queue (`message_bot`); nothing waits, and the reply comes back to the sender as a turn of its own in its main chat. Requests and replies are separate turns, bounded by the chain's hop count; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).-- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).+- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn or steered into the running one, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way, also between turns from work the agent goes on with in the background, into the bot's own chat with a *done* alert, unless the user stopped its last turn; a turn that sent none falls back to its last text, unless it reacted to the user's message instead or passed), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet; with [Show thinking details](../features/chat-messages.md#while-it-works) on (Settings › Chat), the live activity also unfolds the running turn's steps, without the bot's `bookkeeping` tool calls): [docs/features/chat-messages.md](../features/chat-messages.md).diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 39f64083..b3fee89a 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -187,7 +187,12 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/me## Turns-- Messages sent while the agent works are folded into one next turn, joined by blank lines.+- Messages sent while the agent works wait above the composer and are folded into one next turn, joined by blank+ lines. *Send now* (`steer`) hands one to the agent at once: an agent with `_session/steering` (Claude, Codex, omp)+ takes it into the running turn of the user's own chat, and the message joins that turn (its `turn`, its reply,+ memory, a fallback's retry); another agent's turn in the user's chat stops for it, and behind a routine, a room or+ another bot's request it goes first in line. *Remove* (`unqueue`) takes it back: it never goes out and the chat+ hides it (`removed`).- Bot-to-bot requests and the replies to them occupy separate turns in the same queue (replies waiting together are one turn); user messages are only folded together up to the next request or reply. Neither feeds dreaming. See [bot collaboration](bot-collaboration.md).- A request turn (the recipient's) doesn't set the restart marker: its pending notices become interrupted errors instead of automatically replaying work. A reply turn is the sender's own chat turn and sets it, so it resumes like a user turn.- Stop sends `session/cancel`; an agent still running 15 seconds later is stopped (it resumes its session ondiff --git a/docs/reference/acp-adapter-workarounds.md b/docs/reference/acp-adapter-workarounds.mdindex b9dee261..34c11cef 100644--- a/docs/reference/acp-adapter-workarounds.md+++ b/docs/reference/acp-adapter-workarounds.md@@ -97,3 +97,8 @@ Not one adapter's bug: the protocol leaves these open, and the host covers them(`host/src/agent/bot/compaction.rs`).- Mode ids have no fixed meaning: Auto is found by id or name, and Goose's `auto` (approves everything) is hidden(`host/src/agent/modes.rs`).+- No way in ACP v1 to hand a running turn another message: *Send now* uses the agents' own `_session/steering`+ (advertised in the top-level `_meta.steering.supported`; claude-acp, codex-acp, omp) with `idleBehavior:+ "promptRequired"`, and stops the turn for agents without it (`host/src/agent/bot/steer.rs`). Move to the standard+ once ACP v2's prompts during active work and the `delivery` RFD+ ([agent-client-protocol#1261](https://github.com/agentclientprotocol/agent-client-protocol/pull/1261)) are stable.diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.mdindex 1295f2f9..1891d92e 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -71,6 +71,8 @@ host answers and sends it once the host is up.| `section_renamed` | host | `renameSection` | `removed`: whether it removed the section (`to` empty or `null`); never the names || `bot_deleted` | host | `deleteBot` | — || `message_sent` | host | `send` (a resend counts once) | `kind`, `agent`, `reply` (whether it quotes a message), `attachments` (count) |+| `message_steered` | host | *Send now* on a queued message (`steer`), once its outcome is known | `agent`, `how` (`joined` the running turn / `next` turn, the turn ended first / `interrupted` the user's turn / `moved_up` behind other work / `failed`, it waits) |+| `queued_message_removed` | host | *Remove* on a queued message (`unqueue`) | — || `turn_stopped` | host | `stop` | — || `turn_finished` | host | An agent's turn ends: once per agent it ran on, so a turn that fell back once and then answered sends a `failed` and a `done` | `agent`, `outcome` (`done`/`stopped`/`failed`/`needs_setup`/`incomplete`; `needs_setup` is a failure whose `error` is `sign_in` or `not_installed`: the user has a step to take, nothing broke), `stop_reason`, `source` (`user`/`routine`/`group`/`bot`/`host`: the lead opening a call), `seconds`; when failed or needs_setup, `error` (`not_installed`/`timeout`/`exited`/`no_model`/`sign_in`/`agent_error`/`io`/`other`) and, for `agent_error`, `rpc_code` and `agent_reason` (the adapter's own category, else one the host reads from the message, which is never sent: `session_ended`/`rate_limit`/`quota`/`overloaded`/`context`/`model`/`network`/`provider`/`unknown`) || `agent_fell_back` | host | A turn moves on to the bot's next agent ([agent fallbacks](../features/agent-fallback.md)) | `agent` (the one that couldn't answer), `reason` (`usageLimit`/`outOfCredits`/`rateLimited`/`overloaded`/`signedOut`/`notStarting`/`modelMissing`) |diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.mdindex 78a471e7..497aaaee 100644--- a/docs/reference/compatibility.md+++ b/docs/reference/compatibility.md@@ -42,6 +42,9 @@ The iPhone and desktop apps also treat **undecodable data from a newer host** asthat stays undecodable after the one rewind, or a `hello` whose other fields can't be decoded(its `version` and `minApp` are still read). From an older or equal host it's only logged.+Apps older than 2.38.1 don't read `removed`: a queued message taken back on a newer client (`unqueue`) stays in their+chat as *Not sent — stopped*. Nothing breaks and the message never went out, so it raises no floor.+## Changing what crosses the wireThe policy is to move people forward rather than carry old formats: a breaking change shipsdiff --git a/host/src/agent/bot/cmd.rs b/host/src/agent/bot/cmd.rsindex c105a3c7..b05c4585 100644--- a/host/src/agent/bot/cmd.rs+++ b/host/src/agent/bot/cmd.rs@@ -15,6 +15,19 @@ pub enum Cmd {entry_id: String,text: String,},+ /// The user wants a queued message of theirs handled now (`steer`).+ Steer {+ entry_id: String,+ },+ /// What the agent made of a steered message (`_session/steering`).+ Steered {+ entry_id: String,+ outcome: Result<Value>,+ },+ /// The user took back a queued message of theirs (`unqueue`).+ Unqueue {+ entry_id: String,+ },BotRequest(crate::chat::team::BotRequest),/// How a request this bot sent came out: a turn of its own, with any others that arrive meanwhile.BotReply(crate::chat::team::BotReply),diff --git a/host/src/agent/bot/fallback.rs b/host/src/agent/bot/fallback.rsindex 52944611..da9afa9f 100644--- a/host/src/agent/bot/fallback.rs+++ b/host/src/agent/bot/fallback.rs@@ -111,6 +111,14 @@ impl Actor {}}+ /// A message that joined the running turn (`steer`) goes with it to the next agent.+ pub(super) fn relay_joined(&mut self, entry_id: &str, text: &str) {+ if let Some(attempt) = &mut self.relay.attempt {+ attempt.entries.push(entry_id.to_owned());+ attempt.text = format!("{}\n\n{text}", attempt.text);+ }+ }+/// A turn (or its retry) starting on step `target`: the agents before it that rest because a bot found them/// signed out ask to be signed in here too.fn left_signed_out_before(&mut self, target: usize, now: i64) {diff --git a/host/src/agent/bot/launch.rs b/host/src/agent/bot/launch.rsindex f6cc99c6..7d460fab 100644--- a/host/src/agent/bot/launch.rs+++ b/host/src/agent/bot/launch.rs@@ -157,6 +157,8 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, Stringclose: init["agentCapabilities"]["sessionCapabilities"]["close"].is_object(),system_prompt: init["agentCapabilities"]["sessionCapabilities"]["systemPrompt"].is_object(),additional_directories: init["agentCapabilities"]["sessionCapabilities"]["additionalDirectories"].is_object(),+ // Claude's, Codex's and omp's adapters say so in the top-level `_meta`.+ steering: init["_meta"]["steering"]["supported"] == true,};Ok(Conn {acp,diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 2706e3c5..60f669ad 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -28,6 +28,7 @@ mod modes;mod pi_tools;mod queue;mod session;+mod steer;mod tool_entry;mod turn;mod updates;@@ -111,6 +112,7 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {first_prompt: None,turn: None,queue: VecDeque::new(),+ steers_in_flight: HashMap::new(),active_request: None,reply_hops: None,active_prompt: false,@@ -149,6 +151,8 @@ struct SessionCaps {system_prompt: bool,/// ACP `additionalDirectories`: folders outside `cwd` the agent may work in, here the memory folders.additional_directories: bool,+ /// `_session/steering` (not in ACP v1 yet): a message joins the running turn (see `steer`).+ steering: bool,}/// How the bot's instructions (identity and memory) reach the agent.@@ -283,6 +287,8 @@ struct Actor {first_prompt: Option<Snapshot>,turn: Option<i64>,queue: VecDeque<Queued>,+ /// Queued messages handed to the agent to join the running turn, by entry id, until it answers (`steer`).+ steers_in_flight: HashMap<String, steer::InFlight>,active_request: Option<crate::chat::team::BotRequest>,/// During a turn that takes bot replies: the hops of their chain (see `chat::team::BotReply`).reply_hops: Option<u8>,diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 7b6d7c7a..54440074 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -19,6 +19,9 @@ impl Actor {}Cmd::Routine(id) => self.enqueue(Queued::Routine(id), done_tx).await,Cmd::Send { lane, entry_id, text } => self.enqueue(Queued::User { lane, entry_id, text }, done_tx).await,+ Cmd::Steer { entry_id } => self.steer(entry_id).await,+ Cmd::Steered { entry_id, outcome } => self.steered(&entry_id, &outcome),+ Cmd::Unqueue { entry_id } => self.unqueue(&entry_id),Cmd::Group(turn) => {// The room asks again: this turn answers for any still waiting there.self.queue.retain(|q| !matches!(q, Queued::Group(g) if g.lane == turn.lane));@@ -183,7 +186,12 @@ impl Actor {self.restart_agent().await;}let main = Lane::main(&self.cfg.id);- while self.turn.is_none() && self.routine_completion.is_none() && !self.queue.is_empty() {+ // A message being steered is the running turn's or the next one's once the agent answers (`steer`).+ while self.turn.is_none()+ && self.routine_completion.is_none()+ && self.steers_in_flight.is_empty()+ && !self.queue.is_empty()+ {match self.queue.front() {Some(Queued::Routine(_)) => {let Some(Queued::Routine(id)) = self.queue.pop_front() else { unreachable!("front is a routine") };diff --git a/host/src/agent/bot/steer.rs b/host/src/agent/bot/steer.rsnew file mode 100644index 00000000..339e01f4--- /dev/null+++ b/host/src/agent/bot/steer.rs@@ -0,0 +1,153 @@+//! The user's queued messages before their turn comes: handled now (`steer`) or taken back (`unqueue`).++use super::{Actor, Cmd, Queued};+use crate::analytics::{self, Steer, TurnSource};+use crate::chat::team::RequestStatus;+use crate::store::Lane;+use anyhow::{Result, anyhow};+use serde_json::{Value, json};+use std::time::Duration;++/// How long the agent may take to say whether a steered message joined its turn.+const STEER_ANSWER: Duration = Duration::from_secs(15);++/// A queued message handed to the agent to join its running turn, until the agent answers.+pub(super) struct InFlight {+ /// The turn it joins, even one that ends before the answer comes.+ turn: i64,+ /// The user took it back meanwhile (`unqueue`): it goes unless the agent took it.+ taken_back: bool,+}++/// What the agent's answer to a steer made of the message.+fn steer_outcome(answer: &Result<Value>) -> Steer {+ match answer {+ Ok(v) if v["outcome"] == "injected" => Steer::Joined,+ Ok(v) if v["outcome"] == "promptRequired" => Steer::Next,+ _ => Steer::Failed,+ }+}++impl Actor {+ /// Where the user's queued message `entry_id` waits.+ fn queued_at(&self, entry_id: &str) -> Option<usize> {+ self.queue.iter().position(|q| matches!(q, Queued::User { entry_id: id, .. } if id == entry_id))+ }++ /// The running turn answers the user's own messages in `lane`: not a routine's, a room's, another bot's or the+ /// host's, nor a compaction.+ fn answers_user_in(&self, lane: &Lane) -> bool {+ self.turn.is_some() && self.lane == *lane && self.compacting.is_none() && self.source() == TurnSource::User+ }++ /// `steer`: the agent takes the message into its running turn when it can (`_session/steering`). Otherwise the+ /// user's turn stops for it, or, behind other work, it goes first in line.+ pub(super) async fn steer(&mut self, entry_id: String) {+ // Already with the agent.+ if self.steers_in_flight.contains_key(&entry_id) {+ return;+ }+ let Some(at) = self.queued_at(&entry_id) else { return };+ let Some(Queued::User { lane, text, .. }) = self.queue.get(at) else { return };+ let own = self.answers_user_in(lane);+ let text = text.clone();+ if own+ && let Some(turn) = self.turn+ && let Some(conn) = self.conn.as_ref().filter(|c| c.sessions.steering)+ && let Some(sid) = self.turn_session.clone()+ {+ let (acp, hub, bot) = (conn.acp.clone(), self.hub.clone(), self.cfg.id.clone());+ let params = json!({+ "sessionId": sid,+ "prompt": [{"type": "text", "text": text}],+ // A turn that just ended doesn't take it: it stays queued for the next one.+ "_meta": {"steering": {"idleBehavior": "promptRequired"}},+ });+ // What the agent writes from here may answer it: a reply of its own, after the message in the chat.+ self.close_seg();+ self.steers_in_flight.insert(entry_id.clone(), InFlight { turn, taken_back: false });+ tokio::spawn(async move {+ let answer = tokio::time::timeout(STEER_ANSWER, acp.request("_session/steering", params)).await;+ let outcome = answer.unwrap_or_else(|_| Err(anyhow!("the agent didn't answer the steer")));+ let _ = hub.send_cmd(&bot, Cmd::Steered { entry_id, outcome });+ });+ return;+ }+ let item = self.queue.remove(at).expect("found above");+ // A compaction that is due still goes first.+ let first = self.queue.iter().position(|q| !matches!(q, Queued::Compact { .. })).unwrap_or(self.queue.len());+ self.queue.insert(first, item);+ let how = if own {+ self.cancel_turn().await;+ Steer::Interrupted+ } else {+ Steer::MovedUp+ };+ analytics::message_steered(&self.hub, &self.cfg.backend, how);+ }++ /// The agent's answer to a steer: a message it took is that turn's, sent; any other stays queued, unless the+ /// user took it back meanwhile.+ pub(super) fn steered(&mut self, entry_id: &str, outcome: &Result<Value>) {+ let Some(steer) = self.steers_in_flight.remove(entry_id) else { return };+ if let Err(error) = outcome {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't steer; the message waits");+ }+ let how = steer_outcome(outcome);+ analytics::message_steered(&self.hub, &self.cfg.backend, how);+ if how != Steer::Joined {+ if steer.taken_back {+ self.unqueue(entry_id);+ }+ return;+ }+ // A Stop meanwhile dropped it from the queue (and marked it cancelled).+ let Some(at) = self.queued_at(entry_id) else { return };+ let Some(Queued::User { text, .. }) = self.queue.remove(at) else { return };+ // The host's copy, never `removed`, also brings it back to a client that took it back meanwhile.+ if let Some(mut e) = self.hub.store.entry(entry_id) {+ e.data["status"] = json!(RequestStatus::Sent);+ self.hub.set_entry_turn(entry_id, Some(steer.turn), &e.data);+ }+ if self.turn == Some(steer.turn) {+ self.turn_entries.push(entry_id.to_owned());+ if let Some(turn_text) = &mut self.turn_text {+ turn_text.push_str("\n\n");+ turn_text.push_str(&text);+ }+ self.relay_joined(entry_id, &text);+ }+ }++ /// `unqueue`: the message never goes out, and the chat no longer shows it.+ pub(super) fn unqueue(&mut self, entry_id: &str) {+ // Already with the agent, which may take it: `steered` decides.+ if let Some(steer) = self.steers_in_flight.get_mut(entry_id) {+ steer.taken_back = true;+ return;+ }+ let Some(at) = self.queued_at(entry_id) else { return };+ self.queue.remove(at);+ if let Some(mut e) = self.hub.store.entry(entry_id) {+ e.data["status"] = "cancelled".into();+ e.data["removed"] = true.into();+ self.hub.set_entry(entry_id, &e.data);+ // The roster previews the chat's newest message.+ self.hub.emit_bot(&self.cfg.id);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_agents_answer_says_what_became_of_the_message() {+ assert_eq!(steer_outcome(&Ok(json!({"outcome": "injected"}))), Steer::Joined);+ assert_eq!(steer_outcome(&Ok(json!({"outcome": "promptRequired"}))), Steer::Next);+ assert_eq!(steer_outcome(&Ok(json!({"outcome": "somethingNew"}))), Steer::Failed);+ assert_eq!(steer_outcome(&Err(anyhow!("gone"))), Steer::Failed);+ assert_eq!(json!(Steer::MovedUp), "moved_up", "as the event reports it");+ }+}diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex e09849f5..95bdd405 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -451,7 +451,7 @@ impl Actor {}/// What started the turn that is starting or running.- fn source(&self) -> TurnSource {+ pub(super) fn source(&self) -> TurnSource {if self.active_routine.is_some() {TurnSource::Routine} else if self.active_group.is_some() {diff --git a/host/src/analytics.rs b/host/src/analytics.rsindex 3688210a..8e26fc27 100644--- a/host/src/analytics.rs+++ b/host/src/analytics.rs@@ -24,7 +24,7 @@ mod turns;pub use lifecycle::{KV_STARTED, Via, device_paired, host_started, phone_connected};pub use observe::{answered, failed, observe_call};pub use reported::track;-pub use turns::{TurnOutcome, TurnSource, agent_fell_back, turn_finished};+pub use turns::{Steer, TurnOutcome, TurnSource, agent_fell_back, message_steered, turn_finished};const KV_ENABLED: &str = "analytics_enabled";/// The account the install id was last merged into (one `$identify` per account).@@ -64,6 +64,9 @@ pub enum Event {SectionRenamed,BotDeleted,MessageSent,+ /// The user had a queued message handled now (`agent::bot::steer`).+ MessageSteered,+ QueuedMessageRemoved,TurnStopped,TurnFinished,/// A turn moved on to the bot's next agent (`agent::fallback`).@@ -133,6 +136,8 @@ impl Event {Self::SectionRenamed => "section_renamed",Self::BotDeleted => "bot_deleted",Self::MessageSent => "message_sent",+ Self::MessageSteered => "message_steered",+ Self::QueuedMessageRemoved => "queued_message_removed",Self::TurnStopped => "turn_stopped",Self::TurnFinished => "turn_finished",Self::AgentFellBack => "agent_fell_back",diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex ba3df2e8..94c03ae5 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -96,6 +96,7 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<EveEvent::MessageSent}"stop" => Event::TurnStopped,+ "unqueue" => Event::QueuedMessageRemoved,"newSession" => Event::SessionReset,"respondPermission" => Event::PermissionAnswered,"react" => Event::ReactionAdded,diff --git a/host/src/analytics/turns.rs b/host/src/analytics/turns.rsindex 8553c51e..c442812b 100644--- a/host/src/analytics/turns.rs+++ b/host/src/analytics/turns.rs@@ -2,6 +2,7 @@use super::{Event, capture};use crate::hub::Hub;+use serde::Serialize;use serde_json::json;/// How an agent's turn ended (`turn_finished`).@@ -84,6 +85,28 @@ pub fn agent_fell_back(hub: &Hub, agent: &str, reason: crate::agent::fallback::Rcapture(hub, Event::AgentFellBack, p.as_object().cloned().unwrap_or_default());}+/// What became of a queued message the user had handled now (`message_steered`).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Steer {+ /// The agent took it into its running turn.+ Joined,+ /// The turn ended first: it is the next one.+ Next,+ /// The agent can't steer: the user's turn stopped for it.+ Interrupted,+ /// Other work runs (a routine, a room, another bot): it is next in line.+ MovedUp,+ /// The agent refused it or didn't answer: it waits for its turn.+ Failed,+}++/// `message_steered`: the agent and what became of the message.+pub fn message_steered(hub: &Hub, agent: &str, how: Steer) {+ let p = json!({"agent": agent, "how": how});+ capture(hub, Event::MessageSteered, p.as_object().cloned().unwrap_or_default());+}+/// Why a turn failed, as a category (plus the agent's JSON-RPC error, for its code and own/// category): never the error's text, which can hold paths and agent output.fn failure_kind(e: &anyhow::Error) -> (&'static str, Option<&crate::agent::acp::RpcError>) {diff --git a/host/src/api/bots.rs b/host/src/api/bots.rsindex c12aa05b..9bb1b48d 100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@ -246,6 +246,20 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value}json!({})}+ // A message of the user's waiting for its turn: handled now (`steer`) or taken back (`unqueue`).+ "steer" | "unqueue" => {+ let (bot, entry_id) = (str_arg(&b, "botId")?, str_arg(&b, "entryId")?.to_owned());+ let queued = hub+ .store+ .entry(&entry_id)+ .filter(|e| e.bot_id == bot && e.kind == EntryKind::User.as_str() && e.data["status"] == "queued");+ if queued.is_none() {+ bail!("that message isn't waiting any more");+ }+ let cmd = if method == "steer" { Cmd::Steer { entry_id } } else { Cmd::Unqueue { entry_id } };+ hub.send_cmd(bot, cmd)?;+ json!({})+ }"switchBack" => {hub.send_cmd(str_arg(&b, "botId")?, Cmd::SwitchBack)?;json!({})diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rsindex ec1ccacc..1374fbcf 100644--- a/host/src/chat/calls/context.rs+++ b/host/src/chat/calls/context.rs@@ -318,7 +318,8 @@ fn others(hub: &Hub, cfg: &BotConfig) -> String {fn shared(recent: &[Entry]) -> String {let mut titles: Vec<String> = Vec::new();- for e in recent.iter().rev() {+ // A message the user took back before it went out (`unqueue`) shared nothing.+ for e in recent.iter().rev().filter(|e| e.data["removed"] != true) {if let Some(title) = e.data["artifact"]["title"].as_str() {titles.push(format!("- {title} (artifact)"));}@@ -500,4 +501,19 @@ pub(super) mod tests {"{section}");}++ #[test]+ fn a_file_on_a_message_taken_back_is_not_shared() {+ let hub = hub();+ let main = Lane::main("b");+ let files = |name: &str, extra: serde_json::Value| {+ let mut data = json!({"attachments": [{"name": name, "size": 1}]});+ data.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());+ data+ };+ hub.store.insert_entry(&main, EntryKind::User, 1, &files("kept.png", json!({}))).unwrap();+ let gone = files("secret.pem", json!({"status": "cancelled", "removed": true}));+ hub.store.insert_entry(&main, EntryKind::User, 2, &gone).unwrap();+ assert_eq!(shared(&hub.store.history("b", i64::MAX, RECENT).unwrap()), "- kept.png");+ }}diff --git a/host/src/chat/handoff.rs b/host/src/chat/handoff.rsindex fff3c284..d9e16e1e 100644--- a/host/src/chat/handoff.rs+++ b/host/src/chat/handoff.rs@@ -82,7 +82,9 @@ pub fn draft(hub: &Hub, cfg: &BotConfig, session: &str, reason: Reason) -> Resul}fn build(store: &Store, bot: &str, session: &str) -> Result<String> {- let entries = store.history(bot, i64::MAX, READ)?;+ // A message the user took back before it went out (`unqueue`) was never asked.+ let entries: Vec<_> =+ store.history(bot, i64::MAX, READ)?.into_iter().filter(|e| e.data["removed"] != true).collect();let user = EntryKind::User.as_str();let requests: Vec<(String, String)> = entries.iter()diff --git a/host/src/hub.rs b/host/src/hub.rsindex 0c122d54..71b7e28c 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -435,8 +435,13 @@ impl Hub {/// Updates and broadcasts an entry; failures are logged here, like [`Self::add_entry`].pub fn set_entry(&self, id: &str, data: &Value) -> Option<Entry> {+ self.set_entry_turn(id, None, data)+ }++ /// [`Self::set_entry`] that also moves the entry into `turn` when given.+ pub fn set_entry_turn(&self, id: &str, turn: Option<i64>, data: &Value) -> Option<Entry> {let _g = self.emit_lock.locked();- match self.store.update_entry(id, data) {+ match self.store.update_entry(id, turn, data) {Ok(e) => {if let Some(e) = &e {let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));@@ -459,7 +464,7 @@ impl Hub {if !edit(&mut e)? {return Ok(e);}- let e = self.store.update_entry(id, &e.data)?.ok_or_else(|| anyhow!("unknown message"))?;+ let e = self.store.update_entry(id, None, &e.data)?.ok_or_else(|| anyhow!("unknown message"))?;let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));Ok(e)}diff --git a/host/src/store/bots.rs b/host/src/store/bots.rsindex 1cc8313a..67d9bddc 100644--- a/host/src/store/bots.rs+++ b/host/src/store/bots.rs@@ -1,5 +1,6 @@//! The `bots` table: roster rows, sessions, read marks and unread counts.+use super::entries::NOT_REMOVED;use super::model::{BotConfig, BotRow, EntryKind, LastMessage, message_text};use super::{Store, logged, next_rev};use crate::LockExt;@@ -131,10 +132,12 @@ impl Store {pub fn last_message(&self, id: &str) -> Option<LastMessage> {let c = self.db.locked();let row = c.query_row(- "SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND- (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1)) AND- json_extract(data, '$.call') IS NULL- ORDER BY seq DESC LIMIT 1",+ &format!(+ "SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND+ (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1)) AND+ json_extract(data, '$.call') IS NULL AND {NOT_REMOVED}+ ORDER BY seq DESC LIMIT 1"+ ),[id],|r| {let kind: String = r.get(0)?;@@ -210,7 +213,7 @@ mod tests {.unwrap();assert!(a.rev > u.rev);assert_eq!(s.unread("b1", 0), 0, "narration is not unread");- let a2 = s.update_entry(&a.id, &serde_json::json!({"text": "yo!", "final": true})).unwrap().unwrap();+ let a2 = s.update_entry(&a.id, None, &serde_json::json!({"text": "yo!", "final": true})).unwrap().unwrap();assert_eq!(s.unread("b1", 0), 1);assert_eq!(s.entries_since(a2.rev - 1, 500).unwrap().len(), 1);assert_eq!(s.entries_since(0, 1).unwrap().len(), 1, "fresh sync is capped per bot");diff --git a/host/src/store/entries.rs b/host/src/store/entries.rsindex f07734e3..60b0aef6 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -26,6 +26,8 @@ fn row_entry(r: &rusqlite::Row) -> rusqlite::Result<Entry> {const ENTRY_COLS: &str = "seq, id, bot_id, rev, kind, turn, data, created_at, updated_at";/// A bot still winding down after its deletion can't leave lines behind (`?2` is the chat).const LIVE_CHAT: &str = "WHERE NOT EXISTS (SELECT 1 FROM bots WHERE id = ?2 AND deleted = 1)";+/// Leaves out a message the user took back before it went out (`unqueue`): no bot, model or list reads it.+pub(super) const NOT_REMOVED: &str = "json_extract(data, '$.removed') IS NOT 1";impl Store {pub fn insert_entry(&self, lane: &Lane, kind: EntryKind, turn: i64, data: &Value) -> Result<Entry> {@@ -80,12 +82,13 @@ impl Store {Ok((entry, true))}- pub fn update_entry(&self, id: &str, data: &Value) -> Result<Option<Entry>> {+ /// Rewrites an entry's data, and moves it into `turn` when given (a queued message that joined the running turn).+ pub fn update_entry(&self, id: &str, turn: Option<i64>, data: &Value) -> Result<Option<Entry>> {let c = self.db.locked();let rev = next_rev(&c)?;c.execute(- "UPDATE entries SET rev = ?2, data = ?3, updated_at = ?4 WHERE id = ?1",- params![id, rev, data.to_string(), now_ms()],+ "UPDATE entries SET rev = ?2, data = ?3, updated_at = ?4, turn = COALESCE(?5, turn) WHERE id = ?1",+ params![id, rev, data.to_string(), now_ms(), turn],)?;Ok(c.query_row(&format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"), [id], row_entry).optional()?)}@@ -182,7 +185,7 @@ impl Store {pub fn file_messages(&self, bot_id: &str, limit: i64) -> Result<Vec<Entry>> {let c = self.db.locked();let mut st = c.prepare(&format!(- "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND {NOT_REMOVED}AND (json_array_length(data, '$.files') > 0 OR json_array_length(data, '$.attachments') > 0)ORDER BY seq DESC LIMIT ?2"))?;@@ -209,7 +212,7 @@ impl Store {// An FTS5 trigram table once a bot's search passes a second.pub fn search_messages(&self, bot_id: &str, terms: &[String], from: Option<i64>, limit: i64) -> Result<Vec<Entry>> {let mut sql = format!(- "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq <= ?3 AND+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq <= ?3 AND {NOT_REMOVED} AND(kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))");for i in 0..terms.len() {@@ -244,7 +247,7 @@ impl Store {pub fn conversation_since(&self, bot_id: &str, after_seq: i64, limit: i64) -> Result<Vec<Entry>> {let c = self.db.locked();let mut st = c.prepare(&format!(- "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq > ?2 AND+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq > ?2 AND {NOT_REMOVED} AND(kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1)OR (kind = 'notice' AND json_extract(data, '$.transcript') IS NOT NULL))ORDER BY seq LIMIT ?3"@@ -266,7 +269,7 @@ impl Store {pub fn messages_after(&self, lane: &Lane, after_seq: i64, limit: i64) -> Result<Vec<Entry>> {let c = self.db.locked();let mut st = c.prepare(&format!(- "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq > ?2 AND+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq > ?2 AND {NOT_REMOVED} AND(kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))ORDER BY seq DESC LIMIT ?3"))?;@@ -337,7 +340,7 @@ impl Store {"expired"};e.data["status"] = status.into();- self.update_entry(id, &e.data)?;+ self.update_entry(id, None, &e.data)?;}}Ok(ids.len())@@ -388,6 +391,23 @@ mod tests {assert_eq!(texts(&[], None), ["note 4", "note 3"]);}+ #[test]+ fn a_message_taken_back_reaches_no_reader() {+ let s = temp_store();+ let main = Lane::main("b1");+ let file = json!([{"name": "a.png", "size": 1}]);+ let kept = s.insert_entry(&main, EntryKind::User, 1, &json!({"text": "ship it", "attachments": file})).unwrap();+ let gone = json!({"text": "ship the prod table", "attachments": file, "status": "cancelled", "removed": true});+ s.insert_entry(&main, EntryKind::User, 2, &gone).unwrap();+ let ids = |rows: Vec<Entry>| rows.into_iter().map(|e| e.id).collect::<Vec<_>>();+ let kept = [kept.id];+ assert_eq!(ids(s.messages_after(&main, 0, 10).unwrap()), kept, "recaps, calls and rooms");+ assert_eq!(ids(s.conversation_since("b1", 0, 10).unwrap()), kept, "dreaming");+ assert_eq!(ids(s.search_messages("b1", &["ship".to_owned()], None, 10).unwrap()), kept, "memory search");+ assert_eq!(ids(s.file_messages("b1", 10).unwrap()), kept, "the Library");+ assert_eq!(s.last_message("b1").unwrap().text, "ship it", "the roster");+ }+#[test]fn restart_expires_pending_cards_and_queued_sends() {let s = temp_store();diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rsindex a2b97004..26cd514a 100644--- a/host/src/tui/app/input.rs+++ b/host/src/tui/app/input.rs@@ -330,6 +330,8 @@ impl App {}}}+ KeyCode::Char('S') => self.steer_next(),+ KeyCode::Char('D') => self.unqueue_last(),KeyCode::Char('*') => self.make_lead(),KeyCode::Char('x') => {// An older host keeps its lead.diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex 64bcd5d4..d5ca1877 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -15,6 +15,7 @@ mod navigate;mod new_bot;mod overlay_keys;mod pair;+mod queue;mod roster;mod section_order;mod slash;@@ -257,6 +258,8 @@ impl App {// line when the call ends, or when its app went away. A file or an artifact the bot sent stays, to be opened.let opens = |e: &Entry| e.artifact().is_some() || e.data["files"].as_array().is_some_and(|f| !f.is_empty());v.retain(|e| e.kind == Kind::Notice || e.call().is_none() || opens(e));+ // A queued message the user took back (`unqueue`).+ v.retain(|e| e.data["removed"] != true);// A message sent mid-turn belongs after that turn's reply.v.sort_by_key(|e| (e.turn, e.seq));vdiff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex 6a51b513..96a63713 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -224,6 +224,11 @@ impl Entry {self.kind == Kind::Permission && self.data["status"] == "pending"}+ /// A message of the user's waiting for its turn: it shows above the composer, not in the chat.+ pub fn queued(&self) -> bool {+ self.kind == Kind::User && self.data["status"] == "queued"+ }+/// Approval options in the apps' order: allow once, allow always, reject once, reject always.pub fn options(&self) -> Vec<(String, String, String)> {let rank = |k: &str| match k {diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rsindex d93eed94..e5a383c0 100644--- a/host/src/tui/app/navigate.rs+++ b/host/src/tui/app/navigate.rs@@ -130,7 +130,7 @@ impl App {pub(super) fn step_pick(&mut self, d: isize) {let Some(id) = self.selected.clone() else { return };// A run of exchanges with one peer is one pick: its first entry.- let lane = self.lane(&id);+ let lane = self.chat(&id);let picks: Vec<(String, bool)> = group(&id, &lane).into_iter().filter_map(|item| match item {diff --git a/host/src/tui/app/queue.rs b/host/src/tui/app/queue.rsnew file mode 100644index 00000000..140463cd--- /dev/null+++ b/host/src/tui/app/queue.rs@@ -0,0 +1,101 @@+//! The user's messages waiting behind a running turn: `S` sends the next one now (`steer`), `D` takes back the last+//! one (`unqueue`).++use super::{After, App, Entry};+use serde_json::json;++/// The first host that sends a queued message now and takes one back.+const STEER_SINCE: &str = "2.38.1";++impl App {+ /// `bot`'s queued messages, oldest (the next to go) first.+ pub fn queued(&self, bot: &str) -> Vec<&Entry> {+ let mut v: Vec<&Entry> = self.lane(bot).into_iter().filter(|e| e.queued()).collect();+ v.sort_by_key(|e| e.seq);+ v+ }++ /// `bot`'s chat: its lane without the queued messages, which wait above the composer.+ pub fn chat(&self, bot: &str) -> Vec<&Entry> {+ self.lane(bot).into_iter().filter(|e| !e.queued()).collect()+ }++ /// Whether the host takes `S` and `D`: an older one only queues.+ pub fn queue_keys(&self) -> bool {+ crate::compat::at_least(&self.host_version, STEER_SINCE)+ }++ /// `S`: the next queued message goes out now, into the running turn when the agent can take it.+ pub(super) fn steer_next(&mut self) {+ let next = self.selected.as_deref().and_then(|bot| self.queued(bot).first().map(|e| e.id.clone()));+ self.on_queued("steer", next, "Sending now…");+ }++ /// `D`: the last queued message never goes out.+ pub(super) fn unqueue_last(&mut self) {+ let last = self.selected.as_deref().and_then(|bot| self.queued(bot).last().map(|e| e.id.clone()));+ self.on_queued("unqueue", last, "Removed");+ }++ /// `method` on the selected bot's queued message `id`, saying `done`.+ fn on_queued(&mut self, method: &'static str, id: Option<String>, done: &str) {+ let Some(bot) = self.selected.clone() else { return };+ let Some(id) = id else {+ self.flash("No message waiting");+ return;+ };+ if self+ .host_supports(STEER_SINCE, "Update Codync on {host}: sending now and taking back need {version} or newer.")+ {+ self.call(method, json!({"botId": bot, "entryId": id}), After::Nothing);+ self.flash(done);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::super::{Msg, test_app};+ use serde_json::json;++ fn entry(app: &mut super::App, id: &str, seq: i64, data: &serde_json::Value) {+ let e = json!({"id": id, "botId": "a", "seq": seq, "kind": "user", "turn": seq, "data": data});+ app.on_msg(Msg::Event(json!({"type": "entry", "entry": e})));+ }++ #[test]+ fn queued_lists_waiting_messages_oldest_first_and_never_a_removed_one() {+ let mut app = test_app();+ app.on_msg(Msg::Event(json!({"type": "bot", "bot": {"id": "a", "name": "A"}})));+ entry(&mut app, "sent", 1, &json!({"text": "hi", "status": "sent"}));+ entry(&mut app, "second", 3, &json!({"text": "two", "status": "queued"}));+ entry(&mut app, "first", 2, &json!({"text": "one", "status": "queued"}));+ entry(&mut app, "gone", 4, &json!({"text": "x", "status": "cancelled", "removed": true}));+ let ids: Vec<&str> = app.queued("a").iter().map(|e| e.id.as_str()).collect();+ assert_eq!(ids, ["first", "second"]);+ let chat: Vec<&str> = app.chat("a").iter().map(|e| e.id.as_str()).collect();+ assert_eq!(chat, ["sent"], "the chat has neither the waiting messages nor a removed one");+ }++ #[tokio::test]+ async fn s_and_d_act_on_a_waiting_message_on_a_host_that_takes_them() {+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+ let mut app = test_app();+ app.on_msg(Msg::Event(json!({"type": "bot", "bot": {"id": "a", "name": "A"}})));+ app.selected = Some("a".into());+ app.host = "test".into();+ let hint = |app: &mut super::App, c: char| {+ app.on_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::SHIFT));+ app.hint.take().map(|(text, _)| text).unwrap_or_default()+ };+ assert_eq!(hint(&mut app, 'S'), "No message waiting");+ entry(&mut app, "q", 1, &json!({"text": "one", "status": "queued"}));+ app.host_version = "2.38.0".into();+ assert!(!app.queue_keys());+ assert_eq!(hint(&mut app, 'S'), "Update Codync on test: sending now and taking back need 2.38.1 or newer.");+ app.host_version = "2.38.1".into();+ assert!(app.queue_keys());+ assert_eq!(hint(&mut app, 'S'), "Sending now…");+ assert_eq!(hint(&mut app, 'D'), "Removed");+ }+}diff --git a/host/src/tui/app/roster.rs b/host/src/tui/app/roster.rsindex 5db6c3d2..455a0f12 100644--- a/host/src/tui/app/roster.rs+++ b/host/src/tui/app/roster.rs@@ -265,7 +265,7 @@ impl App {}/// Whether the host is `since` or newer; says what to update when it isn't (`why`, with `{host}` and `{version}`).- fn host_supports(&mut self, since: &str, why: &str) -> bool {+ pub(super) fn host_supports(&mut self, since: &str, why: &str) -> bool {if self.host_version.is_empty() {self.flash("Still connecting: try again in a moment.");return false;diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rsindex b256880f..c266a5d2 100644--- a/host/src/tui/view/chat.rs+++ b/host/src/tui/view/chat.rs@@ -1,5 +1,7 @@//! The chat pane: header, transcript viewport and composer.+use std::borrow::Cow;+use ratatui::buffer::Buffer;use ratatui::layout::{Position, Rect};use ratatui::style::{Modifier, Style};@@ -176,8 +178,22 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {set_cursor(Position::new(r.x + 3 + u(cursor.0), cy.min(comp_top + ch)));}+ // Messages waiting for their turn, over the composer.+ let keys = match (app.queue_keys(), typing) {+ (false, _) => QueueKeys::Hidden,+ (true, false) => QueueKeys::Ready,+ (true, true) => QueueKeys::AfterEsc,+ };+ let rows = queued_rows(&app.queued(&b.id), keys);+ let strip_top = box_top.saturating_sub(u(rows.len()));+ for (i, (text, hint)) in rows.iter().enumerate() {+ let y = strip_top + u(i);+ let room = rput(buf, r.right() - 1, y, hint, t.dim).saturating_sub(r.x + 3);+ put(buf, r.x + 1, y, room, &truncate(text, usize::from(room)), t.secondary);+ }+// Transcript.- let body = Rect::new(r.x, top + 1, r.width, box_top.saturating_sub(top + 1));+ let body = Rect::new(r.x, top + 1, r.width, strip_top.saturating_sub(top + 1));app.chat_height = usize::from(body.height);let built = build_chat(app, &b, usize::from(body.width.saturating_sub(1)));let total = built.lines.len();@@ -212,13 +228,59 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {}if app.chat_scroll > 0 {let s = format!(" ↓ {} more ", app.chat_scroll);- rput(buf, r.right() - 1, box_top.saturating_sub(1), &s, t.btn);+ rput(buf, r.right() - 1, strip_top.saturating_sub(1), &s, t.btn);}if typing {command_menu(buf, body, app);}}+/// Which keys the queue band names.+#[derive(Clone, Copy)]+enum QueueKeys {+ /// A host too old for them.+ Hidden,+ Ready,+ /// Typing: they wait for esc.+ AfterEsc,+}++/// The queue band's rows, (text, keys): up to three messages, oldest first (more are counted), `S` beside the first+/// (it goes next) and `D` beside the last.+fn queued_rows(queued: &[&Entry], keys: QueueKeys) -> Vec<(String, String)> {+ let label = |e: &Entry| {+ let text = super::roster::plain(e.text().lines().next().unwrap_or_default());+ let files: Vec<String> = e.attachments().iter().map(|(name, _)| format!("▤ {name}")).collect();+ format!("› {}", if text.is_empty() { files.join(" ") } else { text })+ };+ let mut rows: Vec<(String, String)> = if queued.len() > 3 {+ let mut rows: Vec<_> = queued[..2].iter().map(|e| (label(e), String::new())).collect();+ rows.push((format!(" +{} more", queued.len() - 2), String::new()));+ rows+ } else {+ queued.iter().map(|e| (label(e), String::new())).collect()+ };+ // `first`: the band's label leads.+ let hint = |first: bool, said: &[&str]| {+ let mut parts: Vec<Cow<str>> = if first { vec![tr("queued")] } else { vec![] };+ match keys {+ QueueKeys::Hidden => {}+ QueueKeys::Ready => parts.extend(said.iter().map(|s| tr(s))),+ QueueKeys::AfterEsc => parts.extend(std::iter::once("esc".into()).chain(said.iter().map(|s| tr(s)))),+ }+ parts.join(" · ")+ };+ match rows.as_mut_slice() {+ [] => {}+ [only] => only.1 = hint(true, &["S sends now", "D removes"]),+ [first, .., last] => {+ first.1 = hint(true, &["S sends this now"]);+ last.1 = hint(false, &["D removes the last"]);+ }+ }+ rows+}+/// The `/` list over the bottom of the transcript: the commands matching what's typed, the/// highlighted one kept in view.fn command_menu(buf: &mut Buffer, body: Rect, app: &App) {@@ -298,6 +360,39 @@ pub(super) fn with_bg(lines: Vec<Line<'static>>, width: usize, bg: Style) -> Vecmod tests {use super::*;+ #[test]+ fn the_queue_band_shows_the_oldest_first_with_the_keys_beside_who_they_act_on() {+ use crate::tui::app::Kind;+ let entry = |id: &str, data: serde_json::Value| Entry {+ id: id.into(),+ seq: 0,+ turn: 0,+ kind: Kind::User,+ data,+ created_at: 0,+ };+ let one = entry("1", serde_json::json!({"text": "first\nmore", "status": "queued"}));+ let file = entry("2", serde_json::json!({"attachments": [{"name": "a.png", "size": 1}], "status": "queued"}));+ assert_eq!(queued_rows(&[], QueueKeys::Ready), Vec::<(String, String)>::new());+ assert_eq!(+ queued_rows(&[&one], QueueKeys::Ready),+ [("› first".to_owned(), "queued · S sends now · D removes".to_owned())]+ );+ assert_eq!(+ queued_rows(&[&one, &file], QueueKeys::AfterEsc),+ [+ ("› first".to_owned(), "queued · esc · S sends this now".to_owned()),+ ("› ▤ a.png".to_owned(), "esc · D removes the last".to_owned())+ ]+ );+ let rows = queued_rows(&[&one, &one, &one, &file], QueueKeys::Ready);+ assert_eq!(rows.len(), 3);+ assert_eq!(rows[2], (" +2 more".to_owned(), "D removes the last".to_owned()));+ // An older host takes neither key: the band only says what waits.+ let rows = queued_rows(&[&one, &file], QueueKeys::Hidden);+ assert_eq!((rows[0].1.as_str(), rows[1].1.as_str()), ("queued", ""));+ }+#[test]fn composer_cursor_tracks_wraps_and_newlines() {let (l, c) = composer_lines(&Editor::with("ab\ncd"), 10);diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rsindex af13d2be..0d09eba8 100644--- a/host/src/tui/view/help.rs+++ b/host/src/tui/view/help.rs@@ -10,7 +10,7 @@ use super::buffer::{centered, frame_box, put, u};use super::overlay::field_line;use super::style::theme;-const HELP: [(&str, &str, &str); 73] = [+const HELP: [(&str, &str, &str); 75] = [("MOVE", "j k ↑ ↓", "next / previous bot"),("MOVE", "[ ]", "previous / next bot"),("MOVE", "1…9", "jump to bot 1–9"),@@ -27,6 +27,8 @@ const HELP: [(&str, &str, &str); 73] = [("CHAT", "N", "reject and say why"),("CHAT", "1…9", "pick an approval option"),("CHAT", "s", "stop the bot"),+ ("CHAT", "S", "send the next queued message now"),+ ("CHAT", "D", "take back the last queued message"),("CHAT", ">", "show / hide the working turn's steps (thinking details on)"),("CHAT", "o", "last turn's steps"),("CHAT", "c", "copy the last reply"),diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex 6cda9f80..c1967443 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -64,7 +64,7 @@ pub(super) fn name_style(color: &str) -> Style {pub(super) fn build_chat(app: &App, b: &Bot, width: usize) -> Built {let t = theme();let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };- let entries = app.lane(&b.id);+ let entries = app.chat(&b.id);let info = turn_info(&entries);if entries.is_empty() {intro(&mut out, app, b, width);@@ -152,10 +152,8 @@ fn entry_lines(out: &mut Built, app: &App, b: &Bot, e: &Entry, info: &HashMap<i6Span::styled(" you", t.secondary.add_modifier(Modifier::BOLD)),Span::styled(format!(" {}", clock(e.created_at)), t.dim),];- match e.data["status"].as_str() {- Some("queued") => head.push(Span::styled(format!(" · {}", tr("Queued")), t.dim)),- Some("cancelled") => head.push(Span::styled(" · not sent", t.red)),- _ => {}+ if e.data["status"] == "cancelled" {+ head.push(Span::styled(" · not sent", t.red));}out.lines.push(Line::from(head));out.lines.extend(quote_line(e, width));diff --git a/host/tests/common/host.rs b/host/tests/common/host.rsindex b7c0d853..d417a712 100644--- a/host/tests/common/host.rs+++ b/host/tests/common/host.rs@@ -167,13 +167,13 @@ impl Host {}}- /// The JSON lines a fixture agent logged to `file` in a bot's workspace.+ /// The JSON lines a fixture agent logged to `file` in a bot's workspace (none before it started).pub fn log(&self, bot: &str, file: &str) -> Vec<Value> {- let log = std::fs::read_to_string(self.home.join("bots").join(bot).join("workspace").join(file)).unwrap();- log.lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).collect()+ let log = std::fs::read_to_string(self.home.join("bots").join(bot).join("workspace").join(file));+ log.unwrap_or_default().lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).collect()}- /// The requests `instructions_agent.py` logged in a bot's workspace.+ /// The requests a fixture agent (`instructions_agent.py`, `steer_agent.py`) logged in a bot's workspace.pub fn requests(&self, bot: &str, method: &str) -> Vec<Value> {self.log(bot, "requests.jsonl").into_iter().filter(|r| r["method"] == method).collect()}diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rsindex 713bc2fb..9bc9f53c 100644--- a/host/tests/common/mod.rs+++ b/host/tests/common/mod.rs@@ -19,6 +19,11 @@ fn test_cloud_key() -> String {/// picked here is only free for a moment; when something else takes it before the host binds, the/// host exits and this starts it again on another one.pub async fn serve(home: &Path) -> (Child, String) {+ serve_with(home, &[]).await+}++/// [`serve`] with `env` on top of the test host's own.+pub async fn serve_with(home: &Path, env: &[(&str, &std::ffi::OsStr)]) -> (Child, String) {let deadline = Instant::now() + Duration::from_secs(30);let _ = std::fs::create_dir_all(home);let log = home.join("host-stderr.log");@@ -32,6 +37,9 @@ pub async fn serve(home: &Path) -> (Child, String) {.env("CODYNC_CLOUD", "off")// Pairing checks the phone's account: tests sign certificates with `TEST_CLOUD_SEED`..env("CODYNC_DEVICE_CERT_KEY", test_cloud_key())+ // A test host leaves the computer's agent CLIs and the user's logins alone.+ .env("CODYNC_AGENT_CHECKS", "off")+ .envs(env.iter().copied()).stdout(Stdio::null()).stderr(std::fs::File::create(&log).map_or_else(|_| Stdio::null(), Stdio::from)).spawn()@@ -90,6 +98,16 @@ pub fn python() -> &'static str {if cfg!(windows) { "python" } else { "python3" }}+/// Whether the test machine lacks Python, which a test of a Python fixture then skips.+#[allow(dead_code, reason = "only the tests of Python fixtures check")]+pub fn python_missing() -> bool {+ let missing = Command::new(python()).arg("--version").output().is_err();+ if missing {+ eprintln!("skipping: Python not available");+ }+ missing+}+/// The agent command that runs a Python fixture (quoted for `sh -c` / `cmd /c`). UTF-8 mode makes it read the host's/// UTF-8 the way real agents do: Windows Python reads pipes in the ANSI code page, turning a `”` into a lone surrogate.pub fn python_agent(script: &Path) -> String {diff --git a/host/tests/fixtures/steer_agent.py b/host/tests/fixtures/steer_agent.pynew file mode 100644index 00000000..667583b8--- /dev/null+++ b/host/tests/fixtures/steer_agent.py@@ -0,0 +1,92 @@+"""ACP agent whose turn waits: a steered message joins it, a cancel stops it, or it ends after `seconds`.++Args: `steer|late|limit|next|plain seconds [answer_delay]`. With `steer` it advertises `_session/steering` (top-level+`_meta`, as Claude's and Codex's adapters do) and takes a steered message into its running turn; with `late` it ends+that turn before answering; with `limit` that turn then fails the way Claude's adapter reports a usage limit; with+`next` it advertises steering too but always answers that the message needs a turn of its own. It answers a steer after+`answer_delay` seconds. Every request is logged to requests.jsonl in its folder.+"""++import json+import sys+import threading+import time++MODE = sys.argv[1]+SECONDS = float(sys.argv[2])+ANSWER_DELAY = float(sys.argv[3]) if len(sys.argv) > 3 else 0+SID = "s1"+LIMIT = {+ "code": -32603,+ "message": "Internal error: You've hit your limit · resets 3pm (Asia/Taipei)",+ "data": {"errorKind": "rate_limit"},+}+lock = threading.Lock()+turn = {"wake": None, "steered": None, "cancelled": False}+++def send(value):+ with lock:+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", **value}) + "\n")+ sys.stdout.flush()+++def say(text):+ update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}+ send({"method": "session/update", "params": {"sessionId": SID, "update": update}})+++def run(rid):+ wake = threading.Event()+ turn.update(wake=wake, steered=None, cancelled=False)+ say("Working")+ wake.wait(SECONDS)+ turn["wake"] = None+ if turn["cancelled"]:+ send({"id": rid, "result": {"stopReason": "cancelled"}})+ return+ if MODE == "limit":+ send({"id": rid, "error": LIMIT})+ return+ say("Got: " + turn["steered"] if turn["steered"] else "Done")+ send({"id": rid, "result": {"stopReason": "end_turn"}})+++def steer(message):+ time.sleep(ANSWER_DELAY)+ wake = turn["wake"]+ if MODE == "next" or wake is None:+ send({"id": message["id"], "result": {"outcome": "promptRequired", "reason": "noRunningTurn"}})+ return+ turn["steered"] = message["params"]["prompt"][0]["text"]+ if MODE == "late":+ wake.set()+ time.sleep(0.5)+ send({"id": message["id"], "result": {"outcome": "injected"}})+ if MODE == "limit":+ time.sleep(0.3)+ wake.set()+++init = {"protocolVersion": 1, "agentCapabilities": {"loadSession": False}}+if MODE != "plain":+ init["_meta"] = {"steering": {"supported": True}}+with open("requests.jsonl", "a") as log:+ for line in sys.stdin:+ message = json.loads(line)+ log.write(line if line.endswith("\n") else line + "\n")+ log.flush()+ method = message.get("method")+ if method == "initialize":+ send({"id": message["id"], "result": init})+ elif method == "session/new":+ send({"id": message["id"], "result": {"sessionId": SID}})+ elif method == "session/prompt":+ threading.Thread(target=run, args=(message["id"],)).start()+ elif method == "_session/steering":+ threading.Thread(target=steer, args=(message,)).start()+ elif method == "session/cancel" and turn["wake"] is not None:+ turn["cancelled"] = True+ turn["wake"].set()+ elif "id" in message and method:+ send({"id": message["id"], "result": {}})diff --git a/host/tests/steer_e2e.rs b/host/tests/steer_e2e.rsnew file mode 100644index 00000000..3f3cd97f--- /dev/null+++ b/host/tests/steer_e2e.rs@@ -0,0 +1,257 @@+//! A real host with the user's messages queued behind a running turn: steered into it (and on to a fallback with it),+//! interrupting a turn whose agent can't steer, first in line behind other work, left for the next turn when the agent+//! says so, or taken back.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use common::host::Host;+use common::python_missing;+use serde_json::{Value, json};+use std::path::PathBuf;+use std::time::{Duration, Instant};++async fn entries(host: &Host, bot: &str) -> Vec<Value> {+ host.call("history", json!({"botId": bot})).await["entries"].as_array().unwrap().clone()+}++async fn entry(host: &Host, bot: &str, id: &str) -> Value {+ entries(host, bot).await.into_iter().find(|e| e["id"] == id).unwrap()+}++async fn eventually(what: &str, within: Duration, mut done: impl AsyncFnMut() -> bool) {+ let deadline = Instant::now() + within;+ while !done().await {+ assert!(Instant::now() < deadline, "timed out waiting until {what}");+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}++/// Sends "first" (its turn running at the agent) and then "second", which waits: the ids of both.+async fn queue_behind_a_turn(host: &Host, bot: &str) -> (String, String) {+ let first =+ host.call("send", json!({"botId": bot, "text": "first"})).await["entry"]["id"].as_str().unwrap().to_owned();+ eventually("the agent got the first prompt", Duration::from_mins(1), async || {+ host.requests(bot, "session/prompt").len() == 1+ })+ .await;+ let second = host.call("send", json!({"botId": bot, "text": "second"})).await["entry"].clone();+ assert_eq!(second["data"]["status"], "queued");+ (first, second["id"].as_str().unwrap().to_owned())+}++async fn idle(host: &Host, bot: &str) -> bool {+ common::bot(&host.snapshot().await, bot)["status"] == "idle"+}++async fn status(host: &Host, bot: &str, id: &str) -> Value {+ entry(host, bot, id).await["data"]["status"].clone()+}++#[tokio::test]+async fn a_steered_message_joins_the_running_turn() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Steers", "steer_agent.py", "steer 30 1").await;+ let (first, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ // Pressed twice while the agent decides: it goes to the agent once.+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ eventually("the turn answered both", Duration::from_secs(20), async || {+ status(&host, &bot, &second).await == "sent" && idle(&host, &bot).await+ })+ .await;++ let steered = host.requests(&bot, "_session/steering");+ assert_eq!(steered.len(), 1);+ assert!(steered[0]["params"]["prompt"][0]["text"].as_str().unwrap().contains("second"));+ assert_eq!(steered[0]["params"]["_meta"]["steering"]["idleBehavior"], "promptRequired");+ assert_eq!(host.requests(&bot, "session/prompt").len(), 1, "no turn of its own");+ let (first, second) = (entry(&host, &bot, &first).await, entry(&host, &bot, &second).await);+ assert_eq!(second["turn"], first["turn"], "it is the running turn's");+ let reply = entries(&host, &bot).await.into_iter().rev().find(|e| e["data"]["final"] == true).unwrap();+ assert!(reply["data"]["text"].as_str().unwrap().contains("Got: "), "{reply}");+ assert!(reply["seq"].as_i64() > second["seq"].as_i64(), "the reply comes after the message it answers");+}++#[tokio::test]+async fn a_steered_message_keeps_a_turn_that_ends_before_the_agent_answers() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Late", "steer_agent.py", "late 30").await;+ let (first, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ eventually("the agent took it", Duration::from_secs(20), async || status(&host, &bot, &second).await == "sent")+ .await;+ assert_eq!(host.requests(&bot, "session/prompt").len(), 1, "no turn of its own");+ let (first, second) = (entry(&host, &bot, &first).await, entry(&host, &bot, &second).await);+ assert_eq!(second["turn"], first["turn"], "it stays the turn's");+}++#[tokio::test]+async fn a_steered_message_goes_with_its_turn_to_the_next_agent() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Carries", "steer_agent.py", "limit 30").await;+ let standin = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relay_agent.py");+ let standin = format!("{} standin", common::python_agent(&standin));+ let fallbacks = json!([{"backend": "codex", "command": standin}]);+ host.call("updateBot", json!({"id": bot, "fallbacks": fallbacks})).await;+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ let prompt = async || {+ let log = host.log(&bot, "standin.jsonl");+ log.iter().find(|r| r["method"] == "session/prompt").map(|r| r["params"]["prompt"][0]["text"].clone())+ };+ eventually("the next agent took the turn on", Duration::from_secs(30), async || prompt().await.is_some()).await;+ let prompt = prompt().await.unwrap();+ assert!(prompt.as_str().unwrap().contains("first") && prompt.as_str().unwrap().contains("second"), "{prompt}");+ assert_eq!(status(&host, &bot, &second).await, "sent");+}++#[tokio::test]+async fn behind_other_work_a_steered_message_goes_first_in_line() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Behind", "steer_agent.py", "steer 5").await;+ let mut routines = vec![];+ for name in ["The running routine", "The waiting routine"] {+ let body = json!({"botId": bot, "name": name, "instruction": name, "triggers": [{"type": "webhook"}], "timeoutSeconds": 60});+ routines.push(host.call("saveRoutine", body).await["routine"]["id"].as_str().unwrap().to_owned());+ }+ host.call("runRoutine", json!({"botId": bot, "id": routines[0]})).await;+ eventually("the routine's turn runs", Duration::from_mins(1), async || {+ host.requests(&bot, "session/prompt").len() == 1+ })+ .await;+ host.call("runRoutine", json!({"botId": bot, "id": routines[1]})).await;+ let second = host.call("send", json!({"botId": bot, "text": "second"})).await["entry"].clone();+ assert_eq!(second["data"]["status"], "queued");+ host.call("steer", json!({"botId": bot, "entryId": second["id"]})).await;+ eventually("all three had their turns", Duration::from_secs(30), async || {+ host.requests(&bot, "session/prompt").len() == 3+ })+ .await;++ let prompts: Vec<String> =+ host.requests(&bot, "session/prompt").iter().map(|r| r["params"]["prompt"][0]["text"].to_string()).collect();+ for (prompt, said) in prompts.iter().zip(["The running routine", "second", "The waiting routine"]) {+ assert!(prompt.contains(said), "{said}: {prompts:?}");+ }+ assert_eq!(host.requests(&bot, "_session/steering"), Vec::<Value>::new(), "not the user's turn to join");+ assert_eq!(host.requests(&bot, "session/cancel"), Vec::<Value>::new(), "not the user's turn to stop");+}++#[tokio::test]+async fn steering_an_agent_that_cannot_stops_the_turn_for_the_message() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Plain", "steer_agent.py", "plain 30").await;+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ eventually("the message started its own turn", Duration::from_secs(20), async || {+ host.requests(&bot, "session/prompt").len() == 2+ })+ .await;+ assert_eq!(host.requests(&bot, "_session/steering"), Vec::<Value>::new());+ assert_eq!(host.requests(&bot, "session/cancel").len(), 1);+ let prompt = &host.requests(&bot, "session/prompt")[1]["params"]["prompt"][0]["text"];+ assert!(prompt.as_str().unwrap().contains("second"), "{prompt}");+ assert_eq!(status(&host, &bot, &second).await, "sent");+ host.call("stop", json!({"botId": bot})).await;+}++#[tokio::test]+async fn a_message_the_agent_leaves_for_later_is_the_next_turn() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Later", "steer_agent.py", "next 5").await;+ let (first, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ eventually("the message started its own turn", Duration::from_secs(20), async || {+ host.requests(&bot, "session/prompt").len() == 2+ })+ .await;+ assert_eq!(host.requests(&bot, "_session/steering").len(), 1);+ assert_eq!(host.requests(&bot, "session/cancel"), Vec::<Value>::new(), "the first turn ran to its end");+ let prompt = &host.requests(&bot, "session/prompt")[1]["params"]["prompt"][0]["text"];+ assert!(prompt.as_str().unwrap().contains("second"), "{prompt}");+ let (first, second) = (entry(&host, &bot, &first).await, entry(&host, &bot, &second).await);+ assert_eq!(second["data"]["status"], "sent");+ assert_ne!(second["turn"], first["turn"], "a turn of its own");+ host.call("stop", json!({"botId": bot})).await;+}++#[tokio::test]+async fn a_queued_message_taken_back_never_goes_out() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Takes back", "steer_agent.py", "plain 5").await;+ let (first, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("unqueue", json!({"botId": bot, "entryId": second})).await;+ eventually("the roster stopped previewing it", Duration::from_secs(20), async || {+ !common::bot(&host.snapshot().await, &bot)["lastMessage"].as_str().unwrap().contains("second")+ })+ .await;+ eventually("the first turn ended", Duration::from_secs(20), async || idle(&host, &bot).await).await;+ tokio::time::sleep(Duration::from_millis(500)).await;++ assert_eq!(host.requests(&bot, "session/prompt").len(), 1, "the second never went out");+ let removed = entry(&host, &bot, &second).await;+ assert_eq!(removed["data"]["status"], "cancelled");+ assert_eq!(removed["data"]["removed"], true);+ // Only a message still waiting can be steered or taken back.+ for method in ["steer", "unqueue"] {+ for id in [&first, &second] {+ let error = host.refused(method, json!({"botId": bot, "entryId": id})).await;+ assert!(error.contains("isn't waiting"), "{method} {id}: {error}");+ }+ }+}++#[tokio::test]+async fn a_message_taken_back_while_the_agent_decides_goes_unless_the_agent_took_it() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ // The agent answers each steer a second later: it leaves one for later, and takes the other.+ let (left, taken) = (+ host.fixture_bot("Leaves it", "steer_agent.py", "next 30 1").await,+ host.fixture_bot("Takes it", "steer_agent.py", "steer 30 1").await,+ );+ let (_, gone) = queue_behind_a_turn(&host, &left).await;+ let (_, joined) = queue_behind_a_turn(&host, &taken).await;+ for (bot, id) in [(&left, &gone), (&taken, &joined)] {+ host.call("steer", json!({"botId": bot, "entryId": id})).await;+ host.call("unqueue", json!({"botId": bot, "entryId": id})).await;+ }+ eventually("the agent left it, and it went", Duration::from_secs(20), async || {+ entry(&host, &left, &gone).await["data"]["removed"] == true+ })+ .await;+ eventually("the agent took the other", Duration::from_secs(20), async || {+ status(&host, &taken, &joined).await == "sent"+ })+ .await;+ assert_eq!(status(&host, &left, &gone).await, "cancelled");+ assert_eq!(entry(&host, &taken, &joined).await["data"]["removed"], Value::Null, "the chat shows it again");+ host.call("stop", json!({"botId": left})).await;+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert_eq!(host.requests(&left, "session/prompt").len(), 1, "it never went out");+}diff --git a/host/tests/turns_e2e.rs b/host/tests/turns_e2e.rsindex a5f4dbfe..320413af 100644--- a/host/tests/turns_e2e.rs+++ b/host/tests/turns_e2e.rs@@ -8,7 +8,7 @@ mod common;use serde_json::{Value, json};use std::path::PathBuf;-use std::process::{Child, Command};+use std::process::Child;use std::time::{Duration, Instant};struct Host {@@ -91,17 +91,9 @@ impl Host {}}-fn python_missing() -> bool {- let missing = Command::new(common::python()).arg("--version").output().is_err();- if missing {- eprintln!("skipping: Python not available");- }- missing-}-#[tokio::test]async fn stop_ends_a_turn_whose_agent_ignores_the_cancel() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -117,7 +109,7 @@ async fn stop_ends_a_turn_whose_agent_ignores_the_cancel() {#[tokio::test]async fn a_member_busy_elsewhere_answers_only_the_latest_room_turn() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -156,7 +148,7 @@ async fn a_member_busy_elsewhere_answers_only_the_latest_room_turn() {#[tokio::test]async fn a_reaction_can_be_the_whole_reply() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -221,7 +213,7 @@ const FAST_OFF: &str = r#""configId": "fast", "value": "off""#;#[tokio::test]async fn fast_mode_switches_live_sessions_without_a_restart() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -250,7 +242,7 @@ async fn fast_mode_switches_live_sessions_without_a_restart() {#[tokio::test]async fn an_agent_without_config_options_has_no_fast_mode() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -267,7 +259,7 @@ async fn an_agent_without_config_options_has_no_fast_mode() {#[tokio::test]async fn a_refused_fast_mode_is_reported_and_not_asked_for_again() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -299,7 +291,7 @@ async fn a_refused_fast_mode_is_reported_and_not_asked_for_again() {#[tokio::test]async fn a_new_bot_works_in_its_agents_auto_mode_until_the_user_picks_another() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -341,7 +333,7 @@ async fn a_new_bot_works_in_its_agents_auto_mode_until_the_user_picks_another()#[tokio::test]async fn a_mode_switch_leaves_fast_mode_to_its_own() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -359,7 +351,7 @@ async fn a_mode_switch_leaves_fast_mode_to_its_own() {#[tokio::test]async fn a_bot_never_works_in_a_mode_its_agent_refused_to_switch_to() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -386,7 +378,7 @@ async fn a_bot_never_works_in_a_mode_its_agent_refused_to_switch_to() {#[tokio::test]async fn a_session_that_ended_in_the_agent_is_closed_and_loaded_again() {- if python_missing() {+ if common::python_missing() {return;}let host = Host::start().await;@@ -405,7 +397,7 @@ async fn a_session_that_ended_in_the_agent_is_closed_and_loaded_again() {#[tokio::test]async fn reasoning_is_per_bot_and_applies_with_default_and_legacy_models() {- if python_missing() {+ if common::python_missing() {return;}let mut host = Host::start().await;diff --git a/web/app/components/live-phone/screens.tsx b/web/app/components/live-phone/screens.tsxindex b07cad13..a3065bf3 100644--- a/web/app/components/live-phone/screens.tsx+++ b/web/app/components/live-phone/screens.tsx@@ -320,11 +320,6 @@ function Row({ entry, prev, chats, respond }: { entry: Entry; prev?: Entry; chat<p className="rounded-[22px] px-[16px] py-[10px] text-[17px] leading-[22px] whitespace-pre-wrap" style={{ background: palette.bubbleUser, color: palette.text }}>{entry.text}</p>- {entry.queued && (- <span className="text-[11px]" style={{ color: palette.tertiary }}>- Queued until this response finishes- </span>- )}</div>);case "agent": {diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex b2852b90..435dd892 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -24,7 +24,12 @@ Type in the box at the bottom and send.Each chat keeps its own draft on each device, and the draft comes back when you return to the chat or reopen the app. Drafts aren't synced between devices.-**While the bot works**, the box reads "Queue a message for" followed by the bot's name. Messages you send then show **Queued until this response finishes**, and they reach the agent together as its next turn.+**While the bot works**, the box reads "Queue a message for" followed by the bot's name. Messages you send then wait in a list just above the box, and they reach the agent together as its next turn. Each waiting message has two buttons:++- **Send now** (the turning arrow) hands it to the bot right away. Claude, Codex and omp bots take it into the reply they're working on, which then answers it too; with other agents, that reply stops and the bot starts on your message. While the bot is busy with something else, such as a routine, a group or another bot's request, the message goes first in line.+- **Remove** (the trash can) takes it back: it never reaches the bot.++In the terminal, the waiting messages show above the input; press `esc`, then `S` to send the oldest one now or `D` to take back the newest.**When the computer is offline**, the iPhone can still take a text message: it shows **Waiting for the computer to come online** and goes out when the computer is back. It waits in the Codync relay, encrypted for your computer, for up to 24 hours; after that it shows **Failed to send**. Tap the cancel button beside it to take it back. A message with files can't wait; its send button stays off until the computer is online.