Skip to content

Commit e6901d0

Browse files
committed
fix: keep failed turns in saved history from breaking the chat
Connecting to a Rich Threads conversation replays its saved events, including RUN_ERROR from any earlier failed turn. CopilotKit reports those through onError as agent_run_error_event, so one failed reply made the conversation fail to load ("Could not load conversation") on every visit and showed a stale error banner. While history replays, ignore agent_run_error_event only. Connection failures (agent_connect_failed) still block loading, and errors from new turns still stop the run and the follow-up queue.
1 parent 205cc38 commit e6901d0

3 files changed

Lines changed: 74 additions & 10 deletions

File tree

‎apps/mobile/src/chat.tsx‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { BackgroundUpdates } from "./background-updates";
2626
import { BrowserRunContext, BrowserToolCard } from "./browser-tool-card";
2727
import { BrowserThreadCard } from "./computer";
2828
import { ConversationQueue, type QueuedMessage } from "./conversation-queue";
29-
import { runConversationTurn } from "./conversation-run";
29+
import { replayedRunError, runConversationTurn } from "./conversation-run";
3030
import { MailToolCard } from "./mail-tool-card";
3131
import { FileThreadCard, TaskThreadCard } from "./thread-artifacts";
3232
import { type Selection, useMuseThread } from "./threads";
@@ -200,6 +200,7 @@ export function ChatScreen({
200200
const [saveError, setSaveError] = useState("");
201201
const [historyError, setHistoryError] = useState("");
202202
const [historyAttempt, setHistoryAttempt] = useState(0);
203+
const replaying = useRef(false);
203204
useEffect(() => {
204205
if (!isReady) return;
205206
let active = true;
@@ -213,12 +214,20 @@ export function ChatScreen({
213214
async function hydrate() {
214215
try {
215216
if (richThreads) {
216-
if (selection.existing)
217-
await runConversationTurn(
218-
agentId,
219-
() => copilotkit.connectAgent({ agent }),
220-
(onError) => copilotkit.subscribe({ onError }),
221-
);
217+
if (selection.existing) {
218+
// Replaying history re-emits past RUN_ERROR events; only connection failures block loading.
219+
replaying.current = true;
220+
try {
221+
await runConversationTurn(
222+
agentId,
223+
() => copilotkit.connectAgent({ agent }),
224+
(onError) => copilotkit.subscribe({ onError }),
225+
[replayedRunError],
226+
);
227+
} finally {
228+
replaying.current = false;
229+
}
230+
}
222231
} else {
223232
const { messages } = await api.request<{ messages: Message[] }>("/api/conversation");
224233
if (active) agent.setMessages(messages);
@@ -299,6 +308,8 @@ export function ChatScreen({
299308
const subscription = copilotkit.subscribe({
300309
onError: (event) => {
301310
if (event.context?.agentId && event.context.agentId !== agentId) return;
311+
// A failed turn saved in history is already over; it is not a failure of this session.
312+
if (replaying.current && event.code === replayedRunError) return;
302313
const failure = event.error instanceof Error ? event.error : new Error(String(event.error));
303314
setError(failure.message);
304315
},

‎apps/mobile/src/conversation-run.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1-
type RunError = { error: unknown; context?: { agentId?: string } };
1+
type RunError = { error: unknown; code?: string; context?: { agentId?: string } };
2+
3+
/** A RUN_ERROR event from the thread's saved history, not a failure of this call. */
4+
export const replayedRunError = "agent_run_error_event";
25

36
/** CopilotKit emits run failures through onError even when runAgent resolves. */
47
export async function runConversationTurn(
58
agentId: string,
69
execute: () => Promise<unknown>,
710
subscribe: (listener: (event: RunError) => void) => { unsubscribe: () => void },
11+
ignore: readonly string[] = [],
812
) {
913
let failure: Error | undefined;
1014
const subscription = subscribe((event) => {
1115
if (event.context?.agentId && event.context.agentId !== agentId) return;
16+
if (event.code && ignore.includes(event.code)) return;
1217
failure = event.error instanceof Error ? event.error : new Error(String(event.error));
1318
});
1419
try {

‎tests/conversation-sdk.test.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import assert from "node:assert/strict";
22
import { test } from "node:test";
33
import { AbstractAgent } from "@ag-ui/client";
4+
import { EventType } from "@ag-ui/core";
45
import { CopilotKitCore } from "@copilotkit/core";
5-
import { throwError } from "rxjs";
6+
import { of, throwError } from "rxjs";
67
import { ConversationQueue } from "../apps/mobile/src/conversation-queue.ts";
7-
import { runConversationTurn } from "../apps/mobile/src/conversation-run.ts";
8+
import { replayedRunError, runConversationTurn } from "../apps/mobile/src/conversation-run.ts";
89

910
test("an emitted CopilotKit run error stops the queue even when runAgent resolves", async () => {
1011
let attempts = 0;
@@ -36,3 +37,50 @@ test("an emitted CopilotKit run error stops the queue even when runAgent resolve
3637
["second"],
3738
);
3839
});
40+
41+
test("a failed turn saved in thread history does not block loading the conversation", async () => {
42+
class ReplayingAgent extends AbstractAgent {
43+
run() {
44+
return throwError(() => new Error("not used"));
45+
}
46+
connect() {
47+
return of(
48+
{ type: EventType.RUN_STARTED, threadId: "thread", runId: "old-run" },
49+
{ type: EventType.RUN_ERROR, message: "Missing Authentication header" },
50+
);
51+
}
52+
}
53+
const agent = new ReplayingAgent({ agentId: "default", threadId: "thread" });
54+
const core = new CopilotKitCore({ agents__unsafe_dev_only: { default: agent } });
55+
const connect = (ignore?: string[]) =>
56+
runConversationTurn(
57+
"default",
58+
() => core.connectAgent({ agent }),
59+
(onError) => core.subscribe({ onError }),
60+
ignore,
61+
);
62+
await assert.rejects(connect(), /Missing Authentication header/);
63+
await connect([replayedRunError]);
64+
});
65+
66+
test("a connection failure still blocks loading the conversation", async () => {
67+
class UnreachableAgent extends AbstractAgent {
68+
run() {
69+
return throwError(() => new Error("not used"));
70+
}
71+
connect() {
72+
return throwError(() => new Error("Thread service unavailable"));
73+
}
74+
}
75+
const agent = new UnreachableAgent({ agentId: "default", threadId: "thread" });
76+
const core = new CopilotKitCore({ agents__unsafe_dev_only: { default: agent } });
77+
await assert.rejects(
78+
runConversationTurn(
79+
"default",
80+
() => core.connectAgent({ agent }),
81+
(onError) => core.subscribe({ onError }),
82+
[replayedRunError],
83+
),
84+
/Thread service unavailable/,
85+
);
86+
});

0 commit comments

Comments
 (0)