Skip to content

Open source CapCut alternative.

TypeScript

fix(cut): stop replaying a turn that ended in an error

David Le10eb913db0b8
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index 9db352bd..aa6f6137 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -115,7 +115,7 @@ import { runAiTool } from "@/cut/lib/aiTools";
import { holdEditorChat } from "@/cut/lib/editorWork";
import { recoverSceneCall } from "@/cut/lib/chatRecovery";
import { countChunks, replayChatStream } from "@/cut/lib/chatReplay";
-import { INTERRUPTED_ERROR, isResumeMessage, journalAhead, RESUME_LIMIT, resumePrompt, scrubLostTurn, unfinishedAsk, type JournalMark, type ResumeMetadata, type TurnSettled } from "@/cut/lib/chatResume";
+import { INTERRUPTED_ERROR, isResumeMessage, journalAhead, RESUME_LIMIT, resumePrompt, scrubLostTurn, settledMark, unfinishedAsk, type JournalMark, type ResumeMetadata, type StreamedMark, type TurnSettled } from "@/cut/lib/chatResume";
import { answerEngineGate, claimEngineTool, cancelEngineChat, foldIntoEngineChat, joinRunningEngineChat, peekEngineChat } from "@/cut/lib/engineChat";
import { messageText } from "@/cut/lib/messageText";
import { EngineGate, engineInstant, handledSince, judgeEngineTurn } from "@/cut/lib/pi/engineTurn";
@@ -1131,7 +1131,7 @@ function ChatSession({
const resumed = useRef(initialThread?.resumed ?? 0);
// The journal chunks the newest engine turn's stream handed the chat, and
// the mark the thread keeps once that turn ends (see journalAhead).
- const streamed = useRef<JournalMark | null>(null);
+ const streamed = useRef<StreamedMark | null>(null);
const journalMark = useRef(initialThread?.journal);
// A replay catching the thread up to the engine's journal: "finished" when
// that turn is over, so its tool calls and gate are history, not requests.
@@ -1317,11 +1317,11 @@ function ChatSession({
finishBrowserTurn.current = null;
if (chatThreadDeleted(projectId, threadId)) return;
catchingUp.current = null;
- if (!isAbort && !isDisconnect && !isError) {
- completedMessageId.current = message.id;
- // The whole turn landed: the thread now holds this much of its journal.
- if (streamed.current?.messageId === message.id) journalMark.current = streamed.current;
- }
+ const stop = isAbort || isDisconnect || isError ? "cut" : "finished";
+ if (stop === "finished") completedMessageId.current = message.id;
+ // The stream reached the journal's end — cleanly, or through its closing
+ // error — so the thread now holds that much of it and replays it no more.
+ journalMark.current = settledMark(streamed.current, message.id, stop) ?? journalMark.current;
// A verdict holds the thread for the user. A detach (this panel closing
// its reader while the engine keeps working) and a dropped connection
// with continuations left leave none, so the turn resumes.
diff --git a/site/src/cut/lib/chatReplay.test.ts b/site/src/cut/lib/chatReplay.test.ts
index 5a8e33a2..2407e02a 100644
--- a/site/src/cut/lib/chatReplay.test.ts
+++ b/site/src/cut/lib/chatReplay.test.ts
@@ -2,7 +2,7 @@ import { expect, test } from "bun:test";
import { Chat } from "@ai-sdk/react";
import type { UIMessage, UIMessageChunk } from "ai";
import { countChunks, replayChatStream } from "./chatReplay";
-import { journalAhead, type JournalMark } from "./chatResume";
+import { journalAhead, settledMark, type JournalMark } from "./chatResume";
test("replay identifies the saved reply before exposing any chunks", async () => {
let prepared = false;
@@ -87,7 +87,7 @@ test("a stream's chunks are counted under its turn", async () => {
} });
const reader = countChunks(source, (mark) => marks.push(mark)).getReader();
while (!(await reader.read()).done);
- expect(marks.at(-1)).toEqual({ messageId: "turn-1", chunks: 3 });
+ expect(marks.at(-1)).toEqual({ messageId: "turn-1", chunks: 3, ended: true });
});
// The engine kept the whole turn in its journal while the page's saved copy
@@ -145,3 +145,47 @@ test("a completed thread saved short of its journal catches up by replaying it",
expect(toolCalls).toBe(296);
expect(journalAhead(chat.messages, mark ?? undefined, peeked)).toBe(false);
});
+
+// The engine turn failed, so its journal closes with an error chunk. The
+// catch-up replay reads that chunk and the chat finishes with an error; the
+// thread still counts the whole journal, so the next open replays nothing.
+test("a journal that ends in an error replays once", async () => {
+ const journal: UIMessageChunk[] = [
+ { type: "start", messageId: "turn-1", messageMetadata: { requestMessageId: "ask" } },
+ { type: "text-start", id: "t" },
+ { type: "text-delta", id: "t", delta: "Working on it." },
+ { type: "text-end", id: "t" },
+ { type: "error", errorText: "Chat stopped." },
+ ];
+ const saved: UIMessage[] = [
+ { id: "ask", role: "user", parts: [{ type: "text", text: "build the titles" }] },
+ { id: "turn-1", role: "assistant", parts: [] },
+ ];
+ const peeked = { messageId: "turn-1", chunks: journal.length };
+ let streamed: Parameters<typeof settledMark>[0] = null;
+ let held: JournalMark | null = null;
+ let failed = false;
+ const chat = new Chat<UIMessage>({
+ id: "thread-error",
+ messages: saved,
+ onFinish: ({ message, isError, isAbort, isDisconnect }) => {
+ failed = isError;
+ held = settledMark(streamed, message.id, isAbort || isDisconnect || isError ? "cut" : "finished");
+ },
+ transport: {
+ sendMessages: async () => { throw new Error("A catch-up sends nothing."); },
+ reconnectToStream: async () => {
+ const source = new ReadableStream<UIMessageChunk>({ start(controller) {
+ for (const chunk of journal) controller.enqueue(chunk);
+ controller.close();
+ } });
+ const replay = await replayChatStream(source, () => true, () => {});
+ return replay && countChunks(replay, (next) => { streamed = next; });
+ },
+ },
+ });
+ await chat.resumeStream();
+ expect(failed).toBe(true);
+ expect(held).toEqual(peeked);
+ expect(journalAhead(chat.messages, held ?? undefined, peeked)).toBe(false);
+});
diff --git a/site/src/cut/lib/chatReplay.ts b/site/src/cut/lib/chatReplay.ts
index 54579acd..6ffad562 100644
--- a/site/src/cut/lib/chatReplay.ts
+++ b/site/src/cut/lib/chatReplay.ts
@@ -1,15 +1,18 @@
import type { UIMessageChunk } from "ai";
-import type { JournalMark } from "./chatResume";
+import type { StreamedMark } from "./chatResume";
+
+// The chunks that close an engine journal: nothing follows them but [DONE].
+const CLOSING_CHUNKS = new Set<UIMessageChunk["type"]>(["finish", "error", "abort"]);
/** Count the chunks an engine turn's stream hands the chat. The engine's
* journal counts the same chunks, so a finished turn's count is the mark its
- * saved thread keeps (see journalAhead). */
-export function countChunks(source: ReadableStream<UIMessageChunk>, count: (mark: JournalMark) => void): ReadableStream<UIMessageChunk> {
- let mark: JournalMark | null = null;
+ * saved thread keeps (see journalAhead and settledMark). */
+export function countChunks(source: ReadableStream<UIMessageChunk>, count: (mark: StreamedMark) => void): ReadableStream<UIMessageChunk> {
+ let mark: StreamedMark | null = null;
return source.pipeThrough(new TransformStream<UIMessageChunk, UIMessageChunk>({
transform(chunk, controller) {
- if (chunk.type === "start" && chunk.messageId) mark = { messageId: chunk.messageId, chunks: 0 };
- if (mark) count(mark = { ...mark, chunks: mark.chunks + 1 });
+ if (chunk.type === "start" && chunk.messageId) mark = { messageId: chunk.messageId, chunks: 0, ended: false };
+ if (mark) count(mark = { ...mark, chunks: mark.chunks + 1, ended: CLOSING_CHUNKS.has(chunk.type) });
controller.enqueue(chunk);
},
}));
diff --git a/site/src/cut/lib/chatResume.test.ts b/site/src/cut/lib/chatResume.test.ts
index 35df0334..d1389c7d 100644
--- a/site/src/cut/lib/chatResume.test.ts
+++ b/site/src/cut/lib/chatResume.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from "bun:test";
import type { UIMessage } from "ai";
-import { DETACHED_MEDIA_ERROR, DETACHED_UI_NOTE, INTERRUPTED_ERROR, isResumeMessage, journalAhead, pendingAsk, resumePrompt, scrubLostTurn, unfinishedAsk } from "./chatResume";
+import { DETACHED_MEDIA_ERROR, DETACHED_UI_NOTE, INTERRUPTED_ERROR, isResumeMessage, journalAhead, pendingAsk, resumePrompt, scrubLostTurn, settledMark, unfinishedAsk } from "./chatResume";
const user = (id: string, text: string, metadata?: Record<string, unknown>): UIMessage =>
({ id, role: "user", parts: [{ type: "text", text }], ...(metadata ? { metadata } : {}) }) as UIMessage;
@@ -93,3 +93,18 @@ test("a thread saved short of its newest turn's journal catches up from it", ()
expect(journalAhead([...messages, user("next", "now the music")], undefined, journal)).toBe(false);
expect(journalAhead(messages, undefined, null)).toBe(false);
});
+
+test("a journal that ended in an error or a stop is marked whole, so it replays once", () => {
+ const messages = [user("ask", "build the titles"), reply("turn-1")];
+ const journal = { messageId: "turn-1", chunks: 7 };
+ // The replay read the journal's closing error chunk, then the chat reported an error.
+ const held = settledMark({ messageId: "turn-1", chunks: 7, ended: true }, "turn-1", "cut");
+ expect(held).toEqual(journal);
+ expect(journalAhead(messages, held ?? undefined, journal)).toBe(false);
+ // A connection cut before the journal closed keeps no mark, so the turn catches up later.
+ expect(settledMark({ messageId: "turn-1", chunks: 4, ended: false }, "turn-1", "cut")).toBeNull();
+ // A clean finish keeps its mark; another turn's stream marks nothing.
+ expect(settledMark({ messageId: "turn-1", chunks: 7, ended: false }, "turn-1", "finished")).toEqual(journal);
+ expect(settledMark({ messageId: "turn-0", chunks: 7, ended: true }, "turn-1", "finished")).toBeNull();
+ expect(settledMark(null, "turn-1", "finished")).toBeNull();
+});
diff --git a/site/src/cut/lib/chatResume.ts b/site/src/cut/lib/chatResume.ts
index 380ffc8f..6dbdc5d7 100644
--- a/site/src/cut/lib/chatResume.ts
+++ b/site/src/cut/lib/chatResume.ts
@@ -112,6 +112,24 @@ export function journalAhead(messages: UIMessage[], held: JournalMark | undefine
return held?.messageId !== journal.messageId || held.chunks < journal.chunks;
}
+/** A mark read off a turn's stream, and whether the stream reached the
+ * journal's closing chunk (finish, error or abort). */
+export type StreamedMark = JournalMark & { ended: boolean };
+
+/** How a turn's stream stopped for the chat: "finished" cleanly, or "cut"
+ * by an error, a stop or a dropped connection. */
+export type StreamStop = "finished" | "cut";
+
+/** The mark a thread keeps when a turn's stream stops. A clean finish or a
+ * stream that read the journal's closing chunk covers the whole journal, so
+ * a failed or stopped turn replays once and then rests. A connection cut
+ * before the journal closed keeps no mark, and the turn catches up later. */
+export function settledMark(streamed: StreamedMark | null, messageId: string, stop: StreamStop): JournalMark | null {
+ if (streamed?.messageId !== messageId) return null;
+ if (stop === "cut" && !streamed.ended) return null;
+ return { messageId: streamed.messageId, chunks: streamed.chunks };
+}
+
/** The continuation a resumed turn opens with. It carries the ask itself, so
* a provider session that never received it still knows the job. */
export function resumePrompt(ask: UIMessage): string {