From db08dbc4f57d3b95938200db80d41eb559f7fd81 Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Sun, 22 Nov 2026 21:34:22 -0800 Subject: [PATCH] fix(agents): refresh stale queue rows without error toasts (#5334) A turn could take the next queued message before its row disappeared, so Send now / Edit / Remove on it failed with "already sent" once per click. The dequeue is now published as soon as the turn takes the message; a stale queue action returns OutOfSync after re-publishing the current queue, which the row ignores, and only the pending row is disabled. A missing task or other failure still shows an error. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/lib.rs | 49 +++++++++-------- crates/ide-agent/src/tests.rs | 40 ++++++++++++++ crates/ide-core/src/error.rs | 2 +- src/bindings.ts | 2 +- .../agents/composerSubmission.test.tsx | 52 ++++++++++++++++++- .../agents/session/SessionComposer.tsx | 47 +++++++++++------ 6 files changed, 148 insertions(+), 44 deletions(-) diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index c3d914599..52e8dacf3 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -38,7 +38,7 @@ pub use skill_installer::{ }; use conversation::{Conversation, SavedSubagent, Session}; -use ide_core::{IdeError, IdeResult, IpcPath}; +use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind}; use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes}; use ide_vcs::Repo; use parking_lot::{Mutex, RwLock}; @@ -1172,35 +1172,14 @@ impl AgentManager { /// Drops a queued message. pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult { - let task = self.task(id)?; - let item = { - let mut s = task.state.lock(); - let i = - s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?; - s.task.queue.remove(i) - }; - task.persist(); - task.emit_task(); - Ok(item) + self.task(id)?.take_queued(queued, false).map(|(item, _)| item) } /// Sends queued message `queued` now: into the running turn when the agent takes /// messages mid-turn, else next, cancelling the current turn if there is one. pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> { let task = self.task(id)?; - let (item, busy) = { - let mut s = task.state.lock(); - let i = - s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?; - let item = s.task.queue.remove(i); - let busy = s.busy; - if !busy { - s.busy = true; - } - (item, busy) - }; - task.persist(); - task.emit_task(); + let (item, busy) = task.take_queued(queued, true)?; if !busy { self.shared.runtime.spawn(async move { task.run(item.prompt).await }); return Ok(()); @@ -2345,6 +2324,23 @@ impl Task { self.shared.emit(AgentEvent::Task { task: Box::new(task) }); } + /// Takes the item and, for Send now, claims an idle turn under the same lock. + fn take_queued(&self, id: &str, for_send: bool) -> IdeResult<(AgentQueued, bool)> { + let mut s = self.state.lock(); + let Some(index) = s.task.queue.iter().position(|item| item.id == id) else { + drop(s); + self.emit_task(); + return Err(IdeError::new(ErrorKind::OutOfSync, "Message is no longer queued")); + }; + let item = s.task.queue.remove(index); + let was_busy = s.busy; + s.busy |= for_send; + drop(s); + self.persist(); + self.emit_task(); + Ok((item, was_busy)) + } + /// Shows (or clears) the agent's pending retry; emitted only when it changes. fn set_retry(&self, retry: Option) { { @@ -2553,7 +2549,10 @@ impl Task { self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() }); } match (next, result) { - (Some(queued), _) => prompt = queued.prompt, + (Some(queued), _) => { + self.emit_task(); + prompt = queued.prompt; + } (None, Ok(stop)) => { self.set_status(AgentStatus::Ready, None); if stop != "cancelled" { diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 75d66151f..891f96062 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -1426,6 +1426,46 @@ async fn steers_through_session_steering() { wait_for(&mgr, &task.id, AgentStatus::Ready).await; } +#[tokio::test(flavor = "multi_thread")] +async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() { + use ide_core::error::ErrorKind; + + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let task = mgr + .create(NewAgentTask { provider: "claude".into(), prompt: text("ask"), ..Default::default() }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await; + mgr.prompt(&task.id, text("again"), false).await.unwrap(); + let handle = mgr.task(&task.id).unwrap(); + let queued = handle.state.lock().task.queue[0].id.clone(); + let permission = *handle.permissions.lock().keys().next().unwrap(); + let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel(); + let weak = Arc::downgrade(&handle); + mgr.subscribe(Arc::new(move |event| { + if let AgentEvent::Task { task } = event + && task.queue.is_empty() + && let Some(handle) = weak.upgrade() + { + let _ = tx.send(handle.turns.load(Ordering::Acquire)); + } + })); + mgr.respond(&task.id, permission, Some("yes".into())).unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn"); + while updates.try_recv().is_ok() {} + + for error in + [mgr.unqueue(&task.id, &queued).unwrap_err(), mgr.send_queued_now(&task.id, &queued).await.unwrap_err()] + { + assert_eq!(error.kind, ErrorKind::OutOfSync); + assert_eq!(updates.try_recv().unwrap(), 2, "a stale action gets the current queue"); + } + assert!(!handle.state.lock().busy); + assert_eq!(mgr.unqueue("missing-task", &queued).unwrap_err().kind, ErrorKind::NotFound); +} + #[tokio::test(flavor = "multi_thread")] async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-core/src/error.rs b/crates/ide-core/src/error.rs index d7770cdf5..b3c044e67 100644 --- a/crates/ide-core/src/error.rs +++ b/crates/ide-core/src/error.rs @@ -95,7 +95,7 @@ pub enum ErrorKind { AlreadyExists, PermissionDenied, InvalidInput, - /// Document version mismatch; the UI must resync the full text. + /// The requested state is stale; the UI must use the current snapshot. OutOfSync, Cancelled, TimedOut, diff --git a/src/bindings.ts b/src/bindings.ts index d13163674..6b26084fb 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -6543,7 +6543,7 @@ report?: PushReport | null } | { type: "amendConflict"; commit: string }; export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" | -/** Document version mismatch; the UI must resync the full text. */ +/** The requested state is stale; the UI must use the current snapshot. */ "outOfSync" | "cancelled" | "timedOut" | /** A required external tool (language server, git, debugger) is unavailable. */ "unavailable" | "io" | "protocol" | "internal"; diff --git a/src/features/agents/composerSubmission.test.tsx b/src/features/agents/composerSubmission.test.tsx index 0b82ac105..e82a484bd 100644 --- a/src/features/agents/composerSubmission.test.tsx +++ b/src/features/agents/composerSubmission.test.tsx @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import type { AgentProvider, AgentTask, ProjectInfo } from "@/bindings"; import { useProject } from "@/platform/project"; import { HomeEditor } from "./HomeEditor"; @@ -23,6 +23,9 @@ const backend = vi.hoisted(() => ({ tauri: false, create: vi.fn(), prompt: vi.fn(), + unqueue: vi.fn(), + sendQueued: vi.fn(), + notify: vi.fn(), open: vi.fn(), close: vi.fn(), })); @@ -38,6 +41,8 @@ vi.mock("@/platform/ipc", async (original) => ({ commands: { agentCreate: backend.create, agentPrompt: backend.prompt, + agentUnqueue: backend.unqueue, + agentSendQueuedNow: backend.sendQueued, agentSubscribe: async () => ({ status: "ok", data: [] }), agentProviders: async () => ({ status: "ok", data: [provider] }), agentRefreshModels: async (id: string) => ({ @@ -64,6 +69,7 @@ vi.mock("@/workbench/contributions", async (original) => ({ editorService: () => ({ openInput: backend.open, closeInput: backend.close }), maybeEditorService: () => ({ activePath: () => null }), toolWindowService: () => ({ show: vi.fn() }), + notifications: () => ({ notify: backend.notify }), })); const ok = (data: T) => ({ status: "ok" as const, data }); @@ -353,6 +359,50 @@ describe.each(paths)("$name acknowledgement", (path) => { }); }); +describe("queued message actions", () => { + const item = (id: string) => ({ id, prompt: { text: id, files: [], images: [] } }); + function showQueue() { + useAgents.setState({ tasks: new Map([["A", { ...task("A"), queue: [item("first"), item("second")] }]]) }); + updateComposer("A", { text: "unsent draft" }); + render(); + return within(screen.getByLabelText("Queued messages")); + } + + it("locks only the pending row and leaves the draft alone when another turn takes it", async () => { + const response = deferred(); + backend.unqueue.mockReturnValue(response.promise); + const queue = showQueue(); + fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[0]!); + for (const name of ["Send now", "Edit", "Remove"]) { + const [first, second] = queue.getAllByRole("button", { name }); + expect(first).toBeDisabled(); + expect(second).toBeEnabled(); + fireEvent.click(first!); + } + expect(backend.unqueue).toHaveBeenCalledTimes(1); + expect(backend.sendQueued).not.toHaveBeenCalled(); + await act(async () => { + useAgents.setState({ tasks: new Map([["A", { ...task("A"), queue: [item("second")] }]]) }); + response.resolve({ status: "error", error: { kind: "outOfSync", message: "Message is no longer queued" } }); + }); + expect(queue.queryByText("first")).not.toBeInTheDocument(); + expect(composerDraft("A").text).toBe("unsent draft"); + expect(backend.notify).not.toHaveBeenCalled(); + }); + + it("still reports a missing task and allows another action after a real failure", async () => { + backend.sendQueued.mockResolvedValue({ status: "error", error: { kind: "notFound", message: "missing task" } }); + const queue = showQueue(); + fireEvent.click(queue.getAllByRole("button", { name: "Send now" })[0]!); + await waitFor(() => + expect(backend.notify).toHaveBeenCalledWith(expect.objectContaining({ body: "IpcError: missing task" })), + ); + backend.unqueue.mockResolvedValue(ok(item("first"))); + fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[0]!); + await waitFor(() => expect(composerDraft("A").text).toBe("first\nunsent draft")); + }); +}); + describe("composer UI during submission", () => { it("keeps typing and attachments in the session after Send completes", async () => { const response = deferred(); diff --git a/src/features/agents/session/SessionComposer.tsx b/src/features/agents/session/SessionComposer.tsx index e465d7416..f97b1584f 100644 --- a/src/features/agents/session/SessionComposer.tsx +++ b/src/features/agents/session/SessionComposer.tsx @@ -1,6 +1,7 @@ -import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings"; +import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentQueued, AgentTask } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { tx, useTx } from "@/platform/i18n"; +import { isErrorKind } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { Icon, IconButton, T, type IconName } from "@/ui"; import { notifications, useEditorShown } from "@/workbench/contributions"; @@ -429,25 +430,39 @@ function BackgroundTasks({ task }: { task: AgentTask }) { } function Queue({ task }: { task: AgentTask }) { - const fail = (e: unknown) => - notifications().notify({ - level: "error", - title: "Couldn't update the queue", - body: String(e), - }); return (
{task.queue.map((q) => ( -
- - - {q.prompt.text || Image} - - void sendQueuedNow(task.id, q.id).catch(fail)} /> - void editQueued(task.id, q.id).catch(fail)} /> - void removeQueued(task.id, q.id).catch(fail)} /> -
+ ))}
); } + +function QueueRow({ task, item }: { task: string; item: AgentQueued }) { + const [pending, setPending] = useState(false); + async function run(action: (task: string, queued: string) => Promise) { + if (pending) return; + setPending(true); + try { + await action(task, item.id); + } catch (e) { + // The backend already published the current queue when it found the item gone. + if (!isErrorKind(e, "outOfSync")) + notifications().notify({ level: "error", title: "Couldn't update the queue", body: String(e) }); + } finally { + setPending(false); + } + } + return ( +
+ + + {item.prompt.text || Image} + + void run(sendQueuedNow)} /> + void run(editQueued)} /> + void run(removeQueued)} /> +
+ ); +}