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
fix(apps): keep queued messages in order and stop agents with the host
leepokai101347dbd912
diff --git a/.agents/skills/after-change/SKILL.md b/.agents/skills/after-change/SKILL.mdindex 30eb5e1f..87e0d084 100644--- a/.agents/skills/after-change/SKILL.md+++ b/.agents/skills/after-change/SKILL.md@@ -68,6 +68,6 @@ Report:- E2E: each check's platform, flow, result and evidence; checks not run and why.- Next: readiness to commit, any unresolved failures or material skipped fixes, and any task-owned processes still running.-Do not label missing validation as passed. Follow the existing task's commit/merge/push authorization and the repository's handoff rules; the skill itself does not authorize publishing unrelated work. Only the coordinator performs git handoff.+Do not label missing validation as passed. Follow the existing task's commit/merge/push authorization and the repository's handoff rules; the skill itself does not authorize publishing unrelated work. Only the coordinator performs git handoff. Passing on the worktree is enough, even when `dev` has moved on: a rebase needs only its conflicts resolved and what they touched still building.Keep the change's development app running through review and until its merge is successfully pushed. On merge/push failure, preserve the worktree and its app. After successful push, stop the task-owned app, Vite and sandbox host, verify they exited, leave the worktree, and follow the clean-code guide's worktree/sandbox cleanup. Confirm the worktree contains no unmerged or other agents' work before removal; never remove the shared checkout. Stop other temporary processes you started when no longer needed.diff --git a/.claude/workflows/after-change.js b/.claude/workflows/after-change.jsindex ee515c25..b596ee09 100644--- a/.claude/workflows/after-change.js+++ b/.claude/workflows/after-change.js@@ -139,5 +139,5 @@ return {review: { found: found.length, confirmed, refuted },fix: { refactors, ...fixed },e2e: { checks, fix: e2eFix },- next: 'Unless an e2e check failed or a skipped fix matters: commit in this worktree, rebase on origin/dev, fast-forward dev, push origin dev, pull dev in the main checkout. Only once that merge is pushed (never before, and not at all if the merge or push fails): stop this worktree\'s `npm run dev` (its Vite, Electron app and sandbox host) and check none of it remains, then leave the worktree and, from the main checkout, delete it: `git worktree remove --force <worktree>`, `git branch -D <branch>`, then `npm run dev -- --prune` in apps/desktop (it also deletes the worktree\'s simulator).',+ next: 'Unless an e2e check failed or a skipped fix matters: commit in this worktree, rebase on origin/dev (passing on the worktree is enough, even when dev has moved on: a rebase needs only its conflicts resolved and what they touched still building), fast-forward dev, push origin dev, pull dev in the main checkout. Only once that merge is pushed (never before, and not at all if the merge or push fails): stop this worktree\'s `npm run dev` (its Vite, Electron app and sandbox host) and check none of it remains, then leave the worktree and, from the main checkout, delete it: `git worktree remove --force <worktree>`, `git branch -D <branch>`, then `npm run dev -- --prune` in apps/desktop (it also deletes the worktree\'s simulator).',}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 73b9084f..f52d783e 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,7 +66,7 @@ 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`). */+ /** Queued messages taken back here, by the `rev` they had; the state leaves them out 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. */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 5a535fbc..9d2de40e 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@@ -168,21 +168,19 @@ internal fun AppStore.steer(entry: Entry) = command("steer", body("botId" to ent/** 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())+ mutableState.update { it.copy(entries = withRemovals(it.entries, pendingRemovals)) }command("unqueue", body("botId" to entry.botId, "entryId" to entry.id), "unqueue:" + entry.id, onFailure = {pendingRemovals.remove(entry.id)- show(entry)+ contextScope.launch { refresh() }})}-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). */+/** [entries] as the screens read them, without the messages taken back: for good once the computer says so (the mirror keeps+ * its copy, for its rev guard), and those [pending] (with the `rev` each had) until its newer copy says what became of them+ * (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 }+ entries.filterNot { it.isRemoved || pending[it.id] == it.rev }/** 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/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.ktindex 6aeb669f..5aaf479d 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@@ -118,7 +118,7 @@ import com.kyant.shapes.Capsuleelse 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 },- queued = queuedMessages(state.entries.filter { it.botId == bot.id && it.isChat }.hidingCalls(), bot.isWorking))+ queued = queuedMessages(state.chatEntries(bot), bot.isWorking))}}) {Transcript(bot, chatState, store, connect, PaddingValues(start = 16.dp, end = 16.dp, top = top + 60.dp,@@ -198,12 +198,14 @@ import com.kyant.shapes.Capsule}}+/** [bot]'s chat. What voice calls carried shows in each call's conversation instead. */+private fun AppState.chatEntries(bot: Bot) = entries.filter { it.botId == bot.id && it.isChat }.hidingCalls()+/** The messages: all this phone has, earlier ones from the computer near the top, following the newest. */@Composable private fun Transcript(bot: Bot, state: AppState, store: AppStore, connect: ConnectionRequestActions, padding: PaddingValues,indicatorTop: Dp, openRoutine: (String) -> Unit, reply: (Entry) -> Unit, addFallback: (Bot) -> Unit, openArtifact: (OpenArtifact) -> Unit,openCall: (String) -> Unit, openPeer: (String) -> Unit) {- // What voice calls carried shows in each call's conversation, not in the chat.- val entries = state.entries.filter { it.botId == bot.id && it.isChat }.hidingCalls()+ val entries = state.chatEntries(bot)// 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) }// Messages waiting behind the bot's work show above the composer instead.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 b3ce2d4e..3d24cfcf 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 = traceTurns(all)+ val turns = all.groupBy { it.turn }.toSortedMap().toList()// The running turn's thoughts start unfolded.val running = runningTurn(all, bot.isWorking(bot.id))val list = rememberLazyListState()@@ -55,14 +55,9 @@ import kotlinx.serialization.json.jsonPrimitive}}-/** 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. */+/** The turn running now while the bot works in this chat; a queued message already holds the next turn. */internal fun runningTurn(entries: List<Entry>, working: Boolean): Long? =- if (working) entries.filter { it.status != "queued" && !it.isRemoved }.maxOfOrNull { it.turn } else null+ if (working) entries.filter { it.status != "queued" }.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.ktindex be3ff753..cb58216d 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt@@ -8,35 +8,36 @@ import org.junit.Assert.assertEqualsimport org.junit.Testclass QueuedMessagesTest {- private fun user(id: String, seq: Long, status: String = "sent", nonce: String? = null, removed: Boolean = false) =+ private fun user(id: String, seq: Long, status: String = "sent", nonce: String? = null) =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))+ val chat = listOf(user("later", 3, "queued"), user("sent", 1), user("first", 2, "queued"))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 }+ @Test fun `the chat leaves out what waits above the composer`() {+ val entries = listOf(user("sent", 1), user("waiting", 2, "queued"))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`() {+ @Test fun `a message taken back is gone 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)+ assertEquals(emptyList<Entry>(), withRemovals(listOf(waiting), mapOf("waiting" to waiting.rev)))// 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)))+ // The computer took it back too: gone for good.+ val removed = waiting.copy(rev = waiting.rev + 1, data = buildJsonObject { put("status", "cancelled"); put("removed", true) })+ assertEquals(emptyList<Entry>(), withRemovals(listOf(removed), emptyMap()))}@Test fun `a send that waits on the computer doesn't show again as this phone's`() {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 e8abdd20..903f4734 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,9 +20,6 @@ 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 bf78cd09..d0d00636 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@@ -36,12 +36,12 @@ data class Entry(/** 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 isQueued: Boolean get() = kind == "user" && status == "queued"+ /** A queued message the user took back (`unqueue`): the app's state leaves it out (`withRemovals`). */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() = !isRemoved && kind in listOf("user", "permission") ||+ val isChat: Boolean get() = 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/test/kotlin/com/codync/android/core/ConversationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.ktindex 4cb1a32f..00ae8203 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@@ -69,18 +69,12 @@ 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) })+ @Test fun `a queued message waits above the composer`() {+ fun user(status: String) = Entry("u", 1, "b", rev = 1, kind = "user", data = buildJsonObject { put("text", "hi"); put("status", status) })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`() {diff --git a/apps/desktop/e2e/call-conversation.spec.ts b/apps/desktop/e2e/call-conversation.spec.tsindex 22ee62d4..ab976b03 100644--- a/apps/desktop/e2e/call-conversation.spec.ts+++ b/apps/desktop/e2e/call-conversation.spec.ts@@ -1,23 +1,7 @@import { test, expect, type Page } from '@playwright/test'import { randomUUID } from 'node:crypto'import { tmpdir } from 'node:os'-import type { HostSnapshot } from '../src/shared/ipc.ts'-import { attach } from './sandbox.ts'--type Host = {- snapshot(): Promise<HostSnapshot>- call(baseURL: string, token: string, method: string, body: unknown, timeoutMs: number): Promise<unknown>-}--/** POST /api/<method> on the sandbox host, through the bridge the renderer uses. */-function api<T>(page: Page, method: string, body: unknown): Promise<T> {- return page.evaluate(async ([method, body]) => {- const host = (window as unknown as { codync: { host: Host } }).codync.host- const local = (await host.snapshot()).local- if (!local) throw new Error('The sandbox host has not answered yet.')- return host.call(local.baseURL, local.token, method, body, 30_000)- }, [method, body] as const) as Promise<T>-}+import { api, attach } from './sandbox.ts'/** A call the host has ended, with what was said on it, as its line in the chat. */async function endedCall(page: Page, botId: string, seconds: number, said: ['user' | 'voice', string][]) {diff --git a/apps/desktop/e2e/queue.spec.ts b/apps/desktop/e2e/queue.spec.tsindex 4684a8c1..7aa51c52 100644--- a/apps/desktop/e2e/queue.spec.ts+++ b/apps/desktop/e2e/queue.spec.ts@@ -1,29 +1,16 @@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 { resolve } from 'node:path'import { canSteer } from '../src/renderer/views/thread/queued-messages.ts'-import { attach, sandbox } from './sandbox.ts'+import { api, attach } 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-}+type History = { entries: { kind: string; data: { text?: string; status?: string } }[] }/** 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 })+async function started(page: Page, botId: string, text: string): Promise<boolean> {+ const { entries } = await api<History>(page, 'history', { botId })return entries.some((e) => e.kind === 'user' && e.data.text === text && e.data.status === 'sent')}@@ -33,20 +20,22 @@ async function type(page: Page, text: string) {}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,- })+ let botId: string | undefinedtry {+ const { version } = await api<{ version: string }>(page, 'hello', {})+ test.skip(!canSteer(version), `the sandbox host (${version}) can't steer yet`)+ const { bot } = await api<{ bot: { id: string } }>(page, 'createBot', {+ name, backend: 'custom', command: `python3 -X utf8 -u '${agent}' steer 30`, connectors: [], skills: [], notify: false,+ })+ botId = bot.idawait 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 api(page, 'send', { botId, text: 'first' })+ await expect.poll(() => started(page, bot.id, 'first')).toBe(true)await type(page, 'second')await expect(queued.filter({ hasText: 'second' })).toBeVisible()await expect(transcript).not.toContainText('second')@@ -56,17 +45,19 @@ test('a message sent while the bot works waits above the composer, then goes outawait 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 api(page, 'send', { botId, text: 'third' })+ await expect.poll(() => started(page, 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)+ const { entries } = await api<History>(page, 'history', { botId })+ expect(entries.find((e) => e.data.text === 'never sent')).toBeUndefined()} finally {- await host('stop', { botId: bot.id }).catch(() => {})- await host('deleteBot', { botId: bot.id }).catch(() => {})+ if (botId) {+ await api(page, 'stop', { botId }).catch(() => {})+ await api(page, 'deleteBot', { botId }).catch(() => {})+ }await browser.close()}})diff --git a/apps/desktop/e2e/sandbox.ts b/apps/desktop/e2e/sandbox.tsindex 859b777c..fff77f77 100644--- a/apps/desktop/e2e/sandbox.ts+++ b/apps/desktop/e2e/sandbox.ts@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs'import { homedir } from 'node:os'import { basename, join, resolve } from 'node:path'import { SANDBOX_PREFIX, sandboxName } from '../src/shared/dev-sandbox.ts'+import type { HostSnapshot } from '../src/shared/ipc.ts'// Playwright loads specs as CommonJS here (the package has no "type": "module").const root = resolve(__dirname, '../../..')@@ -33,3 +34,18 @@ export async function attach(): Promise<{ browser: Browser; page: Page }> {if (!page) throw new Error('The sandbox app has no window open.')return { browser, page }}++type Host = {+ snapshot(): Promise<HostSnapshot>+ call(baseURL: string, token: string, method: string, body: unknown, timeoutMs: number): Promise<unknown>+}++/** POST /api/<method> on the sandbox host, through the bridge the renderer uses. */+export function api<T>(page: Page, method: string, body: unknown): Promise<T> {+ return page.evaluate(async ([method, body]) => {+ const host = (window as unknown as { codync: { host: Host } }).codync.host+ const local = (await host.snapshot()).local+ if (!local) throw new Error('The sandbox host has not answered yet.')+ return host.call(local.baseURL, local.token, method, body, 30_000)+ }, [method, body] as const) as Promise<T>+}diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.tsindex d03ac0f4..790ee1dd 100644--- a/apps/desktop/src/renderer/store/bot-mirror.ts+++ b/apps/desktop/src/renderer/store/bot-mirror.ts@@ -10,6 +10,7 @@ import {type PairingRequest,type ScreenState,type Usage,+ withoutRemoved,} from '@shared/models'import type { NetworkView, RecoveryCode } from '@shared/network'import type { HostClient, HostRoute, HostTransport } from '../client/host-client'@@ -209,7 +210,8 @@ export class BotMirror extends Observable {/** A bot's or group's chat, trace entries included. */allEntries(botId: string) {- return this.entries.get(botId) ?? []+ const list = this.entries.get(botId)+ return list ? withoutRemoved(list) : []}canLoadOlder(botId: string) {diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex f6d1ed4d..b68db17b 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -112,17 +112,21 @@ export class BotStore extends BotSync {const files = (entry.data.clientNonce && this.outgoingFiles.get(entry.data.clientNonce)) || []const text = entry.data.text ?? ''if (!text && !files.length) return- this.entries.set(entry.botId, this.allEntries(entry.botId).filter((e) => e.id !== entry.id))+ this.dropEntry(entry)this.send(text, entry.botId, { files, nonce: entry.data.clientNonce, replyTo: entry.data.replyTo })}discard(entry: Entry) {if (entry.data.clientNonce) this.outgoingFiles.delete(entry.data.clientNonce)- this.entries.set(entry.botId, this.allEntries(entry.botId).filter((e) => e.id !== entry.id))+ this.dropEntry(entry)this.changed()this.scheduleSave()}+ private dropEntry(entry: Entry) {+ this.entries.set(entry.botId, (this.entries.get(entry.botId) ?? []).filter((e) => e.id !== entry.id))+ }+private markLocal(nonce: string, botId: string, status: string) {const list = this.entries.get(botId)const i = list?.findIndex((e) => e.id === `local-${nonce}`) ?? -1diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.tsindex 3b0b9632..046dd555 100644--- a/apps/desktop/src/renderer/store/bot-sync.ts+++ b/apps/desktop/src/renderer/store/bot-sync.ts@@ -336,7 +336,7 @@ export class BotSync extends BotMirror {}private isBelowFloor(e: Entry) {- const held = this.allEntries(e.botId).some((x) => x.id === e.id)+ const held = !!this.entries.get(e.botId)?.some((x) => x.id === e.id)return isOutsideLoadedWindow(this.floors.get(e.botId), held, e)}diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsxindex 7a765f4c..78b1a7b4 100644--- a/apps/desktop/src/renderer/views/thread/Composer.tsx+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx@@ -327,7 +327,7 @@ function DestinationComposer({ botId, reply, about, cancelReply, onCall, onInter}/** Keep the outgoing row until its height/fade transition finishes. */-function ComposerReveal({ open, children }: { open: boolean; children: ReactNode }) {+export function ComposerReveal({ open, children }: { open: boolean; children: ReactNode }) {const { mounted, shown } = usePresence(open)const last = useRef(children)if (open) last.current = childrendiff --git a/apps/desktop/src/renderer/views/thread/QueuedMessages.tsx b/apps/desktop/src/renderer/views/thread/QueuedMessages.tsxindex 3e093647..652a2aa0 100644--- a/apps/desktop/src/renderer/views/thread/QueuedMessages.tsx+++ b/apps/desktop/src/renderer/views/thread/QueuedMessages.tsx@@ -8,6 +8,7 @@ import { Text } from '../../components/Text'import { afterExit } from '../../lib/exit-delay'import { messagePreview } from '../../lib/message-preview'import { useStore } from '../../store/context'+import { ComposerReveal } from './Composer'import { canSteer, waitingMessages } from './queued-messages'import './queued-messages.css'@@ -40,11 +41,10 @@ export function QueuedMessages({ botId }: { botId: string }) {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>+ <div className="queued-row" role="listitem">+ <ComposerReveal open={!leaving}><HStack gap={2} className="queued-row-body"><Text size="callout" tone="secondary" truncate grow>{messagePreview(quoteOf(entry).text)}</Text>{actions ? (@@ -54,7 +54,7 @@ function QueuedRow({ entry, leaving, actions }: { entry: Entry; leaving: boolean</>) : null}</HStack>- </div>+ </ComposerReveal></div>)}diff --git a/apps/desktop/src/renderer/views/thread/queued-messages.css b/apps/desktop/src/renderer/views/thread/queued-messages.cssindex 74c5416d..120e48e1 100644--- a/apps/desktop/src/renderer/views/thread/queued-messages.css+++ b/apps/desktop/src/renderer/views/thread/queued-messages.css@@ -26,20 +26,6 @@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.tsindex 081a56ea..edc7ecd7 100644--- a/apps/desktop/src/renderer/views/thread/queued-messages.test.ts+++ b/apps/desktop/src/renderer/views/thread/queued-messages.test.ts@@ -1,7 +1,7 @@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'+import { withoutRemoved, 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,@@ -19,9 +19,10 @@ test('an idle bot takes its next message at once: the chat keeps it and the queuassert.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('a message taken back is gone from what the views read, in one array per list', () => {+ const list = [user('removed', 'cancelled', { removed: true }), user('stopped', 'cancelled')]+ assert.deepEqual(withoutRemoved(list).map((e) => e.id), ['stopped'], 'one Stop dropped still says it wasn’t sent')+ assert.equal(withoutRemoved(list), withoutRemoved(list))})test('only a host that steers gets the queue’s buttons', () => {diff --git a/apps/desktop/src/renderer/views/thread/queued-messages.ts b/apps/desktop/src/renderer/views/thread/queued-messages.tsindex 177b3f36..d02e1354 100644--- a/apps/desktop/src/renderer/views/thread/queued-messages.ts+++ b/apps/desktop/src/renderer/views/thread/queued-messages.ts@@ -2,7 +2,7 @@ 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'+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 {diff --git a/apps/desktop/src/renderer/views/thread/trace-turns.test.ts b/apps/desktop/src/renderer/views/thread/trace-turns.test.tsindex 77eb2db3..b3c4b113 100644--- a/apps/desktop/src/renderer/views/thread/trace-turns.test.ts+++ b/apps/desktop/src/renderer/views/thread/trace-turns.test.ts@@ -37,13 +37,6 @@ 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 dfb80094..9565e5cc 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; one taken back from the queue never had a turn. */+/** A bot's entries grouped by turn, oldest turn first, each turn's entries in their order. */export function traceTurns(entries: Entry[]): [number, Entry[]][] {const turns = new Map<number, Entry[]>()- for (const e of entries) if (!e.data.removed) turns.set(e.turn, [...(turns.get(e.turn) ?? []), e])+ for (const e of entries) 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 (or one taken back) holds the next turn. */+/** The turn running now while the bot works in this chat; a queued message already 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' || e.data.removed ? t : Math.max(t, e.turn)), -1)+ return entries.reduce((t, e) => (e.data.status === 'queued' ? 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 6bc8b260..02ec3f2e 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -308,7 +308,7 @@ 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. */+ /** user: taken back from the queue before it went out (`unqueue`); no view reads it (`withoutRemoved`). */removed?: booleanclientNonce?: stringtitle?: string@@ -360,12 +360,25 @@ export interface Entry {updatedAt: number}+const shownOf = new WeakMap<Entry[], Entry[]>()++/**+ * `list` as the views read it, without the messages taken back (`unqueue`): the store keeps those for its rev guard+ * against a late response. One array per list, because the chat's memos depend on its identity.+ */+export function withoutRemoved(list: Entry[]): Entry[] {+ let shown = shownOf.get(list)+ if (!shown) {+ shown = list.filter((e) => !e.data.removed)+ shownOf.set(list, shown)+ }+ return shown+}+/** Chat-visible (Grok Bot model): user messages, final replies, approval cards, notices. */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/Models/Entry+Queue.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+Queue.swiftindex dfecdee6..f5d605b5 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Entry+Queue.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+Queue.swift@@ -2,7 +2,7 @@ import Foundationpublic 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 }+ var isQueued: Bool { kind == "user" && data.status == "queued" }}public extension Array where Element == Entry {diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swiftindex a43c3a29..bf1afd4b 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Entry+WorkingSteps.swift@@ -21,16 +21,9 @@ public extension Entry {return t.isEmpty || t == "(pass)" || t == "pass"}- /// 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.+ /// The turn running now while the bot works in this chat; a queued message already holds the next turn.static func runningTurn(_ entries: [Entry], working: Bool) -> Int64? {- working ? entries.filter { $0.data.status != "queued" && $0.data.removed != true }.map(\.turn).max() : nil+ working ? entries.filter { $0.data.status != "queued" }.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 28d90d2d..3d34e8b2 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -21,7 +21,7 @@ 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.+ /// user: taken back while it waited (`unqueue`): it never went out, and no view reads it (`BotStore.chat`).public var removed: Bool?public var clientNonce: String?public var title: String?diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex 2ffec4b7..c0328fb9 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -40,8 +40,7 @@ public struct Entry: Codable, Identifiable, Hashable, Sendable {/// conversation going, and a kept handoff changed nothing.public var isChat: Bool {switch kind {- case "user": data.removed != true- case "permission": true+ case "user", "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 58cc6f2a..8888a9a4 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "Gib oben einen Namen und eine Anweisung ein, um zu speichern.","Delete routine": "Routine löschen","Queued": "In der Warteschlange",- "Queued until this response finishes": "Wartet, bis diese Antwort fertig ist","Routine · {name}": "Routine · {name}","Tool": "Werkzeug","Turn {turn}": "Runde {turn}",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 49db6b2b..afaa748d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "Introduce un nombre y una instrucción arriba para guardar.","Delete routine": "Eliminar rutina","Queued": "En cola",- "Queued until this response finishes": "En espera de que termine esta respuesta","Routine · {name}": "Rutina · {name}","Tool": "Herramienta","Turn {turn}": "Turno {turn}",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 7528ef85..d80d7963 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "Saisissez un nom et une instruction ci-dessus pour enregistrer.","Delete routine": "Supprimer la routine","Queued": "En file d’attente",- "Queued until this response finishes": "En attente de la fin de cette réponse","Routine · {name}": "Routine · {name}","Tool": "Outil","Turn {turn}": "Tour {turn}",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex e84d0664..49accab1 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "上に名前と保存する手順を入力します。","Delete routine": "ルーチンの削除","Queued": "待機中",- "Queued until this response finishes": "この返信が終わるまで待機","Routine · {name}": "ルーティン · {name}","Tool": "ツール","Turn {turn}": "{turn} ターン目",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 57c49bf7..1cbf3d85 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "저장하려면 위에 이름과 지침을 입력하세요.","Delete routine": "루틴 삭제","Queued": "대기 중",- "Queued until this response finishes": "이 응답이 끝날 때까지 대기","Routine · {name}": "루틴 · {name}","Tool": "도구","Turn {turn}": "{turn}번째 턴",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.jsonindex c0c31418..70640618 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "Digite um nome e uma instrução acima para salvar.","Delete routine": "Excluir rotina","Queued": "Na fila",- "Queued until this response finishes": "Na fila até esta resposta terminar","Routine · {name}": "Rotina · {name}","Tool": "Ferramenta","Turn {turn}": "Rodada {turn}",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.jsonindex 5871eca2..9b4edac2 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "Введите название и инструкцию выше, чтобы сохранить.","Delete routine": "Удалить рутину","Queued": "В очереди",- "Queued until this response finishes": "В очереди до завершения этого ответа","Routine · {name}": "Рутина · {name}","Tool": "Инструмент","Turn {turn}": "Ход {turn}",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 8f380f96..f526152c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "先在上面填写名称和说明,再保存。","Delete routine": "删除例行任务","Queued": "排队中",- "Queued until this response finishes": "等这次回复结束后再发","Routine · {name}": "例行任务 · {name}","Tool": "工具","Turn {turn}": "第 {turn} 轮",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex e0998907..004fe743 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -706,7 +706,6 @@"Enter a name and instruction above to save.": "先在上面填寫名稱和說明,再儲存。","Delete routine": "刪除例行任務","Queued": "排隊中",- "Queued until this response finishes": "等這次回覆結束後再送","Routine · {name}": "例行任務 · {name}","Tool": "工具","Turn {turn}": "第 {turn} 輪",diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex d8e62dc4..d245e46b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -261,7 +261,9 @@ public final class BotStore {public var hiddenBots: [Bot] { bots.values.filter(\.hidden).sorted { $0.name < $1.name } }/// Everything in a bot's or group's chat this device has, oldest first (trace included).- public func chat(_ botId: String) -> [Entry] { entries[botId] ?? [] }+ /// A chat as the views read it. A message taken back (`unqueue`) stays only in `entries`, for `upsert`'s rev guard+ /// against a late response.+ public func chat(_ botId: String) -> [Entry] { (entries[botId] ?? []).filter { $0.data.removed != true } }public func canLoadOlder(_ botId: String) -> Bool {!historyComplete.contains(botId) && chat(botId).contains { $0.seq > 0 && $0.seq != Int64.max }diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swiftindex f583184d..a51cfe21 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swift@@ -11,7 +11,8 @@ public struct TraceView: View {public var body: some View {let all = model.chat(botId)- let turns = Entry.traceTurns(all)+ let turns = Dictionary(grouping: all, by: \.turn)+ .sorted { $0.key < $1.key }// 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.swiftindex b5268a75..66985dd0 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/QueuedMessagesTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/QueuedMessagesTests.swift@@ -12,22 +12,10 @@ private func entry(_ id: String, seq: Int64, turn: Int64, _ json: String) throwstry 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"])+ #expect(entries.queue(working: true).map(\.id) == ["next", "later"], "oldest first")+ #expect(entries.hidingQueue(working: true).map(\.id) == ["asked"])// 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 976a4200..095aa14b 100644--- a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift@@ -182,8 +182,8 @@ private func rosterBot(_ id: String, pinned: Bool = false, lead: Bool = false, hstore.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.chat("b").isEmpty)+ #expect(await until { store.chat("b").first?.isQueued == true })#expect(store.lastError != nil)}diff --git a/apps/maestro/queue.js b/apps/maestro/queue.jsnew file mode 100644index 00000000..20cad010--- /dev/null+++ b/apps/maestro/queue.js@@ -0,0 +1,25 @@+// Makes the bot `queue.yaml` opens and starts its first turn, on the host the phone is paired with (HOST_PORT and+// HOST_TOKEN, passed with `-e`). Its agent is host/tests/fixtures/steer_agent.py (STEER_AGENT, its full path), whose turn+// waits until a steered message joins it. `SEND` instead starts another turn with that text, and `CLEANUP`, when the flow+// completes, deletes the bot again.+const api = (method, body) => {+ const res = http.post(`http://127.0.0.1:${HOST_PORT}/api/${method}`, {+ headers: { Authorization: `Bearer ${HOST_TOKEN}`, 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ })+ if (res.status !== 200) throw new Error(`${method}: ${res.status} ${res.body}`)+ return json(res.body)+}++if (typeof CLEANUP !== 'undefined') {+ if (output.bot) api('deleteBot', { botId: output.bot.id })+} else if (typeof SEND !== 'undefined') {+ api('send', { botId: output.bot.id, text: SEND })+} else {+ const name = `Queue check ${Math.random().toString(36).slice(2, 6)}`+ const bot = api('createBot', {+ name, backend: 'custom', command: `python3 -X utf8 -u '${STEER_AGENT}' steer 120`, connectors: [], skills: [], notify: false,+ }).bot+ api('send', { botId: bot.id, text: 'first' })+ output.bot = { name, id: bot.id }+}diff --git a/apps/maestro/queue.yaml b/apps/maestro/queue.yamlnew file mode 100644index 00000000..d9464e8c--- /dev/null+++ b/apps/maestro/queue.yaml@@ -0,0 +1,49 @@+# A message sent while the bot works waits above the composer: Send now joins the running turn, whose reply answers it,+# and Remove takes it back. The phone must already be signed in and paired with the host (a worktree's sandbox,+# docs/guides/dev-app.md#worktree-sandboxes), so run it apart from `welcome`, whose clearState undoes that; the flow makes+# its own bot there:+# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags composer \+# -e HOST_PORT=<sandbox port> -e HOST_TOKEN="$(cat ~/.codync-dev-<sandbox name>/token)" \+# -e STEER_AGENT="$PWD/host/tests/fixtures/steer_agent.py" apps/maestro+appId: com.pokai.Codync.ios.dev+tags:+ - composer+onFlowComplete:+ - runScript:+ file: queue.js+ env:+ CLEANUP: "true"+---+- runScript: queue.js+- runFlow:+ when:+ platform: iOS+ commands:+ - launchApp:+ appId: com.pokai.Codync.ios.dev+- runFlow:+ when:+ platform: Android+ commands:+ - launchApp:+ appId: com.pokai.Codync.android.dev+- tapOn: ${output.bot.name}+- tapOn: "Queue a message for.*"+- inputText: "second"+- tapOn: "Send"+- assertVisible: "second"+- takeScreenshot: queue-waiting+- tapOn: "Send now"+- assertNotVisible: "Send now"+- assertVisible: "Got: .*"+- runScript:+ file: queue.js+ env:+ SEND: "third"+- tapOn: "Queue a message for.*"+- inputText: "never sent"+- tapOn: "Send"+- assertVisible: "never sent"+- tapOn: "Remove"+- assertNotVisible: "never sent"+- assertNotVisible: "Remove"diff --git a/cloud/test/e2e/relay.e2e.ts b/cloud/test/e2e/relay.e2e.tsindex 31dcc7e5..bedf9e70 100644--- a/cloud/test/e2e/relay.e2e.ts+++ b/cloud/test/e2e/relay.e2e.ts@@ -129,6 +129,7 @@ async function startHost() {CODYNC_HOME: home,CODYNC_CLOUD_URL: CLOUD,CODYNC_DEVICE_CERT_KEY: certPub,+ CODYNC_AGENT_CHECKS: "off",});await waitFor("host /health", () => fetch(`http://127.0.0.1:${hostPort}/health`).then((r) => r.ok || undefined).catch(() => undefined), 30_000);}diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex a1a8b202..1d8b44be 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -92,7 +92,7 @@ Codync/| CLI and background service | `host/src/main.rs`, `service/`; subcommands `cloud_cli.rs`, `network_cli.rs`, `send_cli.rs` (+ `send_cli/events.rs`, `wait.rs`) || API, caller permissions, event ordering | `host/src/api/`, `hub.rs` || SQLite transcript, bots, lanes and sessions | `host/src/store/` (`entries.rs`, `bots.rs`, `model.rs`, `devices.rs`, `schema.rs`) |-| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`; `codex_names.rs` / `pi_tools.rs` how Codex and pi get Codync's MCP servers), `acp.rs` (+ `acp/codebuddy.rs`, CodeBuddy's ACP extensions), `process.rs` (process-tree ownership; `process_windows.rs` on Windows) |+| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `steer.rs`, `turn.rs`, `updates.rs`; `codex_names.rs` / `pi_tools.rs` how Codex and pi get Codync's MCP servers), `acp.rs` (+ `acp/codebuddy.rs`, CodeBuddy's ACP extensions), `process.rs` (process-tree ownership; `process_windows.rs` on Windows) || Compaction timing and rollover | `host/src/agent/bot/compaction.rs`, the handoff card in `host/src/chat/handoff.rs`; the rules in `codync-mem`'s `compaction.rs` || Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` || Voice calls (the call, the voice's instructions and tools, transcripts, call lines) | `host/src/chat/calls/` (`mod.rs`, `context.rs`, `project.rs` the git state, `tools.rs`, `announce.rs` what the voice hears while the call lasts, `speech.rs` text as a voice says it); the user's messages it relays go through `host/src/chat/messages.rs` like typed ones; clients' `CallLink` (iPhone `CodyncUI/Call/CallLink.swift`, desktop `views/call/call-link.ts`, Android `core/Calls.kt` + `HostCallLink.kt`) and call rows (`CallRows`); the call on the iPhone's Lock Screen (`CodyncUI/Call/CallActivity.swift`, the Live Activity) and Android's call notification (`VoiceService.kt`) |diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.mdindex 8ac85008..fda4cd49 100644--- a/docs/features/chat-messages.md+++ b/docs/features/chat-messages.md@@ -18,7 +18,9 @@ it has no pointer tooltip or link-opening action.- The agent's own reply text (`agent_message_chunk`) stays in the trace when the turn senttext through `send_message`. A turn that sent nothing (an agent that ignores the tool, or has no MCP) falls back tothe old rule: its last text becomes the turn's final message, unless that text is `(pass)`: a message that- needs neither words nor a reaction gets nothing, as in a group.+ needs neither words nor a reaction gets nothing, as in a group. In a turn a steered message joined, what the agent+ wrote after its last `send_message` or reaction becomes a final message too, since either may have answered only+ what came before that message.- File cards are separate final entries. Sharing a file preserves an intended final textreply; a files-only turn uses its filename for the completion summary. See[file attachments](file-attachments.md#files-from-a-bot). Artifact cards (`publish_artifact`) are final entries thediff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex b3fee89a..581696a9 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -191,8 +191,8 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/melines. *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`).+ another bot's request it goes first in line. *Remove* (`unqueue`) takes it back: it never goes out, its files are+ deleted 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/features/file-attachments.md b/docs/features/file-attachments.mdindex 60ca3d7e..2310e1c9 100644--- a/docs/features/file-attachments.md+++ b/docs/features/file-attachments.md@@ -19,6 +19,8 @@ Files travel in both directions: users attach inputs, and bots explicitly share- The agent gets the message text plus an "Attached files" list of absolute paths and reads them withits own tools (Claude and Codex read images too). The entry keeps `attachments: [{id, name, size}]`for display.+- A queued message taken back (`unqueue`) deletes its uploads: the bot finds nothing of it in its folder, and+ `readUpload` refuses them. A message Stop dropped keeps its files, for the chat's *Not sent* row.- Files don't go through the relay mailbox: while the computer is offline, a message with fileswaits in the composer's send button (disabled) instead. A failed send keeps its files on the devicefor Resend until the app quits.diff --git a/docs/guides/composer.md b/docs/guides/composer.mdindex 6a25435b..bfc4cf0c 100644--- a/docs/guides/composer.md+++ b/docs/guides/composer.md@@ -50,6 +50,19 @@ on one line and an X that cancels (the terminal UI: `↳ “…”`, esc cancelsplaceholder reads "Reply…", and leaving the chat cancels the reply. See[replies](../features/groups-and-replies.md).+## Queued messages++While the bot works anywhere (its own chat, a room, a routine), the user's queued messages leave the transcript and+wait above the box, oldest first, one line each: the desktop's tray tucked under the composer's top edge+(`views/thread/QueuedMessages.tsx`), the phones' card past the + button (`Thread/QueuedMessages.swift`,+`QueuedMessages.kt`), the terminal's band over its input (`view/queue.rs`, at most three rows). An idle bot takes the+next message at once, so the chat keeps showing that one.++Each row has icon-only Send now (`arrow.turn.down.right`) and Remove (`trash`); the terminal has `S` (send the oldest+now) and `D` (take back the newest). A host older than 2.38.1 has neither, so the rows only show. Remove hides the+message at once and brings it back if the host refuses. What each does on the host:+[turns](../features/context-and-memory.md#turns).+## Draft lifetimeText is saved exactly, including leading/trailing whitespace, blank lines and emoji.diff --git a/docs/guides/test-stack.md b/docs/guides/test-stack.mdindex 9f0c0abb..ed758311 100644--- a/docs/guides/test-stack.md+++ b/docs/guides/test-stack.md@@ -4,7 +4,7 @@ How the end-to-end (e2e) checks drive the apps: Playwright for the desktop app,## Host tests-`host/tests` drive real hosts against fake agents (the Python scripts in `tests/fixtures`). `tests/common` starts every test host with `CODYNC_AGENT_CHECKS=off`, so it never runs the computer's agent CLIs for their sign-in and usage checks and never touches your logins. A test of those checks turns them back on (`tests/agent_checks_e2e.rs`).+`host/tests` drive real hosts against fake agents (the Python scripts in `tests/fixtures`). `tests/common` starts every test host with `CODYNC_AGENT_CHECKS=off`, as do `cloud/test/e2e/relay.e2e.ts` and `tools/check-connectors.py`, so it never runs the computer's agent CLIs for their sign-in and usage checks and never touches your logins. A test of those checks turns them back on (`tests/agent_checks_e2e.rs`).Run them one at a time: never start a test binary several times in parallel, or several copies of the suite, not even to hunt a flake. Repeat it one run after another, a few times at most. On 2026-11-04 parallel repeats left about 200 `claude -p /usage` processes behind, using 55 GB on a 32 GB Mac, and froze it.diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rsindex ceb0ec64..25de8969 100644--- a/host/src/agent/acp.rs+++ b/host/src/agent/acp.rs@@ -9,8 +9,8 @@ use anyhow::{Context, Result};use serde_json::{Value, json};use std::collections::{HashMap, VecDeque};use std::process::Stdio;-use std::sync::Arc;use std::sync::atomic::{AtomicI64, Ordering};+use std::sync::{Arc, Weak};use std::time::Duration;use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tokio::process::ChildStdin;@@ -25,6 +25,8 @@ const EXIT_GRACE: Duration = Duration::from_secs(10);/// Agents [`Acp::kill`] is still stopping, for the host to wait for before it exits.static STOPPING: std::sync::Mutex<Vec<tokio::task::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());+/// Every agent started, for the host to stop whichever are left before it exits.+static STARTED: std::sync::Mutex<Vec<Weak<Acp>>> = std::sync::Mutex::new(Vec::new());pub enum Incoming {Notification { method: String, params: Value },@@ -273,6 +275,7 @@ impl Acp {child,pid,});+ note_started(&acp);Ok((acp, rx))}@@ -340,6 +343,20 @@ pub async fn stopped() {futures::future::join_all(tasks).await;}+/// Stops every agent left and waits for them, before the host exits: `process::exit` drops no process, and Cursor's agent+/// outlives its closed stdin. The bots stop their own, so this is for a sign-in check or a model list still under way.+pub async fn stop_all() {+ let started: Vec<_> = std::mem::take(&mut *STARTED.locked()).iter().filter_map(Weak::upgrade).collect();+ futures::future::join_all(started.iter().map(|acp| acp.kill())).await;+ stopped().await;+}++fn note_started(acp: &Arc<Acp>) {+ let mut started = STARTED.locked();+ started.retain(|acp| acp.strong_count() > 0);+ started.push(Arc::downgrade(acp));+}+/// The result for a `session/request_permission`: the option picked, or `cancelled` without one.pub fn permission_answer(option_id: Option<&str>) -> Value {match option_id {@@ -377,158 +394,4 @@ pub fn truncate(s: &str, max: usize) -> String {}#[cfg(test)]-mod tests {- use super::*;-- async fn descendant_agent() -> (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>) {- let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/process_agent.py");- let python = if cfg!(windows) { "python" } else { "python3" };- let command = format!("{python} -u {}", crate::shell::quote(&script.display().to_string()));- let (acp, mut rx) = Acp::spawn(&command, env!("CARGO_MANIFEST_DIR"), &[]).unwrap();- let ready = tokio::time::timeout(Duration::from_secs(15), rx.recv()).await;- let ready = ready.unwrap();- assert!(matches!(ready, Some(Incoming::Notification { method, .. }) if method == "ready"));- (acp, rx)- }-- async fn assert_descendant_pipes_close(mut rx: mpsc::UnboundedReceiver<Incoming>) {- let closed = tokio::time::timeout(Duration::from_secs(5), rx.recv()).await;- let closed = closed.unwrap();- assert!(matches!(closed, Some(Incoming::Closed { .. })));- }-- #[tokio::test]- async fn leader_exit_releases_descendants_without_waiting_for_stdout_eof() {- let (acp, rx) = descendant_agent().await;- let notified = acp.notify("exit", json!({})).await;- notified.unwrap();- assert_descendant_pipes_close(rx).await;- }-- #[tokio::test]- async fn dropping_an_agent_releases_its_process_tree() {- let (acp, rx) = descendant_agent().await;- drop(acp);- assert_descendant_pipes_close(rx).await;- }-- #[tokio::test]- async fn actor_unwinding_releases_its_process_tree() {- let (acp, rx) = descendant_agent().await;- let task = tokio::spawn(async move {- let _owned = acp;- panic!("simulated actor panic");- });- let panicked = task.await;- assert!(panicked.unwrap_err().is_panic());- assert_descendant_pipes_close(rx).await;- }-- #[tokio::test]- async fn timed_out_requests_do_not_accumulate_pending_answers() {- let (acp, rx) = descendant_agent().await;- for _ in 0..10 {- let response = tokio::time::timeout(Duration::from_millis(10), acp.request("never", json!({}))).await;- assert!(response.is_err());- assert_eq!(acp.pending.locked().len(), 0);- }- acp.kill().await;- stopped().await;- assert_descendant_pipes_close(rx).await;- }-- #[cfg(unix)]- #[tokio::test]- async fn a_stopped_agent_that_exits_cleanly_does_not_hold_the_host_for_the_grace_period() {- let (acp, mut rx) = Acp::spawn("cat", env!("CARGO_MANIFEST_DIR"), &[]).unwrap();- let started = tokio::time::Instant::now();- acp.kill().await;- stopped().await;- assert!(started.elapsed() < EXIT_GRACE / 2, "stopping waited out the grace period");- assert!(matches!(rx.recv().await, Some(Incoming::Closed { .. })));- }-- #[test]- fn content_text_flattens_blocks() {- let v = json!([- {"type": "content", "content": {"type": "text", "text": "a"}},- {"type": "diff", "path": "/x"},- {"type": "text", "text": "b"}- ]);- assert_eq!(content_text(&v), "a\nb");- assert_eq!(truncate("héllo", 2), "h…");- }-- #[tokio::test]- async fn an_error_keeps_the_adapters_category_only_when_it_is_an_identifier() {- let kind = |data: Value| async move {- let (tx, rx) = oneshot::channel();- let _ = tx.send(Err(json!({"code": -32603, "message": "Internal error", "data": data})));- let e = Answer { id: 0, pending: Pending::default(), rx: Some(rx) }- .response()- .await- .expect_err("an error answer");- e.downcast::<RpcError>().expect("an RpcError").kind- };- assert_eq!(kind(json!({"errorKind": "rate_limit"})).await.as_deref(), Some("rate_limit"));- assert_eq!(kind(json!({"errorKind": "Usage: /Users/me"})).await, None);- assert_eq!(kind(json!({"errorKind": ""})).await, None);- assert_eq!(kind(json!("details")).await, None);- assert_eq!(- kind(json!({"codexErrorInfo": "usageLimitExceeded"})).await.as_deref(),- Some("usage_limit_exceeded")- );- assert_eq!(- kind(json!({"codexErrorInfo": {"httpConnectionFailed": {"httpStatusCode": 502}}})).await.as_deref(),- Some("http_connection_failed")- );- }-- #[cfg(unix)]- #[tokio::test]- async fn stopping_an_agent_closes_its_descendants_pipes() {- let (acp, mut rx) = Acp::spawn(- r#"sh -c 'sleep 60 & echo "{\"jsonrpc\":\"2.0\",\"method\":\"ready\"}"; read line'"#,- "/tmp",- &[],- )- .unwrap();- let ready = tokio::time::timeout(Duration::from_secs(3), rx.recv()).await.unwrap();- assert!(matches!(ready, Some(Incoming::Notification { .. })));- acp.kill().await;- // Killing only the shell leaves sleep holding stdout for 60 seconds.- let closed = tokio::time::timeout(EXIT_GRACE + Duration::from_secs(3), rx.recv()).await.unwrap();- assert!(matches!(closed, Some(Incoming::Closed { .. })));- }-- #[cfg(unix)]- #[tokio::test]- async fn a_stopped_agent_finishes_by_itself_first() {- // The adapter exits on its closed stdin; the CLI it started saves its login a second later.- let (acp, mut rx) = Acp::spawn(- r#"sh -c 'read line; (sleep 1; echo "{\"jsonrpc\":\"2.0\",\"method\":\"saved\"}") &'"#,- "/tmp",- &[],- )- .unwrap();- acp.kill().await;- let saved = tokio::time::timeout(EXIT_GRACE, rx.recv()).await.unwrap();- assert!(matches!(saved, Some(Incoming::Notification { method, .. }) if method == "saved"));- assert!(acp.notify("x", json!({})).await.is_err(), "a stopped agent takes no more messages");- }-- #[cfg(unix)]- #[tokio::test]- async fn request_response_roundtrip() {- // A fake agent: answers `initialize`, then sends a notification and exits.- let script = r#"read l; id=$(echo "$l" | sed 's/.*"id":\([0-9]*\).*/\1/'); echo "{\"jsonrpc\":\"2.0\",\"id\":$id,\"result\":{\"ok\":true}}"; echo '{"jsonrpc":"2.0","method":"session/update","params":{"x":1}}'"#;- let (acp, mut rx) = Acp::spawn(&format!("sh -c '{}'", script.replace('\'', "'\\''")), "/tmp", &[]).unwrap();- let res = acp.request("initialize", json!({})).await.unwrap();- assert_eq!(res["ok"], true);- match rx.recv().await.unwrap() {- Incoming::Notification { method, .. } => assert_eq!(method, "session/update"),- _ => panic!("expected notification"),- }- assert!(matches!(rx.recv().await.unwrap(), Incoming::Closed { .. }));- }-}+mod tests;diff --git a/host/src/agent/acp/tests.rs b/host/src/agent/acp/tests.rsnew file mode 100644index 00000000..9f86467d--- /dev/null+++ b/host/src/agent/acp/tests.rs@@ -0,0 +1,142 @@+use super::*;++async fn descendant_agent() -> (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>) {+ let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/process_agent.py");+ let python = if cfg!(windows) { "python" } else { "python3" };+ let command = format!("{python} -u {}", crate::shell::quote(&script.display().to_string()));+ let (acp, mut rx) = Acp::spawn(&command, env!("CARGO_MANIFEST_DIR"), &[]).unwrap();+ let ready = tokio::time::timeout(Duration::from_secs(15), rx.recv()).await;+ let ready = ready.unwrap();+ assert!(matches!(ready, Some(Incoming::Notification { method, .. }) if method == "ready"));+ (acp, rx)+}++async fn assert_descendant_pipes_close(mut rx: mpsc::UnboundedReceiver<Incoming>) {+ let closed = tokio::time::timeout(Duration::from_secs(5), rx.recv()).await;+ let closed = closed.unwrap();+ assert!(matches!(closed, Some(Incoming::Closed { .. })));+}++#[tokio::test]+async fn leader_exit_releases_descendants_without_waiting_for_stdout_eof() {+ let (acp, rx) = descendant_agent().await;+ let notified = acp.notify("exit", json!({})).await;+ notified.unwrap();+ assert_descendant_pipes_close(rx).await;+}++#[tokio::test]+async fn dropping_an_agent_releases_its_process_tree() {+ let (acp, rx) = descendant_agent().await;+ drop(acp);+ assert_descendant_pipes_close(rx).await;+}++#[tokio::test]+async fn actor_unwinding_releases_its_process_tree() {+ let (acp, rx) = descendant_agent().await;+ let task = tokio::spawn(async move {+ let _owned = acp;+ panic!("simulated actor panic");+ });+ let panicked = task.await;+ assert!(panicked.unwrap_err().is_panic());+ assert_descendant_pipes_close(rx).await;+}++#[tokio::test]+async fn timed_out_requests_do_not_accumulate_pending_answers() {+ let (acp, rx) = descendant_agent().await;+ for _ in 0..10 {+ let response = tokio::time::timeout(Duration::from_millis(10), acp.request("never", json!({}))).await;+ assert!(response.is_err());+ assert_eq!(acp.pending.locked().len(), 0);+ }+ acp.kill().await;+ stopped().await;+ assert_descendant_pipes_close(rx).await;+}++#[cfg(unix)]+#[tokio::test]+async fn a_stopped_agent_that_exits_cleanly_does_not_hold_the_host_for_the_grace_period() {+ let (acp, mut rx) = Acp::spawn("cat", env!("CARGO_MANIFEST_DIR"), &[]).unwrap();+ let started = tokio::time::Instant::now();+ acp.kill().await;+ stopped().await;+ assert!(started.elapsed() < EXIT_GRACE / 2, "stopping waited out the grace period");+ assert!(matches!(rx.recv().await, Some(Incoming::Closed { .. })));+}++#[test]+fn content_text_flattens_blocks() {+ let v = json!([+ {"type": "content", "content": {"type": "text", "text": "a"}},+ {"type": "diff", "path": "/x"},+ {"type": "text", "text": "b"}+ ]);+ assert_eq!(content_text(&v), "a\nb");+ assert_eq!(truncate("héllo", 2), "h…");+}++#[tokio::test]+async fn an_error_keeps_the_adapters_category_only_when_it_is_an_identifier() {+ let kind = |data: Value| async move {+ let (tx, rx) = oneshot::channel();+ let _ = tx.send(Err(json!({"code": -32603, "message": "Internal error", "data": data})));+ let e =+ Answer { id: 0, pending: Pending::default(), rx: Some(rx) }.response().await.expect_err("an error answer");+ e.downcast::<RpcError>().expect("an RpcError").kind+ };+ assert_eq!(kind(json!({"errorKind": "rate_limit"})).await.as_deref(), Some("rate_limit"));+ assert_eq!(kind(json!({"errorKind": "Usage: /Users/me"})).await, None);+ assert_eq!(kind(json!({"errorKind": ""})).await, None);+ assert_eq!(kind(json!("details")).await, None);+ assert_eq!(kind(json!({"codexErrorInfo": "usageLimitExceeded"})).await.as_deref(), Some("usage_limit_exceeded"));+ assert_eq!(+ kind(json!({"codexErrorInfo": {"httpConnectionFailed": {"httpStatusCode": 502}}})).await.as_deref(),+ Some("http_connection_failed")+ );+}++#[cfg(unix)]+#[tokio::test]+async fn stopping_an_agent_closes_its_descendants_pipes() {+ let (acp, mut rx) =+ Acp::spawn(r#"sh -c 'sleep 60 & echo "{\"jsonrpc\":\"2.0\",\"method\":\"ready\"}"; read line'"#, "/tmp", &[])+ .unwrap();+ let ready = tokio::time::timeout(Duration::from_secs(3), rx.recv()).await.unwrap();+ assert!(matches!(ready, Some(Incoming::Notification { .. })));+ acp.kill().await;+ // Killing only the shell leaves sleep holding stdout for 60 seconds.+ let closed = tokio::time::timeout(EXIT_GRACE + Duration::from_secs(3), rx.recv()).await.unwrap();+ assert!(matches!(closed, Some(Incoming::Closed { .. })));+}++#[cfg(unix)]+#[tokio::test]+async fn a_stopped_agent_finishes_by_itself_first() {+ // The adapter exits on its closed stdin; the CLI it started saves its login a second later.+ let (acp, mut rx) =+ Acp::spawn(r#"sh -c 'read line; (sleep 1; echo "{\"jsonrpc\":\"2.0\",\"method\":\"saved\"}") &'"#, "/tmp", &[])+ .unwrap();+ acp.kill().await;+ let saved = tokio::time::timeout(EXIT_GRACE, rx.recv()).await.unwrap();+ assert!(matches!(saved, Some(Incoming::Notification { method, .. }) if method == "saved"));+ assert!(acp.notify("x", json!({})).await.is_err(), "a stopped agent takes no more messages");+}++#[cfg(unix)]+#[tokio::test]+async fn request_response_roundtrip() {+ // A fake agent: answers `initialize`, then sends a notification and exits.+ let script = r#"read l; id=$(echo "$l" | sed 's/.*"id":\([0-9]*\).*/\1/'); echo "{\"jsonrpc\":\"2.0\",\"id\":$id,\"result\":{\"ok\":true}}"; echo '{"jsonrpc":"2.0","method":"session/update","params":{"x":1}}'"#;+ let (acp, mut rx) = Acp::spawn(&format!("sh -c '{}'", script.replace('\'', "'\\''")), "/tmp", &[]).unwrap();+ let res = acp.request("initialize", json!({})).await.unwrap();+ assert_eq!(res["ok"], true);+ match rx.recv().await.unwrap() {+ Incoming::Notification { method, .. } => assert_eq!(method, "session/update"),+ _ => panic!("expected notification"),+ }+ assert!(matches!(rx.recv().await.unwrap(), Incoming::Closed { .. }));+}diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rsindex d344a5a2..d9b744ee 100644--- a/host/src/agent/auth.rs+++ b/host/src/agent/auth.rs@@ -130,6 +130,9 @@ pub async fn check(store: &Store, backend: &str) -> Result<Value> {}async fn probe(store: &Store, backend: &str) -> Result<Status> {+ if backends::agent_checks_off() {+ return Ok(Status::default());+ }let (acp, mut inbox, init, cmd) = start(store, backend).await?;let methods = methods(backend, &init, &cmd);if let ControlFlow::Break(signed_in) =diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 60f669ad..7c109645 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -123,6 +123,7 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {last_text: None,sent: Vec::new(),reacted: Reacted::No,+ joined: false,files: files::FileShares::default(),perms: HashMap::new(),stop_requested: false,@@ -299,11 +300,16 @@ struct Actor {seg: Seg,tools: HashMap<String, String>,plan_entry: Option<String>,+ /// What it wrote last this turn, since its last `send_message` or `react`.last_text: Option<String>,/// Messages the bot sent the user this turn (`send_message`); none: its last text is the reply.sent: Vec<String>,/// The bot's `react` this turn; with no message sent, it is the reply.reacted: Reacted,+ /// A steered message joined this turn: its last text is a reply even after a `send_message` or `react`.+ // ponytail: the host can't tell which message a send answered, so a closing note after one shows too; a bubble too+ // many beats a reply lost.+ joined: bool,files: files::FileShares,/// permission entry id -> who waits for the answerperms: HashMap<String, updates::Answer>,diff --git a/host/src/agent/bot/steer.rs b/host/src/agent/bot/steer.rsindex 339e01f4..f48aa7b1 100644--- a/host/src/agent/bot/steer.rs+++ b/host/src/agent/bot/steer.rs@@ -3,6 +3,7 @@use super::{Actor, Cmd, Queued};use crate::analytics::{self, Steer, TurnSource};use crate::chat::team::RequestStatus;+use crate::chat::uploads;use crate::store::Lane;use anyhow::{Result, anyhow};use serde_json::{Value, json};@@ -35,9 +36,13 @@ impl Actor {}/// 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.+ /// host's, nor a compaction, nor one the user already stopped.fn answers_user_in(&self, lane: &Lane) -> bool {- self.turn.is_some() && self.lane == *lane && self.compacting.is_none() && self.source() == TurnSource::User+ self.turn.is_some()+ && !self.stop_requested+ && 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@@ -51,32 +56,10 @@ impl Actor {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 });- });+ if own && self.hand_to_agent(entry_id, &text) {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);+ self.move_first(at);let how = if own {self.cancel_turn().await;Steer::Interrupted@@ -86,8 +69,62 @@ impl Actor {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.+ /// Hands the message to the agent to join its running turn (`steered` gets the answer); false when it can't steer.+ fn hand_to_agent(&mut self, entry_id: String, text: &str) -> bool {+ let (Some(turn), Some(conn), Some(sid)) =+ (self.turn, self.conn.as_ref().filter(|c| c.sessions.steering), self.turn_session.clone())+ else {+ return false;+ };+ 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")));+ // Refused only once the bot was deleted meanwhile: no one is left to tell.+ let _ = hub.send_cmd(&bot, Cmd::Steered { entry_id, outcome });+ });+ true+ }++ /// Moves what waits at `at` first in line; a compaction that is due still goes before it.+ fn move_first(&mut self, at: usize) {+ let Some(item) = self.queue.remove(at) else { return };+ let first = self.queue.iter().position(|q| !matches!(q, Queued::Compact { .. })).unwrap_or(self.queue.len());+ self.queue.insert(first, item);+ self.renumber_waiting();+ }++ /// Hands the waiting messages' turn numbers out again in their new order: a batch runs as its last message's turn+ /// (`start_turn`), and the clients take the highest for the running one.+ fn renumber_waiting(&self) {+ let waiting: Vec<_> = self+ .queue+ .iter()+ .filter_map(|q| match q {+ Queued::User { entry_id, .. } => self.hub.store.entry(entry_id),+ _ => None,+ })+ .collect();+ let mut turns: Vec<i64> = waiting.iter().map(|e| e.turn).collect();+ turns.sort_unstable();+ for (e, turn) in waiting.iter().zip(turns) {+ if e.turn != turn {+ self.hub.set_entry_turn(&e.id, Some(turn), &e.data);+ }+ }+ }++ /// The agent's answer to a steer: a message it took is that turn's, sent; one it left for later goes next; 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 {@@ -95,14 +132,16 @@ impl Actor {}let how = steer_outcome(outcome);analytics::message_steered(&self.hub, &self.cfg.backend, how);+ // A Stop meanwhile dropped it from the queue (and marked it cancelled).+ let Some(at) = self.queued_at(entry_id) else { return };if how != Steer::Joined {if steer.taken_back {self.unqueue(entry_id);+ } else if how == Steer::Next {+ self.move_first(at);}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) {@@ -110,16 +149,20 @@ impl Actor {self.hub.set_entry_turn(entry_id, Some(steer.turn), &e.data);}if self.turn == Some(steer.turn) {+ self.joined = true;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);+ // `send --wait` learns a started message's turn from the bot's next event, and a status and activity that+ // stay the same send none.+ self.hub.emit_bot(&self.cfg.id);}}- /// `unqueue`: the message never goes out, and the chat no longer shows it.+ /// `unqueue`: the message never goes out, the chat no longer shows it, and its files leave the bot's folder.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) {@@ -129,13 +172,35 @@ impl Actor {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["status"] = json!(RequestStatus::Cancelled);e.data["removed"] = true.into();self.hub.set_entry(entry_id, &e.data);+ self.delete_uploads(&e.data);// The roster previews the chat's newest message.self.hub.emit_bot(&self.cfg.id);}}++ /// Deletes the files of a message (its saved `data`) that never went out.+ fn delete_uploads(&self, data: &Value) {+ let ids: Vec<String> = data["attachments"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|a| a["id"].as_str().map(str::to_owned))+ .collect();+ if ids.is_empty() {+ return;+ }+ let (root, bot) = (uploads::root(&self.cfg), self.cfg.id.clone());+ tokio::task::spawn_blocking(move || {+ for id in ids {+ if let Err(error) = uploads::remove(&root, &id) {+ tracing::warn!(%bot, error = format!("{error:#}"), "couldn't delete a removed message's file");+ }+ }+ });+ }}#[cfg(test)]diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 95bdd405..bdf81b65 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -131,6 +131,7 @@ impl Actor {self.last_text = None;self.sent.clear();self.reacted = Reacted::No;+ self.joined = false;self.files.summary = None;self.files.cancel();if hidden {@@ -262,11 +263,11 @@ impl Actor {let sent = std::mem::take(&mut self.sent);let reacted = std::mem::take(&mut self.reacted);if !sent.is_empty() {- // The bot talked through send_message: what it wrote as its reply stays in the trace.- self.last_text = None;final_text = Some(sent.join("\n\n"));- } else if !matches!(reacted, Reacted::No) {- // A reaction (or one it held back) was its whole reply: what it wrote stays in the trace too.+ }+ // The bot talked through send_message, or a reaction (or one it held back) was its whole reply: what it wrote+ // stays in the trace. With a message that joined the turn, either may have answered only what came before it.+ if !self.joined && (!sent.is_empty() || !matches!(reacted, Reacted::No)) {self.last_text = None;}if let Some(id) = self.last_text.take().filter(|_| !stopped)diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rsindex 9aed9239..1dda1e1f 100644--- a/host/src/agent/bot/updates.rs+++ b/host/src/agent/bot/updates.rs@@ -311,6 +311,7 @@ impl Actor {self.add(EntryKind::Agent, turn, json!({"text": text, "final": true})).ok_or_else(|| anyhow::anyhow!("couldn't save the message"))?;self.sent.push(text);+ self.last_text = None;self.set_activity("Working…");Ok(())}@@ -340,6 +341,7 @@ impl Actor {if crate::chat::reactions::reacted_lately(&self.hub, &self.lane, &self.cfg.id, &target)? {if in_chat {self.reacted = Reacted::Refused;+ self.last_text = None;}anyhow::bail!("you reacted in this chat a moment ago and reactions stay rare: no reaction this time. If the message \@@ -349,6 +351,7 @@ impl Actor {self.hub.bot_react(&target, &self.cfg.id, emoji)?;if in_chat {self.reacted = Reacted::With(emoji.trim().to_owned());+ self.last_text = None;}Ok(())}diff --git a/host/src/background.rs b/host/src/background.rsindex f1de1d13..a9210ce3 100644--- a/host/src/background.rs+++ b/host/src/background.rs@@ -3,10 +3,10 @@use crate::{agent::registry, hub::Hub, market, remote::relay, screen, update, usage, voice};use std::sync::Arc;use std::time::Duration;-use tokio::task::JoinHandle;+use tokio::task::JoinSet;/// Starts the host's background work. Answers the tasks that run the computer's agent CLIs, for [`stop_agent_checks`].-pub fn start(hub: &Arc<Hub>) -> Vec<JoinHandle<()>> {+pub fn start(hub: &Arc<Hub>) -> JoinSet<()> {tokio::spawn({let hub = hub.clone();async move {@@ -21,13 +21,12 @@ pub fn start(hub: &Arc<Hub>) -> Vec<JoinHandle<()>> {tokio::spawn(market::automatic_loop(hub.clone()));tokio::spawn(voice::refresh_loop(hub.clone()));tokio::spawn(crate::chat::calls::sweep_loop(hub.clone()));- let agent_checks = vec![- tokio::spawn({- let hub = hub.clone();- async move { market::agent_sign_in::refresh(&hub).await }- }),- tokio::spawn(usage::poll(hub.clone())),- ];+ let mut agent_checks = JoinSet::new();+ agent_checks.spawn({+ let hub = hub.clone();+ async move { market::agent_sign_in::refresh(&hub).await }+ });+ agent_checks.spawn(usage::poll(hub.clone()));tokio::spawn(update::automatic_loop(hub.clone()));tokio::spawn(update::release_watch());tokio::spawn(screen::serve_helpers(hub.screen.clone()));@@ -41,9 +40,7 @@ pub fn start(hub: &Arc<Hub>) -> Vec<JoinHandle<()>> {/// and a `claude -p /usage` left behind holds on to its memory for as long as it runs.// ponytail: a check an API call started (`usage`, `refreshBackends`) can still outlive the host; track those too if one// shows up in practice.-pub async fn stop_agent_checks(tasks: Vec<JoinHandle<()>>) {- for task in &tasks {- task.abort();- }- let _ = tokio::time::timeout(Duration::from_secs(1), futures::future::join_all(tasks)).await;+pub async fn stop_agent_checks(mut tasks: JoinSet<()>) {+ // A slow shutdown must not hold up the exit.+ let _ = tokio::time::timeout(Duration::from_secs(1), tasks.shutdown()).await;}diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rsindex 1374fbcf..ec1ccacc 100644--- a/host/src/chat/calls/context.rs+++ b/host/src/chat/calls/context.rs@@ -318,8 +318,7 @@ fn others(hub: &Hub, cfg: &BotConfig) -> String {fn shared(recent: &[Entry]) -> String {let mut titles: Vec<String> = Vec::new();- // 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) {+ for e in recent.iter().rev() {if let Some(title) = e.data["artifact"]["title"].as_str() {titles.push(format!("- {title} (artifact)"));}@@ -501,19 +500,4 @@ 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 d9e16e1e..fff3c284 100644--- a/host/src/chat/handoff.rs+++ b/host/src/chat/handoff.rs@@ -82,9 +82,7 @@ pub fn draft(hub: &Hub, cfg: &BotConfig, session: &str, reason: Reason) -> Resul}fn build(store: &Store, bot: &str, session: &str) -> Result<String> {- // 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 entries = store.history(bot, i64::MAX, READ)?;let user = EntryKind::User.as_str();let requests: Vec<(String, String)> = entries.iter()diff --git a/host/src/chat/uploads.rs b/host/src/chat/uploads.rsindex d560d705..1069aa48 100644--- a/host/src/chat/uploads.rs+++ b/host/src/chat/uploads.rs@@ -89,6 +89,11 @@ pub fn read(root: &Path, upload: &str, offset: u64, len: usize) -> Result<(Vec<uOk((data, size))}+/// Deletes an upload and its folder.+pub fn remove(root: &Path, upload: &str) -> Result<()> {+ std::fs::remove_dir_all(dir(root, upload)?).context("deleting the upload")+}+/// What the agent reads after the message text.pub fn prompt_suffix(paths: &[PathBuf]) -> String {let list: Vec<String> = paths.iter().map(|p| format!("- {}", p.display())).collect();@@ -99,6 +104,17 @@ pub fn prompt_suffix(paths: &[PathBuf]) -> String {mod tests {use super::*;+ #[test]+ fn removing_an_upload_stays_inside_the_folder() {+ let root = std::env::temp_dir().join(format!("codync-uploads-{}", uuid::Uuid::new_v4()));+ let upload = uuid::Uuid::new_v4().to_string();+ append(&root, &upload, "a.txt", 0, b"hi", true).expect("upload");+ assert!(remove(&root, "../other").is_err());+ remove(&root, &upload).expect("remove");+ assert!(resolve(&root, &upload).is_err());+ std::fs::remove_dir_all(&root).expect("clean up");+ }+#[test]fn names_stay_inside_the_folder() {assert_eq!(clean_name("../../etc/passwd").expect("last component"), "passwd");diff --git a/host/src/hub.rs b/host/src/hub.rsindex 71b7e28c..e40d8378 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -441,7 +441,7 @@ impl Hub {/// [`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, turn, data) {+ match self.store.update_entry_turn(id, turn, data) {Ok(e) => {if let Some(e) = &e {let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));@@ -464,7 +464,7 @@ impl Hub {if !edit(&mut e)? {return Ok(e);}- let e = self.store.update_entry(id, None, &e.data)?.ok_or_else(|| anyhow!("unknown message"))?;+ let e = self.store.update_entry(id, &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/main.rs b/host/src/main.rsindex ddcafae0..9cc61d73 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -542,7 +542,7 @@ async fn serve(bind: &str, port: u16) -> Result<()> {}hub.shutdown().await;background::stop_agent_checks(agent_checks).await;- agent::acp::stopped().await;+ agent::acp::stop_all().await;analytics::flush_before_exit(&hub).await;tracing::info!("codync-host stopped");// A keychain read may still wait on an unlock prompt; dropping the runtime would wait for it.diff --git a/host/src/store/bots.rs b/host/src/store/bots.rsindex 67d9bddc..0d2a7690 100644--- a/host/src/store/bots.rs+++ b/host/src/store/bots.rs@@ -213,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, None, &serde_json::json!({"text": "yo!", "final": true})).unwrap().unwrap();+ let a2 = s.update_entry(&a.id, &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 60b0aef6..d6fe58ba 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -82,8 +82,12 @@ impl Store {Ok((entry, true))}- /// 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>> {+ pub fn update_entry(&self, id: &str, data: &Value) -> Result<Option<Entry>> {+ self.update_entry_turn(id, None, data)+ }++ /// [`Self::update_entry`] that also moves the entry into `turn` when given (a queued message on its way out).+ pub fn update_entry_turn(&self, id: &str, turn: Option<i64>, data: &Value) -> Result<Option<Entry>> {let c = self.db.locked();let rev = next_rev(&c)?;c.execute(@@ -167,11 +171,11 @@ impl Store {Ok(st.query_map(params![since, cap], row_entry)?.collect::<rusqlite::Result<_>>()?)}- /// Older entries of a chat.+ /// Older entries of a chat, without the messages taken back: a client hears of those through `entries_since`.pub fn history(&self, bot_id: &str, before_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+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq < ?2 AND {NOT_REMOVED}ORDER BY seq DESC LIMIT ?3"))?;let mut rows: Vec<Entry> =@@ -340,7 +344,7 @@ impl Store {"expired"};e.data["status"] = status.into();- self.update_entry(id, None, &e.data)?;+ self.update_entry(id, &e.data)?;}}Ok(ids.len())@@ -405,6 +409,7 @@ mod tests {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!(ids(s.history("b1", i64::MAX, 10).unwrap()), kept, "paging, handoffs and calls");assert_eq!(s.last_message("b1").unwrap().text, "ship it", "the roster");}diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rsindex c266a5d2..c7460c0d 100644--- a/host/src/tui/view/chat.rs+++ b/host/src/tui/view/chat.rs@@ -1,7 +1,5 @@//! 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};@@ -11,6 +9,7 @@ use super::super::app::{App, Click, Editor, Entry, Mark, SlashAction, Status};use super::super::l10n::tr;use super::super::md::{truncate, width as w};use super::buffer::{fill, hline, put, put_line, rput, u};+use super::queue::queue_band;use super::set_cursor;use super::style::{avatar, rgb, spin, theme};use super::time::elapsed;@@ -178,19 +177,7 @@ 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);- }+ let strip_top = queue_band(buf, r, app, &b, box_top, typing);// Transcript.let body = Rect::new(r.x, top + 1, r.width, strip_top.saturating_sub(top + 1));@@ -235,52 +222,6 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {}}-/// 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) {@@ -360,39 +301,6 @@ 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/mod.rs b/host/src/tui/view/mod.rsindex 5955e2c5..fba5e14c 100644--- a/host/src/tui/view/mod.rs+++ b/host/src/tui/view/mod.rs@@ -23,6 +23,7 @@ mod new_bot;mod overlay;mod pair;mod permission;+mod queue;mod roster;mod skill;mod style;diff --git a/host/src/tui/view/queue.rs b/host/src/tui/view/queue.rsnew file mode 100644index 00000000..fcefd1d1--- /dev/null+++ b/host/src/tui/view/queue.rs@@ -0,0 +1,114 @@+//! The band over the composer: the user's messages waiting for their turn, and the keys that act on them.++use std::borrow::Cow;++use ratatui::buffer::Buffer;+use ratatui::layout::Rect;++use super::super::app::{App, Bot, Entry};+use super::super::l10n::tr;+use super::super::md::truncate;+use super::buffer::{put, rput, u};+use super::style::theme;++/// Draws `bot`'s waiting messages right over the composer at `box_top`: where the band starts.+pub(super) fn queue_band(buf: &mut Buffer, r: Rect, app: &App, bot: &Bot, box_top: u16, typing: bool) -> u16 {+ let t = theme();+ let keys = match (app.queue_keys(), typing) {+ (false, _) => QueueKeys::Hidden,+ (true, false) => QueueKeys::Ready,+ (true, true) => QueueKeys::AfterEsc,+ };+ let rows = queued_rows(&app.queued(&bot.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);+ }+ strip_top+}++/// 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+}++#[cfg(test)]+mod 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", ""));+ }+}diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex c1967443..60cf4ce7 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -5,7 +5,6 @@ use ratatui::text::{Line, Span};use std::collections::{BTreeMap, BTreeSet, HashMap};use super::super::app::{App, Bot, Click, Entry, Exchange, Item, Kind, Outcome, Status, group};-use super::super::l10n::tr;use super::super::md::{self, truncate, width as w};use super::buffer::u;use super::chat::with_bg;diff --git a/host/tests/agent_checks_e2e.rs b/host/tests/agent_checks_e2e.rsindex e99ba770..c053c4b3 100644--- a/host/tests/agent_checks_e2e.rs+++ b/host/tests/agent_checks_e2e.rs@@ -9,24 +9,32 @@ mod common;use std::ffi::OsString;use std::os::unix::fs::PermissionsExt as _;use std::path::{Path, PathBuf};-use std::time::{Duration, Instant};+use std::time::Duration;-/// A `claude` first on the PATH that logs its process id and arguments, then never finishes. The PATH it's on, and its log.-fn slow_claude(home: &Path) -> (OsString, PathBuf) {+/// Fake `claude` and `cursor-agent` that log their process id and arguments, then never finish, not even when their stdin+/// closes. The PATH with them and no other agent CLI, and their log.+fn slow_agents(home: &Path) -> (OsString, PathBuf) {let bin = home.join("bin");std::fs::create_dir_all(&bin).unwrap();- let log = home.join("claude.log");+ let log = home.join("agents.log");let script = format!("#!/bin/sh\necho \"$$ $*\" >> '{}'\nexec sleep 300\n", log.display());- let claude = bin.join("claude");- std::fs::write(&claude, script).unwrap();- std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap();- let path = std::env::join_paths(- std::iter::once(bin).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())),- )- .unwrap();+ for agent in ["claude", "cursor-agent"] {+ let file = bin.join(agent);+ std::fs::write(&file, &script).unwrap();+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let path = std::env::join_paths([bin.as_path(), Path::new("/usr/bin"), Path::new("/bin")]).unwrap();(path, log)}+fn call(base: &str, home: &Path, method: &str) -> reqwest::RequestBuilder {+ let token = std::fs::read_to_string(home.join("token")).unwrap();+ reqwest::Client::new()+ .post(format!("{base}/api/{method}"))+ .bearer_auth(token.trim())+ .json(&serde_json::json!({"refresh": true, "backend": "cursor"}))+}+fn alive(pid: &str) -> bool {std::process::Command::new("kill").args(["-0", pid]).stderr(std::process::Stdio::null()).status().unwrap().success()}@@ -35,23 +43,32 @@ fn alive(pid: &str) -> bool {async fn a_stopped_host_ends_the_checks_it_was_running() {let home = std::env::temp_dir().join(format!("codync-agent-checks-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&home).unwrap();- let (path, log) = slow_claude(&home);- let env = [("PATH", path.as_os_str()), ("CODYNC_AGENT_CHECKS", "on".as_ref())];- let (mut host, _) = common::serve_with(&home, &env).await;+ let (path, log) = slow_agents(&home);+ // The checks run for real here, so they get a home of their own: the computer's other agent CLIs and logins stay out.+ let env = [+ ("PATH", path.as_os_str()),+ ("HOME", home.as_os_str()),+ ("ZDOTDIR", home.as_os_str()),+ ("CODYNC_AGENT_CHECKS", "on".as_ref()),+ ];+ let (mut host, base) = common::serve_with(&home, &env).await;+ // A check that starts the agent, which never answers: the host is still waiting when it stops.+ tokio::spawn(call(&base, &home, "agentAuth").send());let read = || std::fs::read_to_string(&log).unwrap_or_default();- let deadline = Instant::now() + Duration::from_secs(30);- while !read().contains("/usage") {- assert!(Instant::now() < deadline, "the host never ran its usage check: {}", read());- tokio::time::sleep(Duration::from_millis(50)).await;- }- common::stop(&mut host);+ common::eventually("the host ran its usage, sign-in and agent checks", Duration::from_secs(30), async || {+ let lines = read();+ lines.contains("/usage") && lines.contains("auth status") && lines.contains(" acp")+ })+ .await;+ // Not `common::stop`, which gives up sooner than an agent gets to exit by itself.+ std::process::Command::new("kill").arg(host.id().to_string()).status().unwrap();+ common::eventually("the host stopped", Duration::from_secs(20), async || host.try_wait().unwrap().is_some()).await;let lines = read();let pids: Vec<&str> = lines.lines().filter_map(|line| line.split_whitespace().next()).collect();- let deadline = Instant::now() + Duration::from_secs(5);- while pids.iter().any(|pid| alive(pid)) {- assert!(Instant::now() < deadline, "still running after the host stopped: {lines}");- tokio::time::sleep(Duration::from_millis(50)).await;- }+ common::eventually("the checks ended with the host", Duration::from_secs(5), async || {+ !pids.iter().any(|pid| alive(pid))+ })+ .await;let _ = std::fs::remove_dir_all(&home);}@@ -59,17 +76,10 @@ async fn a_stopped_host_ends_the_checks_it_was_running() {async fn a_test_host_never_runs_the_agent_clis() {let home = std::env::temp_dir().join(format!("codync-agent-checks-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&home).unwrap();- let (path, log) = slow_claude(&home);+ let (path, log) = slow_agents(&home);let (mut host, base) = common::serve_with(&home, &[("PATH", path.as_os_str())]).await;- let token = std::fs::read_to_string(home.join("token")).unwrap();- for method in ["refreshBackends", "usage"] {- let response = reqwest::Client::new()- .post(format!("{base}/api/{method}"))- .bearer_auth(token.trim())- .json(&serde_json::json!({"refresh": true}))- .send()- .await- .unwrap();+ for method in ["refreshBackends", "usage", "agentAuth"] {+ let response = call(&base, &home, method).send().await.unwrap();assert!(response.status().is_success(), "{method}: {}", response.status());}tokio::time::sleep(Duration::from_secs(1)).await;diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rsindex 9bc9f53c..52a21f6a 100644--- a/host/tests/common/mod.rs+++ b/host/tests/common/mod.rs@@ -93,6 +93,16 @@ pub fn stop(child: &mut Child) {let _ = child.wait();}+/// Waits until `done` holds, checking every 100 ms; fails naming `what` after `within`.+#[allow(dead_code, reason = "only some tests wait this way")]+pub 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;+ }+}+/// Python as the test machine names it.pub fn python() -> &'static str {if cfg!(windows) { "python" } else { "python3" }diff --git a/host/tests/e2e/wire_shape.rs b/host/tests/e2e/wire_shape.rsindex a9dd88b3..4f339078 100644--- a/host/tests/e2e/wire_shape.rs+++ b/host/tests/e2e/wire_shape.rs@@ -137,6 +137,9 @@ async fn wire_shape_matches_the_snapshot() {.to_owned();host.call("send", json!({"botId": bot, "text": "go", "clientNonce": "n1"})).await;let card = host.wait_for(&bot, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;+ // A queued message taken back: its `removed`.+ let waiting = host.call("send", json!({"botId": bot, "text": "never mind", "clientNonce": "n3"})).await;+ host.call("unqueue", json!({"botId": bot, "entryId": waiting["entry"]["id"]})).await;host.call("respondPermission", json!({"entryId": card["id"], "optionId": "allow"})).await;host.wait_for(&bot, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;// A bot another bot created: its `createdBy`.diff --git a/host/tests/fixtures/steer_agent.py b/host/tests/fixtures/steer_agent.pyindex 667583b8..824b850f 100644--- a/host/tests/fixtures/steer_agent.py+++ b/host/tests/fixtures/steer_agent.py@@ -1,13 +1,16 @@"""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.+Args: `steer|sends|late|limit|next|refuse|lingers|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 `sends` it also calls `send_message` before it takes the message and again after, before its last+text; 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; with `refuse` it answers a steer with an error; with `lingers` it takes two seconds to wind down after a cancel. It+answers a steer after `answer_delay` seconds. Every request is logged to requests.jsonl in its folder."""import json+import subprocessimport sysimport threadingimport time@@ -23,6 +26,7 @@ LIMIT = {}lock = threading.Lock()turn = {"wake": None, "steered": None, "cancelled": False}+servers = []def send(value):@@ -36,13 +40,33 @@ def say(text):send({"method": "session/update", "params": {"sessionId": SID, "update": update}})+def send_message(text):+ server = next(s for s in servers if s["name"] == "chat")+ calls = [+ ("initialize", {"protocolVersion": "2025-06-18"}),+ ("tools/call", {"name": "send_message", "arguments": {"text": text}}),+ ]+ with subprocess.Popen([server["command"], *server["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as mcp:+ for identifier, (method, params) in enumerate(calls):+ mcp.stdin.write(json.dumps({"jsonrpc": "2.0", "id": identifier, "method": method, "params": params}) + "\n")+ mcp.stdin.flush()+ mcp.stdout.readline()++def run(rid):wake = threading.Event()turn.update(wake=wake, steered=None, cancelled=False)say("Working")+ if MODE == "sends":+ send_message("Before it joined")wake.wait(SECONDS)turn["wake"] = None+ if MODE == "sends" and turn["steered"]:+ say("About to send")+ send_message("After it joined")if turn["cancelled"]:+ if MODE == "lingers":+ time.sleep(2)send({"id": rid, "result": {"stopReason": "cancelled"}})returnif MODE == "limit":@@ -53,8 +77,11 @@ def run(rid):def steer(message):- time.sleep(ANSWER_DELAY)wake = turn["wake"]+ time.sleep(ANSWER_DELAY)+ if MODE == "refuse":+ send({"id": message["id"], "error": {"code": -32603, "message": "Can't take that now"}})+ returnif MODE == "next" or wake is None:send({"id": message["id"], "result": {"outcome": "promptRequired", "reason": "noRunningTurn"}})return@@ -63,8 +90,7 @@ def steer(message):wake.set()time.sleep(0.5)send({"id": message["id"], "result": {"outcome": "injected"}})- if MODE == "limit":- time.sleep(0.3)+ time.sleep(0.3)wake.set()@@ -80,6 +106,7 @@ with open("requests.jsonl", "a") as log:if method == "initialize":send({"id": message["id"], "result": init})elif method == "session/new":+ servers[:] = message["params"]["mcpServers"]send({"id": message["id"], "result": {"sessionId": SID}})elif method == "session/prompt":threading.Thread(target=run, args=(message["id"],)).start()diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex 5abd9fe0..e2dbdc78 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -169,6 +169,7 @@"event:entry(user).entry.data": "object","event:entry(user).entry.data.attachments": "array","event:entry(user).entry.data.clientNonce": "string",+ "event:entry(user).entry.data.removed": "bool","event:entry(user).entry.data.status": "string","event:entry(user).entry.data.text": "string","event:entry(user).entry.id": "string",diff --git a/host/tests/send_cli_e2e.rs b/host/tests/send_cli_e2e.rsindex 4273b4ad..85478e93 100644--- a/host/tests/send_cli_e2e.rs+++ b/host/tests/send_cli_e2e.rs@@ -38,6 +38,32 @@ async fn sends_plain_text_json_and_an_unwaited_acknowledgement() {assert!(ack.starts_with("id=") && ack.contains(" seq=") && ack.contains(" turn="), "{ack}");}+#[tokio::test]+async fn a_message_steered_into_the_running_turn_gets_that_turns_reply() {+ let host = Host::start().await;+ // It only writes text: the bot's activity doesn't change while the turn takes the message in.+ let bot = host.fixture_bot("Steers", "steer_agent.py", "steer 30").await;+ host.call("send", json!({"botId": bot, "text": "first"})).await;+ common::eventually("the agent got the first prompt", Duration::from_mins(1), async || {+ host.requests(&bot, "session/prompt").len() == 1+ })+ .await;+ let steer_it = async {+ let waiting = async || {+ let history = host.call("history", json!({"botId": bot})).await;+ history["entries"].as_array().unwrap().iter().find(|e| e["data"]["text"] == "second").cloned()+ };+ common::eventually("the second message waits", Duration::from_secs(20), async || waiting().await.is_some())+ .await;+ host.call("steer", json!({"botId": bot, "entryId": waiting().await.unwrap()["id"]})).await;+ };+ let wait = ["--bot", &bot, "--wait", "--json", "--timeout", "20", "second"];+ let (output, ()) = tokio::join!(host.run(&wait), steer_it);+ let result = json_output(&output, 0);+ assert_eq!(result["status"], "completed");+ assert!(result["reply"].as_str().unwrap().contains("Got: "), "{result}");+}+#[tokio::test]async fn a_turn_without_a_text_reply_completes_when_the_bot_is_idle() {let host = Host::start().await;diff --git a/host/tests/steer_e2e.rs b/host/tests/steer_e2e.rsindex 3f3cd97f..2a933da2 100644--- a/host/tests/steer_e2e.rs+++ b/host/tests/steer_e2e.rs@@ -1,16 +1,16 @@//! 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.+//! says so or refuses, or taken back.#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]mod common;use common::host::Host;-use common::python_missing;+use common::{eventually, python_missing};use serde_json::{Value, json};use std::path::PathBuf;-use std::time::{Duration, Instant};+use std::time::Duration;async fn entries(host: &Host, bot: &str) -> Vec<Value> {host.call("history", json!({"botId": bot})).await["entries"].as_array().unwrap().clone()@@ -20,22 +20,25 @@ 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;- }+/// Whether `history` no longer lists a message: one taken back.+async fn gone(host: &Host, bot: &str, id: &str) -> bool {+ entries(host, bot).await.iter().all(|e| e["id"] != id)}-/// 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) {+/// Sends "first" and waits until its turn runs at the agent: its id.+async fn turn_running(host: &Host, bot: &str) -> 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;+ first+}++/// 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 = turn_running(host, bot).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())@@ -77,6 +80,39 @@ async fn a_steered_message_joins_the_running_turn() {assert!(reply["seq"].as_i64() > second["seq"].as_i64(), "the reply comes after the message it answers");}+#[tokio::test]+async fn a_steered_message_gets_its_reply_even_after_the_bot_used_send_message() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Sends", "steer_agent.py", "sends 30").await;+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ let is_final = async |text: &str| {+ entries(&host, &bot)+ .await+ .iter()+ .find(|e| e["data"]["text"].as_str().is_some_and(|t| t.starts_with(text)))+ .map(|e| e["data"]["final"] == true)+ };+ eventually("the bot told the user something", Duration::from_secs(20), async || {+ is_final("Before it joined").await == Some(true)+ })+ .await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ eventually("the turn ended", Duration::from_secs(20), async || {+ status(&host, &bot, &second).await == "sent" && idle(&host, &bot).await+ })+ .await;++ assert_eq!(is_final("After it joined").await, Some(true));+ assert_eq!(is_final("Working").await, Some(false), "what it wrote before a send stays in the trace");+ assert_eq!(is_final("About to send").await, Some(false), "so does what it wrote before a later send");+ 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() > entry(&host, &bot, &second).await["seq"].as_i64());+}+#[tokio::test]async fn a_steered_message_keeps_a_turn_that_ends_before_the_agent_answers() {if python_missing() {@@ -212,9 +248,7 @@ async fn a_queued_message_taken_back_never_goes_out() {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);+ assert!(gone(&host, &bot, &second).await, "history no longer lists it");// Only a message still waiting can be steered or taken back.for method in ["steer", "unqueue"] {for id in [&first, &second] {@@ -235,23 +269,176 @@ async fn a_message_taken_back_while_the_agent_decides_goes_unless_the_agent_tookhost.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 (_, left_alone) = queue_behind_a_turn(&host, &left).await;let (_, joined) = queue_behind_a_turn(&host, &taken).await;- for (bot, id) in [(&left, &gone), (&taken, &joined)] {+ for (bot, id) in [(&left, &left_alone), (&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+ gone(&host, &left, &left_alone).await}).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");}++#[tokio::test]+async fn a_queued_message_taken_back_takes_its_files_with_it() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Files", "steer_agent.py", "plain 5").await;+ turn_running(&host, &bot).await;+ let upload = uuid::Uuid::new_v4().to_string();+ let chunk =+ json!({"botId": bot, "uploadId": upload, "name": "secret.pem", "offset": 0, "data": "aGk=", "done": true});+ host.call("upload", chunk).await;+ let sent = host.call("send", json!({"botId": bot, "text": "", "attachments": [upload]})).await;+ let read = json!({"botId": bot, "uploadId": upload, "offset": 0});+ assert!(host.post("readUpload", &read).await.0, "the file is there while it waits");+ host.call("unqueue", json!({"botId": bot, "entryId": sent["entry"]["id"]})).await;+ let folder = host.home.join("bots").join(&bot).join("workspace/uploads").join(&upload);+ eventually("its file left the bot's folder", Duration::from_secs(10), async || !folder.exists()).await;+ assert!(!host.post("readUpload", &read).await.0, "nor can a client read it");+ host.call("stop", json!({"botId": bot})).await;+}++#[tokio::test]+async fn a_message_the_agent_leaves_for_later_goes_before_other_work() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Ahead", "steer_agent.py", "next 3").await;+ turn_running(&host, &bot).await;+ let body = json!({"botId": bot, "name": "Other work", "instruction": "Other work", "triggers": [{"type": "webhook"}], "timeoutSeconds": 60});+ let routine = host.call("saveRoutine", body).await["routine"]["id"].clone();+ host.call("runRoutine", json!({"botId": bot, "id": routine})).await;+ let second = host.call("send", json!({"botId": bot, "text": "second"})).await["entry"]["id"].clone();+ host.call("steer", json!({"botId": bot, "entryId": second})).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(["first", "second", "Other work"]) {+ assert!(prompt.contains(said), "{said}: {prompts:?}");+ }+}++#[tokio::test]+async fn a_message_moved_first_takes_the_earlier_turn() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Reorders", "steer_agent.py", "plain 3").await;+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ let third = host.call("send", json!({"botId": bot, "text": "third"})).await["entry"]["id"].clone();+ host.call("steer", json!({"botId": bot, "entryId": third})).await;+ eventually("both started one turn, and it ended", Duration::from_secs(20), async || {+ host.requests(&bot, "session/prompt").len() == 2 && idle(&host, &bot).await+ })+ .await;+ let prompt = host.requests(&bot, "session/prompt")[1]["params"]["prompt"][0]["text"].to_string();+ assert!(prompt.find("third") < prompt.find("second"), "{prompt}");+ let (second, third) = (entry(&host, &bot, &second).await, entry(&host, &bot, third.as_str().unwrap()).await);+ assert!(third["turn"].as_i64() < second["turn"].as_i64(), "turns follow the order they went out in");+ let reply = entries(&host, &bot).await.into_iter().rev().find(|e| e["data"]["final"] == true).unwrap();+ assert_eq!(reply["turn"], second["turn"], "the agent works in the batch's last turn, the highest");+}++#[tokio::test]+async fn a_message_steered_after_stop_waits_for_the_stopping_turn_to_end() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Lingers", "steer_agent.py", "lingers 30").await;+ turn_running(&host, &bot).await;+ host.call("stop", json!({"botId": bot})).await;+ let second = host.call("send", json!({"botId": bot, "text": "second"})).await["entry"].clone();+ assert_eq!(second["data"]["status"], "queued", "the stopped turn is still winding down");+ host.call("steer", json!({"botId": bot, "entryId": second["id"]})).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(), "a stopping turn takes nothing in");+ let prompt = &host.requests(&bot, "session/prompt")[1]["params"]["prompt"][0]["text"];+ assert!(prompt.as_str().unwrap().contains("second"), "{prompt}");+ host.call("stop", json!({"botId": bot})).await;+}++#[tokio::test]+async fn a_message_the_agent_refuses_waits_for_the_next_turn() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Refuses", "steer_agent.py", "refuse 3").await;+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ eventually("the agent got the steer", Duration::from_secs(20), async || {+ host.requests(&bot, "_session/steering").len() == 1+ })+ .await;+ assert_eq!(status(&host, &bot, &second).await, "queued");+ eventually("the message started its own turn", Duration::from_secs(20), async || {+ host.requests(&bot, "session/prompt").len() == 2+ })+ .await;+ 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_stop_while_the_agent_decides_keeps_the_message_dropped() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.fixture_bot("Stops", "steer_agent.py", "steer 30 1").await;+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ host.call("stop", json!({"botId": bot})).await;+ eventually("the agent answered", Duration::from_secs(10), async || idle(&host, &bot).await).await;+ tokio::time::sleep(Duration::from_secs(2)).await;+ let dropped = entry(&host, &bot, &second).await;+ assert_eq!(dropped["data"]["status"], "cancelled", "the agent's late yes doesn't bring it back");+ assert_eq!(dropped["data"]["removed"], Value::Null, "the chat says it wasn't sent");+ assert_eq!(host.requests(&bot, "session/prompt").len(), 1);+}++#[tokio::test]+async fn a_steered_message_is_in_the_exchange_the_bot_learns_from() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/steer_agent.py");+ let command = format!("{} steer 30", common::python_agent(&script));+ let created = json!({"name": "", "backend": "custom", "command": command, "connectors": [], "notify": false});+ let bot = host.call("createBot", created).await["bot"]["id"].as_str().unwrap().to_owned();+ let (_, second) = queue_behind_a_turn(&host, &bot).await;+ host.call("steer", json!({"botId": bot, "entryId": second})).await;+ let db = rusqlite::Connection::open(host.home.join("codync.db")).unwrap();+ let observed = || -> Option<String> {+ db.query_row("SELECT v FROM kv WHERE k = ?", [format!("naming.turns.{bot}")], |r| r.get(0)).ok()+ };+ eventually("the turn's exchange was recorded", Duration::from_secs(20), async || observed().is_some()).await;+ let turns: Value = serde_json::from_str(&observed().unwrap()).unwrap();+ let user = turns[0]["user"].as_str().unwrap();+ assert!(user.contains("first") && user.contains("second"), "{user}");+}diff --git a/tools/check-connectors.py b/tools/check-connectors.pyindex 0e97b42e..202305e2 100644--- a/tools/check-connectors.py+++ b/tools/check-connectors.py@@ -191,7 +191,7 @@ def main():with tempfile.TemporaryDirectory(prefix="codync-connectors-check-") as temp:home = Path(temp)- env = {**os.environ, "CODYNC_HOME": str(home), "CODYNC_CLOUD": "off"}+ env = {**os.environ, "CODYNC_HOME": str(home), "CODYNC_CLOUD": "off", "CODYNC_AGENT_CHECKS": "off"}with socket.socket() as listener:listener.bind(("127.0.0.1", 0))port = listener.getsockname()[1]diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex 435dd892..56a5d743 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -27,7 +27,7 @@ Each chat keeps its own draft on each device, and the draft comes back when you**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.+- **Remove** (the trash can) takes it back: neither it nor its files reach 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.