Skip to content

Commit a325a8f

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 d0b3a6b commit a325a8f

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
@@ -27,7 +27,7 @@ import { BackgroundUpdates } from "./background-updates";
2727
import { BrowserRunContext, BrowserToolCard } from "./browser-tool-card";
2828
import { BrowserThreadCard } from "./computer";
2929
import { ConversationQueue, type QueuedMessage } from "./conversation-queue";
30-
import { runConversationTurn } from "./conversation-run";
30+
import { replayedRunError, runConversationTurn } from "./conversation-run";
3131
import { confirmedJevSelection, displayJevUserMessage, latestJevPanelId } from "./jev-actions";
3232
import { JevInteractionContext, JevToolCard } from "./jev-tool-card";
3333
import { MailToolCard } from "./mail-tool-card";
@@ -217,6 +217,7 @@ export function ChatScreen({
217217
const [saveError, setSaveError] = useState("");
218218
const [historyError, setHistoryError] = useState("");
219219
const [historyAttempt, setHistoryAttempt] = useState(0);
220+
const replaying = useRef(false);
220221
useEffect(() => {
221222
if (!isReady) return;
222223
let active = true;
@@ -230,12 +231,20 @@ export function ChatScreen({
230231
async function hydrate() {
231232
try {
232233
if (richThreads) {
233-
if (selection.existing)
234-
await runConversationTurn(
235-
agentId,
236-
() => copilotkit.connectAgent({ agent }),
237-
(onError) => copilotkit.subscribe({ onError }),
238-
);
234+
if (selection.existing) {
235+
// Replaying history re-emits past RUN_ERROR events; only connection failures block loading.
236+
replaying.current = true;
237+
try {
238+
await runConversationTurn(
239+
agentId,
240+
() => copilotkit.connectAgent({ agent }),
241+
(onError) => copilotkit.subscribe({ onError }),
242+
[replayedRunError],
243+
);
244+
} finally {
245+
replaying.current = false;
246+
}
247+
}
239248
} else {
240249
const { messages } = await api.request<{ messages: Message[] }>("/api/conversation");
241250
if (active) agent.setMessages(messages);
@@ -352,6 +361,8 @@ export function ChatScreen({
352361
const subscription = copilotkit.subscribe({
353362
onError: (event) => {
354363
if (event.context?.agentId && event.context.agentId !== agentId) return;
364+
// A failed turn saved in history is already over; it is not a failure of this session.
365+
if (replaying.current && event.code === replayedRunError) return;
355366
const failure = event.error instanceof Error ? event.error : new Error(String(event.error));
356367
setError(failure.message);
357368
},

‎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)