The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(agents): handle conversation loading failures (#2426)
l0ng-ai6c51e3307e69
diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rsindex 69aecb82a..990a28c58 100644--- a/crates/ide-agent/src/tests.rs+++ b/crates/ide-agent/src/tests.rs@@ -366,6 +366,35 @@ fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentMan)}+#[tokio::test(flavor = "multi_thread")]+async fn saved_conversation_reads_do_not_start_or_load_the_agent() {+ let tmp = tempfile::tempdir().unwrap();+ let agent = Arc::new(FakeAgent::default());+ let mgr = manager(tmp.path(), agent.clone());+ let task = mgr+ .create(NewAgentTask {+ project_root: None,+ prompt: text("Review the saved conversation"),+ provider: "claude".into(),+ config: Vec::new(),+ isolation: Isolation::Local,+ base: None,+ })+ .await+ .unwrap();+ wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;+ mgr.shutdown();+ let restored_agent = Arc::new(FakeAgent::default());+ let restored = manager(tmp.path(), restored_agent.clone());+ assert!(!restored.entries(&task.id, None).unwrap().is_empty());+ assert!(restored_agent.calls.lock().is_empty());+ assert!(restored.entries("missing-task", None).is_err());+ assert!(restored.entries(&task.id, Some("missing-subagent".into())).is_err());+ restored.task(&task.id).unwrap().state.lock().conversation = Conversation::default();+ assert!(restored.entries(&task.id, None).unwrap().is_empty());+ restored.shutdown();+}+#[cfg(unix)]#[tokio::test(flavor = "multi_thread")]async fn claude_commands_before_session_are_fetched_once_and_saved() {diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rsindex 602daee55..fd5ffa99d 100644--- a/src-tauri/src/remote_dev.rs+++ b/src-tauri/src/remote_dev.rs@@ -831,7 +831,7 @@ pub async fn remote_invoke(None};let call = Invoke { window: label, cmd, args };- let result: Value = c.peer.request("invoke", call, None).await.map_err(ide_host::rpc::error_from_reply)?;+ let result = invoke_reply(&c.peer, call, std::time::Duration::from_secs(30)).await?;if let (Some((peers, edit)), Some(version)) =(mirrored, result.as_u64().and_then(|version| u32::try_from(version).ok())){@@ -875,10 +875,39 @@ pub async fn remote_import_local(result}+// Conversation reads are snapshots; a silent host must not leave them pending forever.+async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Duration) -> IdeResult<Value> {+ let reply = peer.request("invoke", &call, None);+ if call.cmd == "agent_entries" {+ tokio::time::timeout(entries_timeout, reply)+ .await+ .map_err(|_| IdeError::unavailable("Loading the conversation timed out. Try again."))?+ .map_err(ide_host::rpc::error_from_reply)+ } else {+ reply.await.map_err(ide_host::rpc::error_from_reply)+ }+}+#[cfg(test)]mod tests {use super::*;+ #[tokio::test]+ async fn conversation_read_times_out_when_the_host_never_replies() {+ let (client, _silent_host) = tokio::io::duplex(4096);+ let (reader, writer) = tokio::io::split(client);+ let peer = Peer::connect(reader, writer, Arc::new(ide_jsonrpc::NoopHandler));+ let call = Invoke {+ window: "main".into(),+ cmd: "agent_entries".into(),+ args: serde_json::json!({"task": "saved-codex-task", "subagent": null}),+ };+ let error = invoke_reply(&peer, call, std::time::Duration::from_millis(10)).await.unwrap_err();+ assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);+ assert_eq!(error.message, "Loading the conversation timed out. Try again.");+ peer.kill();+ }+#[test]fn maps_uname_to_rust_platform_names() {assert_eq!(platform("Linux x86_64"), ("linux".into(), "x86_64".into()));diff --git a/src/features/agents/SessionEditor.tsx b/src/features/agents/SessionEditor.tsxindex 2252157f3..232c2c928 100644--- a/src/features/agents/SessionEditor.tsx+++ b/src/features/agents/SessionEditor.tsx@@ -140,6 +140,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {const [path, setPath] = useState<string[]>([]);const view = path.at(-1) ?? null;const viewEntries = useAgents((s) => s.entries.get(entriesKey(id, view)));+ const loadError = useAgents((s) => s.entryLoads.get(entriesKey(id, view))?.error);// Each subagent's card, from its parent's conversation.const cards = useAgents(useShallow((s) => path.map((sub, i) => findSubagent(s.entries.get(entriesKey(id, path[i - 1] ?? null)), sub))),@@ -199,6 +200,7 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {key={view ?? ""}task={task}entries={viewEntries ?? null}+ loadError={loadError}subagent={view ? (cards.at(-1) ?? null) : null}onOpenSubagent={openSubagent}finding={finding && shown}@@ -526,6 +528,7 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,interface StreamProps {task: AgentTask;entries: AgentEntry[] | null;+ loadError?: string | null;/** The card of the subagent whose conversation this is; `null`: the task's own. */subagent: SubagentEntry | null;onOpenSubagent: (id: string) => void;@@ -538,7 +541,7 @@ interface StreamProps {/** Entries rendered at a time when a conversation opens at its end. */const ENTRY_BATCH = 40;-function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, onCloseFind }: StreamProps) {+function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, findFocus, onCloseFind }: StreamProps) {const ref = useRef<HTMLDivElement>(null);useSelectionBoundary(ref);const key = entriesKey(task.id, subagent?.id ?? null);@@ -754,8 +757,26 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, oshowContextMenu(e, items);}}>+ {loadError && (+ <div role="alert">+ <EmptyState+ title={tx`Couldn't load the conversation: ${loadError}`}+ actions={+ <Button+ onClick={() =>+ void executeAction("agents.retryConversation", { task: task.id, subagent: subagent?.id ?? null })+ }+ >+ Retry+ </Button>+ }+ />+ </div>+ )}{entries === null ? (- <Spinner />+ !loadError && <Spinner />+ ) : entries.length === 0 && !busy && !loadError ? (+ <EmptyState title="No conversation history" />) : (rows.map((row) => (<divdiff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsxindex 7b41c2040..bbbcf8bb3 100644--- a/src/features/agents/sessionState.test.tsx+++ b/src/features/agents/sessionState.test.tsx@@ -19,6 +19,8 @@ const backend = vi.hoisted(() => ({changes: [] as AgentChange[],answers: [] as Array<[string, number, string | null]>,fetched: [] as string[],+ entryError: null as string | null,+ entryWait: null as Promise<void> | null,}));vi.mock("@/platform/ipc", async (original) => ({...(await original<typeof import("@/platform/ipc")>()),@@ -26,6 +28,9 @@ vi.mock("@/platform/ipc", async (original) => ({agentEntries: async (id: string, sub: string | null) => {const key = sub ? `${id}/${sub}` : id;backend.fetched.push(key);+ await backend.entryWait;+ if (backend.entryError !== null)+ return { status: "error", error: { kind: "unavailable", message: backend.entryError } };return { status: "ok", data: backend.entries.get(key) ?? [] };},agentChanges: async () => ({ status: "ok", data: backend.changes }),@@ -98,12 +103,15 @@ const scrollTopDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototypafterEach(() => {disposeActions();vi.restoreAllMocks();+ vi.useRealTimers();if (scrollTopDescriptor) Object.defineProperty(HTMLElement.prototype, "scrollTop", scrollTopDescriptor);else Reflect.deleteProperty(HTMLElement.prototype, "scrollTop");});beforeEach(() => {- disposeActions = registerActions(replyActions);+ disposeActions = registerActions([...replyActions, ...taskActions]);+ backend.entryError = null;+ backend.entryWait = null;disconnect();localStorage.clear();backend.changes = [];@@ -733,6 +741,80 @@ describe("a pending permission request in the conversation", () => {});});+describe("conversation loading", () => {+ beforeEach(() => useAgents.setState({ entries: new Map() }));++ it.each(["Remote host disconnected", ""])(+ "shows load errors (%s) in the conversation and retries the same task",+ async (reason) => {+ backend.entryError = reason;+ render(<SessionEditor input={input("A")} />);+ expect(+ await screen.findByText(`Couldn't load the conversation: ${reason || "Unknown error"}`),+ ).toBeInTheDocument();+ expect(within(stream()).queryByRole("status", { name: "Loading" })).toBeNull();+ backend.entryError = null;+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(await screen.findByText("Answer A")).toBeInTheDocument();+ expect(screen.queryByText(/Couldn't load the conversation/)).toBeNull();+ },+ );++ it("shows an empty state when no history was saved", async () => {+ backend.entries.set("A", []);+ render(<SessionEditor input={input("A")} />);+ expect(await screen.findByText("No conversation history")).toBeInTheDocument();+ expect(within(stream()).queryByRole("status", { name: "Loading" })).toBeNull();+ });++ it("bounds a request that never answers, then permits retry without applying its late result", async () => {+ vi.useFakeTimers();+ let finish!: () => void;+ backend.entryWait = new Promise<void>((resolve) => {+ finish = resolve;+ });+ render(<SessionEditor input={input("A")} />);+ expect(within(stream()).getByRole("status", { name: "Loading" })).toBeInTheDocument();+ await act(() => vi.advanceTimersByTimeAsync(35_000));+ expect(+ screen.getByText("Couldn't load the conversation: Loading the conversation timed out. Try again."),+ ).toBeInTheDocument();+ expect(within(stream()).queryByRole("status", { name: "Loading" })).toBeNull();+ backend.entryWait = null;+ backend.entries.set("A", [{ type: "agent", text: "Retried history" }]);+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await act(async () => {});+ expect(screen.getByText("Retried history")).toBeInTheDocument();+ backend.entries.set("A", [{ type: "agent", text: "Stale history" }]);+ await act(async () => finish());+ expect(screen.queryByText("Stale history")).toBeNull();+ });++ it("keeps subagent failures separate and retries that subagent", async () => {+ useAgents.setState({ entries: new Map([["A", backend.entries.get("A")!]]) });+ backend.entryError = "No such subagent";+ render(<SessionEditor input={input("A")} />);+ fireEvent.click(screen.getByRole("button", { name: /Explore task A/ }));+ expect(await screen.findByText("Couldn't load the conversation: No such subagent")).toBeInTheDocument();+ backend.entryError = null;+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(await screen.findByText("Child answer")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByText("Answer A")).toBeInTheDocument();+ });++ it("does not apply entries after disconnecting the project", async () => {+ let finish!: () => void;+ backend.entryWait = new Promise<void>((resolve) => {+ finish = resolve;+ });+ render(<SessionEditor input={input("A")} />);+ act(() => disconnect());+ await act(async () => finish());+ expect(useAgents.getState().entries.size).toBe(0);+ });+});+describe("session state across tasks and hosts", () => {it("leaves a task unread while its kept-alive tab is hidden, and reads it once shown", () => {vi.spyOn(document, "hasFocus").mockReturnValue(true);diff --git a/src/features/agents/store.ts b/src/features/agents/store.tsindex 934e106e6..aef6944d7 100644--- a/src/features/agents/store.ts+++ b/src/features/agents/store.ts@@ -63,6 +63,7 @@ interface AgentsState {unread: Set<string>;/** Entries of the tasks (and subagents) opened in this window, by `entriesKey`. */entries: Map<string, AgentEntry[]>;+ entryLoads: Map<string, { error: string | null }>;changes: Map<string, AgentChange[]>;/** Scroll position and follow-output preference by conversation, shared by both hosts. */scrollPositions: Map<string, { top: number; stick: boolean }>;@@ -123,6 +124,7 @@ export const useAgents = create<AgentsState>(() => ({tasks: new Map(),unread: new Set(),entries: new Map(),+ entryLoads: new Map(),changes: new Map(),providers: [],limits: new Map(),@@ -258,6 +260,7 @@ export async function connect(): Promise<void> {error: null,tasks: new Map(tasks.map((t) => [t.id, t])),entries: new Map(),+ entryLoads: new Map(),changes: new Map(),providers,});@@ -279,6 +282,7 @@ export function disconnect() {tasks: new Map(),unread: new Set(),entries: new Map(),+ entryLoads: new Map(),changes: new Map(),docked: null,lastTask: null,@@ -374,8 +378,31 @@ function notifyChange(prev: AgentTask | undefined, task: AgentTask) {/** Loads the entries of the task's conversation, or of its subagent `subagent`'s. */export async function loadEntries(task: string, subagent: string | null = null): Promise<void> {- const entries = await call(commands.agentEntries(task, subagent));- useAgents.setState((s) => ({ entries: new Map(s.entries).set(entriesKey(task, subagent), entries) }));+ const key = entriesKey(task, subagent);+ if (useAgents.getState().entryLoads.get(key)?.error === null) return;+ const load = { error: null };+ useAgents.setState((s) => ({ entryLoads: new Map(s.entryLoads).set(key, load) }));+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const entries = await Promise.race([+ call(commands.agentEntries(task, subagent)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error(tx("Loading the conversation timed out. Try again."))), 35_000);+ }),+ ]);+ if (useAgents.getState().entryLoads.get(key) !== load) return;+ useAgents.setState((s) => {+ const entryLoads = new Map(s.entryLoads);+ entryLoads.delete(key);+ return { entries: new Map(s.entries).set(key, entries), entryLoads };+ });+ } catch (e) {+ if (useAgents.getState().entryLoads.get(key) !== load) return;+ const error = (e instanceof Error ? e.message : String(e)).trim() || tx("Unknown error");+ useAgents.setState((s) => ({ entryLoads: new Map(s.entryLoads).set(key, { error }) }));+ } finally {+ clearTimeout(timer);+ }}export async function refreshChanges(task: string): Promise<void> {diff --git a/src/features/agents/taskActions.ts b/src/features/agents/taskActions.tsindex d313486cb..f281c8565 100644--- a/src/features/agents/taskActions.ts+++ b/src/features/agents/taskActions.ts@@ -11,6 +11,7 @@ import {deleteTask,dockTask,forkTask,+ loadEntries,openTask,openTaskInEditorLocation,renameTask,@@ -72,6 +73,17 @@ async function confirmDelete(tasks: AgentTask[]) {}export const taskActions: Action[] = [+ {+ id: "agents.retryConversation",+ title: "Retry Loading Conversation",+ category: "Agents",+ hidden: true,+ run: ({ arg }) => {+ const request = arg as { task?: unknown; subagent?: unknown } | null;+ if (typeof request?.task === "string" && (request.subagent == null || typeof request.subagent === "string"))+ return loadEntries(request.task, request.subagent ?? null);+ },+ },{id: "agents.useToolWindow",title: "Chat in Tool Window",diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.jsonindex 1a07e3099..b687d1ff8 100644--- a/src/platform/locales/text/en.json+++ b/src/platform/locales/text/en.json@@ -1,4 +1,9 @@{+ "Unknown error": "Unknown error",+ "Retry Loading Conversation": "Retry Loading Conversation",+ "No conversation history": "No conversation history",+ "Loading the conversation timed out. Try again.": "Loading the conversation timed out. Try again.",+ "Couldn't load the conversation: {0}": "Couldn't load the conversation: {0}","Astro Language Server": "Astro Language Server","Astro Language Server needs Node.js. Install it or select its executable in Settings › Languages & Frameworks › Node.js.": "Astro Language Server needs Node.js. Install it or select its executable in Settings › Languages & Frameworks › Node.js.","Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.": "Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.",diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.jsonindex 84da68a72..5ebd72d46 100644--- a/src/platform/locales/text/zh.json+++ b/src/platform/locales/text/zh.json@@ -1,4 +1,9 @@{+ "Unknown error": "未知错误",+ "Retry Loading Conversation": "重新加载对话",+ "No conversation history": "没有对话历史记录",+ "Loading the conversation timed out. Try again.": "加载对话超时,请重试。",+ "Couldn't load the conversation: {0}": "无法加载对话:{0}","Astro Language Server": "Astro 语言服务器","Astro Language Server needs Node.js. Install it or select its executable in Settings › Languages & Frameworks › Node.js.": "Astro 语言服务器需要 Node.js。请安装 Node.js,或在设置 › 语言和框架 › Node.js 中选择其可执行文件。","Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.": "Astro 语言服务器需要 TypeScript 语言服务库。请在项目中安装 typescript@6,或在设置中选择 TypeScript 的 lib 目录。",diff --git a/src/platform/remote.test.ts b/src/platform/remote.test.tsindex 74596d647..48e7b00b8 100644--- a/src/platform/remote.test.ts+++ b/src/platform/remote.test.ts@@ -41,6 +41,10 @@ describe("remote invoke", () => {expect(remoteRouting("settings_set", { scope: "global", key: "k", value: "1" }, served)).toBe("both");});+ it.each(["agent_subscribe", "agent_entries", "agent_prompt"])("routes %s to the agent's host", (cmd) => {+ expect(remoteRouting(cmd, { task: "saved-codex-task", subagent: null }, new Set([cmd]))).toBe("remote");+ });+it("encodes no arguments as an empty object", () => {expect(encodeArgs(undefined).json).toBe("{}");});