Skip to content

Commit 345ed67

Browse files
fix: keep failed turns in saved history from breaking the chat (#54)
* 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. * fix: count history replays so an old load cannot end a newer one --------- Co-authored-by: Jerel Velarde <85066839+jerelvelarde@users.noreply.github.com>
1 parent e9d2490 commit 345ed67

3 files changed

Lines changed: 75 additions & 10 deletions

File tree

‎apps/mobile/src/chat.tsx‎

Lines changed: 19 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 { DesktopToolCard } from "./desktop-tool-card";
3232
import { confirmedJevSelection, displayJevUserMessage, latestJevPanelId } from "./jev-actions";
3333
import { JevInteractionContext, JevToolCard } from "./jev-tool-card";
@@ -235,6 +235,8 @@ export function ChatScreen({
235235
const [saveError, setSaveError] = useState("");
236236
const [historyError, setHistoryError] = useState("");
237237
const [historyAttempt, setHistoryAttempt] = useState(0);
238+
// Loads still replaying history. A count, so an old load finishing does not end a newer one.
239+
const replaying = useRef(0);
238240
useEffect(() => {
239241
if (!isReady) return;
240242
let active = true;
@@ -248,12 +250,20 @@ export function ChatScreen({
248250
async function hydrate() {
249251
try {
250252
if (richThreads) {
251-
if (selection.existing)
252-
await runConversationTurn(
253-
agentId,
254-
() => copilotkit.connectAgent({ agent }),
255-
(onError) => copilotkit.subscribe({ onError }),
256-
);
253+
if (selection.existing) {
254+
// Replaying history re-emits past RUN_ERROR events; only connection failures block loading.
255+
replaying.current += 1;
256+
try {
257+
await runConversationTurn(
258+
agentId,
259+
() => copilotkit.connectAgent({ agent }),
260+
(onError) => copilotkit.subscribe({ onError }),
261+
[replayedRunError],
262+
);
263+
} finally {
264+
replaying.current -= 1;
265+
}
266+
}
257267
} else {
258268
const { messages } = await api.request<{ messages: Message[] }>("/api/conversation");
259269
if (active) agent.setMessages(messages);
@@ -370,6 +380,8 @@ export function ChatScreen({
370380
const subscription = copilotkit.subscribe({
371381
onError: (event) => {
372382
if (event.context?.agentId && event.context.agentId !== agentId) return;
383+
// A failed turn saved in history is already over; it is not a failure of this session.
384+
if (replaying.current > 0 && event.code === replayedRunError) return;
373385
const failure = event.error instanceof Error ? event.error : new Error(String(event.error));
374386
setError(failure.message);
375387
},

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