mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
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>
This commit is contained in:
+24
-25
@@ -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<AgentQueued> {
|
||||
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<AgentRetry>) {
|
||||
{
|
||||
@@ -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" {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
+1
-1
@@ -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";
|
||||
|
||||
@@ -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 = <T,>(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(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
|
||||
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();
|
||||
|
||||
@@ -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 (
|
||||
<div className={styles.queue} aria-label={tx("Queued messages")}>
|
||||
{task.queue.map((q) => (
|
||||
<div key={q.id} className={styles.queued}>
|
||||
<Icon name="pause" size={12} className={styles.muted} />
|
||||
<span className={styles.queuedText} title={q.prompt.text}>
|
||||
{q.prompt.text || <T>Image</T>}
|
||||
</span>
|
||||
<IconButton icon="arrow-up" title="Send now" onClick={() => void sendQueuedNow(task.id, q.id).catch(fail)} />
|
||||
<IconButton icon="edit" title="Edit" onClick={() => void editQueued(task.id, q.id).catch(fail)} />
|
||||
<IconButton icon="close" title="Remove" onClick={() => void removeQueued(task.id, q.id).catch(fail)} />
|
||||
</div>
|
||||
<QueueRow key={q.id} task={task.id} item={q} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QueueRow({ task, item }: { task: string; item: AgentQueued }) {
|
||||
const [pending, setPending] = useState(false);
|
||||
async function run(action: (task: string, queued: string) => Promise<unknown>) {
|
||||
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 (
|
||||
<div className={styles.queued}>
|
||||
<Icon name="pause" size={12} className={styles.muted} />
|
||||
<span className={styles.queuedText} title={item.prompt.text}>
|
||||
{item.prompt.text || <T>Image</T>}
|
||||
</span>
|
||||
<IconButton icon="arrow-up" title="Send now" disabled={pending} onClick={() => void run(sendQueuedNow)} />
|
||||
<IconButton icon="edit" title="Edit" disabled={pending} onClick={() => void run(editQueued)} />
|
||||
<IconButton icon="close" title="Remove" disabled={pending} onClick={() => void run(removeQueued)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user