Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend/copilot): run the chat on a turn runtime that resumes at its cursor on one connection (#15089)

Reinier van der Leer38c89a7287a0
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
index 9d46e02863..2d6610349e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx
@@ -5,6 +5,7 @@ import { RateLimitGate } from "./components/RateLimitResetDialog/RateLimitGate";
import { useCopilotPage } from "./useCopilotPage";
import { FlaskConicalIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
interface Props {
droppedFiles: File[];
@@ -16,14 +17,27 @@ interface Props {
/**
* Session-scoped chat host. Parent mounts this with `key={sessionId}` so
- * session-local view state resets on switch, while the actual AI SDK Chat
- * instance is preserved in the per-session runtime registry.
+ * session-local view state resets on switch, while the stream itself is
+ * preserved in a per-session runtime registry. Keyed again by the stream
+ * flag, so flags resolving after mount swap the stream hook by remounting.
*/
-export function CopilotChatHost({
+export function CopilotChatHost(props: Props) {
+ const isStreamRuntime = useGetFlag(Flag.COPILOT_STREAM_RUNTIME) === true;
+ return (
+ <ChatHostBody
+ key={isStreamRuntime ? "stream-runtime" : "ai-sdk"}
+ {...props}
+ isStreamRuntime={isStreamRuntime}
+ />
+ );
+}
+
+function ChatHostBody({
droppedFiles,
onDroppedFilesConsumed,
hasFloatingControls,
-}: Props) {
+ isStreamRuntime,
+}: Props & { isStreamRuntime: boolean }) {
const {
sessionId,
messages,
@@ -64,7 +78,7 @@ export function CopilotChatHost({
isAdoptingExpertSession,
isKickoffStarting,
followBackendTurn,
- } = useCopilotPage();
+ } = useCopilotPage({ isStreamRuntime });
return (
<>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx
index 740cdd7c88..e5a575ca04 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx
@@ -5,10 +5,11 @@ import {
} from "@/tests/integrations/copilot-sse";
import { screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { resetCopilotChatRegistry } from "../copilotChatRegistry";
import {
copilotStreamSequenceHandler,
renderHost,
+ resetChatRuntimes,
+ STREAM_PATHS,
TEST_BACKEND_BASE_URL,
TEST_SESSION_ID,
typeAndSend,
@@ -45,256 +46,280 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
// Keep mode/model toggles and artifacts off so the chat input renders a
// single, predictable Submit button.
+const streamPath = vi.hoisted(() => ({ runtime: false }));
+
vi.mock("@/services/feature-flags/use-get-flag", () => ({
Flag: {
CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ COPILOT_STREAM_RUNTIME: "copilot-stream-runtime",
},
- useGetFlag: () => false,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
}));
beforeEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
});
afterEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
});
-describe("Otto streaming — content rendering", () => {
- it("renders assistant text from a single text-delta frame", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: assistantTextChunks("Hello from the copilot."),
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- expect(
- await screen.findByText("Hello from the copilot.", undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
+ beforeEach(() => {
+ streamPath.runtime = path === "stream runtime";
});
- it("concatenates multiple text-delta frames into a single rendered message", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "text-start", id: "t1" },
- { type: "text-delta", id: "t1", delta: "Hello " },
- { type: "text-delta", id: "t1", delta: "from " },
- { type: "text-delta", id: "t1", delta: "the copilot." },
- { type: "text-end", id: "t1" },
- { type: "finish-step" },
- { type: "finish" },
- ],
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- expect(
- await screen.findByText("Hello from the copilot.", undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- });
+ describe("Otto streaming — content rendering", () => {
+ it("renders assistant text from a single text-delta frame", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: assistantTextChunks("Hello from the copilot."),
+ }),
+ );
- it("renders the assistant's final text after reasoning chunks", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "reasoning-start", id: "r1" },
- { type: "reasoning-delta", id: "r1", delta: "Thinking " },
- { type: "reasoning-delta", id: "r1", delta: "step by step." },
- { type: "reasoning-end", id: "r1" },
- { type: "text-start", id: "t1" },
- { type: "text-delta", id: "t1", delta: "Final answer." },
- { type: "text-end", id: "t1" },
- { type: "finish-step" },
- { type: "finish" },
- ],
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- expect(
- await screen.findByText("Final answer.", undefined, { timeout: 5000 }),
- ).toBeDefined();
- });
+ renderHost();
+ await typeAndSend("hi");
- it("renders text emitted after a tool call in the same turn", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- {
- type: "tool-input-start",
- toolCallId: "call-1",
- toolName: "search",
- dynamic: true,
- },
- {
- type: "tool-input-available",
- toolCallId: "call-1",
- toolName: "search",
- input: { query: "weather" },
- dynamic: true,
- },
- {
- type: "tool-output-available",
- toolCallId: "call-1",
- output: { result: "sunny" },
- dynamic: true,
- },
- { type: "text-start", id: "t1" },
- { type: "text-delta", id: "t1", delta: "The weather is sunny." },
- { type: "text-end", id: "t1" },
- { type: "finish-step" },
- { type: "finish" },
- ],
- }),
- );
-
- renderHost();
- await typeAndSend("weather?");
-
- expect(
- await screen.findByText("The weather is sunny.", undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- });
+ expect(
+ await screen.findByText("Hello from the copilot.", undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ });
- it("renders text from both steps of a two-step turn", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "text-start", id: "t1" },
- { type: "text-delta", id: "t1", delta: "First step text." },
- { type: "text-end", id: "t1" },
- { type: "finish-step" },
- { type: "start-step" },
- { type: "text-start", id: "t2" },
- { type: "text-delta", id: "t2", delta: "Second step text." },
- { type: "text-end", id: "t2" },
- { type: "finish-step" },
- { type: "finish" },
- ],
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- // Each step's text part renders in its own element, so assert both
- // individually rather than as a single concatenated string.
- expect(
- await screen.findByText("First step text.", undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- expect(await screen.findByText("Second step text.")).toBeDefined();
- });
+ it("concatenates multiple text-delta frames into a single rendered message", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "text-start", id: "t1" },
+ { type: "text-delta", id: "t1", delta: "Hello " },
+ { type: "text-delta", id: "t1", delta: "from " },
+ { type: "text-delta", id: "t1", delta: "the copilot." },
+ { type: "text-end", id: "t1" },
+ { type: "finish-step" },
+ { type: "finish" },
+ ],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("hi");
+
+ expect(
+ await screen.findByText("Hello from the copilot.", undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ });
+
+ it("renders the assistant's final text after reasoning chunks", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "reasoning-start", id: "r1" },
+ { type: "reasoning-delta", id: "r1", delta: "Thinking " },
+ { type: "reasoning-delta", id: "r1", delta: "step by step." },
+ { type: "reasoning-end", id: "r1" },
+ { type: "text-start", id: "t1" },
+ { type: "text-delta", id: "t1", delta: "Final answer." },
+ { type: "text-end", id: "t1" },
+ { type: "finish-step" },
+ { type: "finish" },
+ ],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("hi");
+
+ expect(
+ await screen.findByText("Final answer.", undefined, { timeout: 5000 }),
+ ).toBeDefined();
+ });
+
+ it("renders text emitted after a tool call in the same turn", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ {
+ type: "tool-input-start",
+ toolCallId: "call-1",
+ toolName: "search",
+ dynamic: true,
+ },
+ {
+ type: "tool-input-available",
+ toolCallId: "call-1",
+ toolName: "search",
+ input: { query: "weather" },
+ dynamic: true,
+ },
+ {
+ type: "tool-output-available",
+ toolCallId: "call-1",
+ output: { result: "sunny" },
+ dynamic: true,
+ },
+ { type: "text-start", id: "t1" },
+ { type: "text-delta", id: "t1", delta: "The weather is sunny." },
+ { type: "text-end", id: "t1" },
+ { type: "finish-step" },
+ { type: "finish" },
+ ],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("weather?");
+
+ expect(
+ await screen.findByText("The weather is sunny.", undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ });
- it("completes the turn cleanly on an empty completion (no content, no error)", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "finish-step" },
- { type: "finish" },
- ],
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- await waitFor(
- () => {
- expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();
+ it("renders text from both steps of a two-step turn", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "text-start", id: "t1" },
+ { type: "text-delta", id: "t1", delta: "First step text." },
+ { type: "text-end", id: "t1" },
+ { type: "finish-step" },
+ { type: "start-step" },
+ { type: "text-start", id: "t2" },
+ { type: "text-delta", id: "t2", delta: "Second step text." },
+ { type: "text-end", id: "t2" },
+ { type: "finish-step" },
+ { type: "finish" },
+ ],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("hi");
+
+ if (path === "stream runtime") {
+ // The runtime renders the persisted row, and the backend appends a
+ // message's text blocks to one assistant row; a reload shows the same.
expect(
- screen.queryByRole("button", { name: /submit/i }),
- ).not.toBeNull();
- },
- { timeout: 5000 },
- );
- expect(screen.queryByText(/encountered an error/i)).toBeNull();
- });
+ await screen.findByText(
+ "First step text.Second step text.",
+ undefined,
+ {
+ timeout: 5000,
+ },
+ ),
+ ).toBeDefined();
+ return;
+ }
+ // Each step's text part renders in its own element, so assert both
+ // individually rather than as a single concatenated string.
+ expect(
+ await screen.findByText("First step text.", undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ expect(await screen.findByText("Second step text.")).toBeDefined();
+ });
- it("renders both assistant replies across two back-to-back turns in the same session", async () => {
- server.use(
- copilotStreamSequenceHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunksPerTurn: [
- assistantTextChunks("First reply.", { messageId: "msg-1" }),
- assistantTextChunks("Second reply.", { messageId: "msg-2" }),
- ],
- }),
- );
-
- renderHost();
- await typeAndSend("first message");
- expect(
- await screen.findByText("First reply.", undefined, { timeout: 5000 }),
- ).toBeDefined();
-
- await typeAndSend("second message");
- expect(
- await screen.findByText("Second reply.", undefined, { timeout: 5000 }),
- ).toBeDefined();
-
- // First reply must still be visible — both turns should accumulate in
- // the chat log, not replace each other.
- expect(screen.getByText("First reply.")).toBeDefined();
- });
+ it("completes the turn cleanly on an empty completion (no content, no error)", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "finish-step" },
+ { type: "finish" },
+ ],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("hi");
+
+ await waitFor(
+ () => {
+ expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: /submit/i }),
+ ).not.toBeNull();
+ },
+ { timeout: 5000 },
+ );
+ expect(screen.queryByText(/encountered an error/i)).toBeNull();
+ });
+
+ it("renders both assistant replies across two back-to-back turns in the same session", async () => {
+ server.use(
+ copilotStreamSequenceHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunksPerTurn: [
+ assistantTextChunks("First reply.", { messageId: "msg-1" }),
+ assistantTextChunks("Second reply.", { messageId: "msg-2" }),
+ ],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("first message");
+ expect(
+ await screen.findByText("First reply.", undefined, { timeout: 5000 }),
+ ).toBeDefined();
+
+ await typeAndSend("second message");
+ expect(
+ await screen.findByText("Second reply.", undefined, { timeout: 5000 }),
+ ).toBeDefined();
+
+ // First reply must still be visible — both turns should accumulate in
+ // the chat log, not replace each other.
+ expect(screen.getByText("First reply.")).toBeDefined();
+ });
+
+ it("renders inline markdown emphasis through the assistant's text pipeline", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: assistantTextChunks("Hello **bold** world."),
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("emphasize this");
- it("renders inline markdown emphasis through the assistant's text pipeline", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: assistantTextChunks("Hello **bold** world."),
- }),
- );
-
- renderHost();
- await typeAndSend("emphasize this");
-
- // The raw `**bold**` literal must not appear in the rendered text — if
- // it did, the markdown step was bypassed entirely. (Streamdown wraps
- // inline emphasis runs in spans for its streaming animation rather
- // than a bare <strong>, so we don't pin the tag.)
- await screen.findByText(/bold/i, undefined, { timeout: 5000 });
- expect(screen.queryByText("**bold**", { exact: true })).toBeNull();
- expect(screen.queryByText(/\*\*bold\*\*/)).toBeNull();
+ // The raw `**bold**` literal must not appear in the rendered text — if
+ // it did, the markdown step was bypassed entirely. (Streamdown wraps
+ // inline emphasis runs in spans for its streaming animation rather
+ // than a bare <strong>, so we don't pin the tag.)
+ await screen.findByText(/bold/i, undefined, { timeout: 5000 });
+ expect(screen.queryByText("**bold**", { exact: true })).toBeNull();
+ expect(screen.queryByText(/\*\*bold\*\*/)).toBeNull();
+ });
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
index c6f1486468..f43fe8f029 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
@@ -15,15 +15,16 @@ import userEvent from "@testing-library/user-event";
import type { UIMessageChunk } from "ai";
import { http, HttpResponse } from "msw";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- getOrCreateCopilotChatRuntime,
- resetCopilotChatRegistry,
-} from "../copilotChatRegistry";
+import { getOrCreateCopilotChatRuntime } from "../copilotChatRegistry";
import { useCopilotStreamStore } from "../copilotStreamStore";
import { getKickoffStatus, kickoffStorageKey } from "../expertKickoff";
import { useCopilotUIStore } from "../store";
+import { getTurnRuntime } from "../stream/turnRuntime";
import {
renderHost,
+ resetChatRuntimes,
+ STREAM_PATHS,
+ type StreamPath,
TEST_BACKEND_BASE_URL,
TEST_SESSION_ID,
typeAndSend,
@@ -58,18 +59,25 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
const flagState = vi.hoisted(() => ({ experts: false }));
+const streamPath = vi.hoisted(() => ({ runtime: false }));
+
vi.mock("@/services/feature-flags/use-get-flag", () => ({
Flag: {
CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
HIRE_EXPERTS: "HIRE_EXPERTS",
+ COPILOT_STREAM_RUNTIME: "copilot-stream-runtime",
},
useGetFlag: (flag: string) =>
- flag === "HIRE_EXPERTS" ? flagState.experts : false,
+ flag === "copilot-stream-runtime"
+ ? streamPath.runtime
+ : flag === "HIRE_EXPERTS"
+ ? flagState.experts
+ : false,
}));
beforeEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
useCopilotStreamStore.getState().resetAll();
useCopilotUIStore.setState({ initialPrompt: null });
window.localStorage.clear();
@@ -77,429 +85,457 @@ beforeEach(() => {
});
afterEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
useCopilotStreamStore.getState().resetAll();
useCopilotUIStore.setState({ initialPrompt: null });
window.localStorage.clear();
flagState.experts = false;
});
-describe("Otto streaming — error paths", () => {
- it.each(["ready", "error"] as const)(
- "retries an empty response with a fresh stream when status is %s",
- async (status) => {
- const errorText = "The model returned an empty response.";
- const failureChunks = assistantTextChunks(
- `[__COPILOT_RETRYABLE_ERROR_a9c2__] ${errorText}`,
- { messageId: "failed-response" },
- );
- if (status === "error") {
- failureChunks.splice(-1, 1, { type: "error", errorText });
- }
- const requests: unknown[] = [];
- const queueRequest = vi.fn(() =>
- HttpResponse.json(
- {
- detail:
- "Session has no active turn. Start a new turn with POST /stream.",
- },
- { status: 409 },
- ),
- );
- server.use(
- http.post(
- `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,
- async ({ request }) => {
- requests.push(await request.json());
- return streamSseResponse(
- requests.length === 1
- ? failureChunks
- : assistantTextChunks("Retry succeeded.", {
- messageId: "retried-response",
- }),
- { abortSignal: request.signal },
- );
- },
- ),
- http.post(
- `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/messages/pending`,
- queueRequest,
- ),
- );
-
- renderHost();
- await typeAndSend("Please try this task");
- await screen.findByText(errorText);
- await waitFor(() =>
- expect(getOrCreateCopilotChatRuntime(TEST_SESSION_ID).chat.status).toBe(
- status,
- ),
- );
-
- await userEvent
- .setup()
- .click(screen.getByRole("button", { name: /try again/i }));
-
- await waitFor(() => expect(requests).toHaveLength(2));
- expect(requests[1]).toMatchObject({ message: "Please try this task" });
- expect(await screen.findByText("Retry succeeded.")).toBeDefined();
- expect(queueRequest).not.toHaveBeenCalled();
- },
- 15_000,
- );
-
- it("surfaces an SSE error chunk to the user", async () => {
- const chunks: UIMessageChunk[] = [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "error", errorText: "Backend went sideways." },
- ];
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks,
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- expect(
- await screen.findByText(/backend went sideways\./i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
+ beforeEach(() => {
+ streamPath.runtime = path === "stream runtime";
});
- it("opens the rate-limit dialog on HTTP 429 'usage limit'", async () => {
- server.use(
- copilotStreamErrorHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- status: 429,
- body: { detail: "You've reached your usage limit. Try again later." },
- }),
+ describe("Otto streaming — error paths", () => {
+ it.each(["ready", "error"] as const)(
+ "retries an empty response with a fresh stream when status is %s",
+ async (status) => {
+ const errorText = "The model returned an empty response.";
+ const failureChunks = assistantTextChunks(
+ `[__COPILOT_RETRYABLE_ERROR_a9c2__] ${errorText}`,
+ { messageId: "failed-response" },
+ );
+ if (status === "error") {
+ failureChunks.splice(-1, 1, { type: "error", errorText });
+ }
+ const requests: unknown[] = [];
+ const queueRequest = vi.fn(() =>
+ HttpResponse.json(
+ {
+ detail:
+ "Session has no active turn. Start a new turn with POST /stream.",
+ },
+ { status: 409 },
+ ),
+ );
+ server.use(
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,
+ async ({ request }) => {
+ requests.push(await request.json());
+ return streamSseResponse(
+ requests.length === 1
+ ? failureChunks
+ : assistantTextChunks("Retry succeeded.", {
+ messageId: "retried-response",
+ }),
+ { abortSignal: request.signal },
+ );
+ },
+ ),
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/messages/pending`,
+ queueRequest,
+ ),
+ );
+
+ renderHost();
+ await typeAndSend("Please try this task");
+ await screen.findByText(errorText);
+ await waitFor(() =>
+ expect(settledStatus(path)).toBe(
+ path === "stream runtime" ? RUNTIME_PHASE[status] : status,
+ ),
+ );
+
+ await userEvent
+ .setup()
+ .click(screen.getByRole("button", { name: /try again/i }));
+
+ await waitFor(() => expect(requests).toHaveLength(2));
+ expect(requests[1]).toMatchObject({ message: "Please try this task" });
+ expect(await screen.findByText("Retry succeeded.")).toBeDefined();
+ expect(queueRequest).not.toHaveBeenCalled();
+ },
+ 15_000,
);
- renderHost();
- await typeAndSend("rate limited please");
-
- // useCopilotStream's rate-limit branch sets rateLimitMessage, which the
- // RateLimitGate translates into a Dialog with this title.
- expect(
- await screen.findByText(/daily usage limit reached/i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- });
+ it("surfaces an SSE error chunk to the user", async () => {
+ const chunks: UIMessageChunk[] = [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "error", errorText: "Backend went sideways." },
+ ];
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks,
+ }),
+ );
- it("clears kickoff recovery state after an HTTP 429", async () => {
- const expertId = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";
- flagState.experts = true;
- server.use(
- http.get("*/api/experts/identities", () =>
- HttpResponse.json([
- {
- id: expertId,
- name: "Maria",
- avatar_url: null,
- role: "Operations expert",
- is_archived: false,
- },
- ]),
- ),
- copilotStreamErrorHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- status: 429,
- body: { detail: "You've reached your usage limit. Try again later." },
- }),
- );
+ renderHost();
+ await typeAndSend("hi");
- renderHost({
- searchParams: `?sessionId=${TEST_SESSION_ID}&expertId=${expertId}&kickoff=1`,
- sessionOverride: { expert_id: expertId },
+ expect(
+ await screen.findByText(/backend went sideways\./i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
});
- expect(
- await screen.findByText(/daily usage limit reached/i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- await waitFor(() =>
- expect(getKickoffStatus("test-user", expertId)).toBe("idle"),
- );
- expect(
- window.localStorage.getItem(kickoffStorageKey("test-user", expertId)),
- ).toBeNull();
- expect(useCopilotStreamStore.getState().getCoord(TEST_SESSION_ID)).toEqual({
- lastSubmittedMessageText: null,
- lastSubmittedKickoffExpertId: null,
- lastSubmittedKickoffAttemptToken: null,
+ it("opens the rate-limit dialog on HTTP 429 'usage limit'", async () => {
+ server.use(
+ copilotStreamErrorHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ status: 429,
+ body: { detail: "You've reached your usage limit. Try again later." },
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("rate limited please");
+
+ // useCopilotStream's rate-limit branch sets rateLimitMessage, which the
+ // RateLimitGate translates into a Dialog with this title.
+ expect(
+ await screen.findByText(/daily usage limit reached/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
});
- expect(useCopilotUIStore.getState().initialPrompt).toBeNull();
- expect(
- useCopilotStreamStore
- .getState()
- .getMessageSnapshot(TEST_SESSION_ID)
- .filter((message) => message.role === "user"),
- ).toHaveLength(0);
- });
- it("surfaces an HTTP 500 response as a visible error", async () => {
- server.use(
- copilotStreamErrorHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- status: 500,
- body: "kaboom",
- }),
- );
+ it("clears kickoff recovery state after an HTTP 429", async () => {
+ const expertId = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";
+ flagState.experts = true;
+ server.use(
+ http.get("*/api/experts/identities", () =>
+ HttpResponse.json([
+ {
+ id: expertId,
+ name: "Maria",
+ avatar_url: null,
+ role: "Operations expert",
+ is_archived: false,
+ },
+ ]),
+ ),
+ copilotStreamErrorHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ status: 429,
+ body: { detail: "You've reached your usage limit. Try again later." },
+ }),
+ );
- renderHost();
- await typeAndSend("hi");
+ renderHost({
+ searchParams: `?sessionId=${TEST_SESSION_ID}&expertId=${expertId}&kickoff=1`,
+ sessionOverride: { expert_id: expertId },
+ });
- expect(
- await screen.findByText(/kaboom/i, undefined, { timeout: 5000 }),
- ).toBeDefined();
- });
+ expect(
+ await screen.findByText(/daily usage limit reached/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ await waitFor(() =>
+ expect(getKickoffStatus("test-user", expertId)).toBe("idle"),
+ );
+ expect(
+ window.localStorage.getItem(kickoffStorageKey("test-user", expertId)),
+ ).toBeNull();
+ expect(
+ useCopilotStreamStore.getState().getCoord(TEST_SESSION_ID),
+ ).toEqual({
+ lastSubmittedMessageText: null,
+ lastSubmittedKickoffExpertId: null,
+ lastSubmittedKickoffAttemptToken: null,
+ });
+ expect(useCopilotUIStore.getState().initialPrompt).toBeNull();
+ const userRows =
+ path === "stream runtime"
+ ? getTurnRuntime(TEST_SESSION_ID)
+ .getSnapshot()
+ .segments.filter((seg) => seg.kind === "user")
+ : useCopilotStreamStore
+ .getState()
+ .getMessageSnapshot(TEST_SESSION_ID)
+ .filter((message) => message.role === "user");
+ expect(userRows).toHaveLength(0);
+ });
- it("preserves the partial assistant text when an error chunk arrives mid-stream", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "text-start", id: "t1" },
- { type: "text-delta", id: "t1", delta: "Partial response so far." },
- { type: "text-end", id: "t1" },
- { type: "error", errorText: "Stream blew up." },
- ],
- }),
- );
+ it("surfaces an HTTP 500 response as a visible error", async () => {
+ server.use(
+ copilotStreamErrorHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ status: 500,
+ body: "kaboom",
+ }),
+ );
- renderHost();
- await typeAndSend("hi");
-
- // Both the partial text and the error must be visible — losing the
- // partial would silently drop work the model already did, and hiding
- // the error would leave the user staring at a stalled bubble.
- expect(
- await screen.findByText("Partial response so far.", undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- expect(await screen.findByText(/stream blew up\./i)).toBeDefined();
- });
+ renderHost();
+ await typeAndSend("hi");
- it("keeps the chat input enabled after an HTTP 500 so the user can retry", async () => {
- server.use(
- copilotStreamErrorHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- status: 500,
- body: "kaboom",
- }),
- );
+ expect(
+ await screen.findByText(/kaboom/i, undefined, { timeout: 5000 }),
+ ).toBeDefined();
+ });
- renderHost();
- await typeAndSend("hi");
+ it("preserves the partial assistant text when an error chunk arrives mid-stream", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "text-start", id: "t1" },
+ { type: "text-delta", id: "t1", delta: "Partial response so far." },
+ { type: "text-end", id: "t1" },
+ { type: "error", errorText: "Stream blew up." },
+ ],
+ }),
+ );
- await screen.findByText(/kaboom/i, undefined, { timeout: 5000 });
+ renderHost();
+ await typeAndSend("hi");
+
+ // Both the partial text and the error must be visible — losing the
+ // partial would silently drop work the model already did, and hiding
+ // the error would leave the user staring at a stalled bubble.
+ expect(
+ await screen.findByText("Partial response so far.", undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ expect(await screen.findByText(/stream blew up\./i)).toBeDefined();
+ });
- // Input must remain enabled for retries; locking it on stream error
- // would strand the user with no way to send a follow-up.
- await waitFor(() => {
- const input = screen.getByLabelText(
- /chat message input/i,
- ) as HTMLTextAreaElement;
- expect(input.disabled).toBe(false);
+ it("keeps the chat input enabled after an HTTP 500 so the user can retry", async () => {
+ server.use(
+ copilotStreamErrorHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ status: 500,
+ body: "kaboom",
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("hi");
+
+ await screen.findByText(/kaboom/i, undefined, { timeout: 5000 });
+
+ // Input must remain enabled for retries; locking it on stream error
+ // would strand the user with no way to send a follow-up.
+ await waitFor(() => {
+ const input = screen.getByLabelText(
+ /chat message input/i,
+ ) as HTMLTextAreaElement;
+ expect(input.disabled).toBe(false);
+ });
+ expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();
});
- expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();
});
-});
-describe("AutoPilot streaming — our usage cap next to a linked subscription", () => {
- function platformOffer(): AIConnectionOffer {
- return {
- offer_id: "platform:deployment",
- provider_family: "autogpt",
- auth_provider: "platform",
- display_name: "AutoGPT Platform",
- auth_method: "deployment",
- credential_id: null,
- backed_by_label: "Your AutoGPT plan",
- description: "Runs on your AutoGPT plan.",
- state: "ready",
- selectable: true,
- is_default: true,
- tiers: [],
- limitations: [],
- lock_reason: null,
- unlock_href: null,
- };
- }
-
- function chatgptOffer(): AIConnectionOffer {
- return {
- ...platformOffer(),
- offer_id: "codex:cred-1",
- provider_family: "openai",
- auth_provider: "codex",
- display_name: "ChatGPT",
- auth_method: "chatgpt_oauth",
- credential_id: "cred-1",
- is_default: false,
+ describe("AutoPilot streaming — our usage cap next to a linked subscription", () => {
+ function platformOffer(): AIConnectionOffer {
+ return {
+ offer_id: "platform:deployment",
+ provider_family: "autogpt",
+ auth_provider: "platform",
+ display_name: "AutoGPT Platform",
+ auth_method: "deployment",
+ credential_id: null,
+ backed_by_label: "Your AutoGPT plan",
+ description: "Runs on your AutoGPT plan.",
+ state: "ready",
+ selectable: true,
+ is_default: true,
+ tiers: [],
+ limitations: [],
+ lock_reason: null,
+ unlock_href: null,
+ };
+ }
+
+ function chatgptOffer(): AIConnectionOffer {
+ return {
+ ...platformOffer(),
+ offer_id: "codex:cred-1",
+ provider_family: "openai",
+ auth_provider: "codex",
+ display_name: "ChatGPT",
+ auth_method: "chatgpt_oauth",
+ credential_id: "cred-1",
+ is_default: false,
+ };
+ }
+
+ // What the backend's admission check sends once it refuses on our own
+ // daily budget: a 429 whose body is the typed envelope, not a bare string.
+ const ourCap = {
+ detail: {
+ kind: "usage_limit",
+ message: "You've reached your daily usage limit. Resets in 1h 0m.",
+ authProvider: "platform",
+ credentialId: null,
+ resetsAt: null,
+ retryable: false,
+ reconnectFixesIt: false,
+ },
};
- }
-
- // What the backend's admission check sends once it refuses on our own
- // daily budget: a 429 whose body is the typed envelope, not a bare string.
- const ourCap = {
- detail: {
- kind: "usage_limit",
- message: "You've reached your daily usage limit. Resets in 1h 0m.",
- authProvider: "platform",
- credentialId: null,
- resetsAt: null,
- retryable: false,
- reconnectFixesIt: false,
- },
- };
- it("keeps the plan dialog for our cap and offers the linked subscription beside the upgrade", async () => {
- let switchedTo: unknown = null;
- server.use(
- copilotStreamErrorHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- status: 429,
- body: ourCap,
- }),
- getGetV2ListChatConnectionsMockHandler200({
- offers: [platformOffer(), chatgptOffer()],
- }),
- getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200(
- async ({ request }) => {
- switchedTo = await request.json();
- return {};
- },
- ),
- );
+ it("keeps the plan dialog for our cap and offers the linked subscription beside the upgrade", async () => {
+ let switchedTo: unknown = null;
+ server.use(
+ copilotStreamErrorHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ status: 429,
+ body: ourCap,
+ }),
+ getGetV2ListChatConnectionsMockHandler200({
+ offers: [platformOffer(), chatgptOffer()],
+ }),
+ getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200(
+ async ({ request }) => {
+ switchedTo = await request.json();
+ return {};
+ },
+ ),
+ );
- renderHost();
- await typeAndSend("over the cap");
-
- // Our own cap, so our own dialog: the upgrade path survives ...
- expect(
- await screen.findByText(/daily usage limit reached/i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- expect(screen.queryByText(/hit this connection's limit/i)).toBeNull();
- expect(
- screen.getByRole("button", { name: /upgrade plan|contact us/i }),
- ).toBeDefined();
-
- // ... and the linked subscription is offered next to it, because the cap
- // does not apply to a turn billed to the user's own credential.
- const user = userEvent.setup();
- await user.click(
- await screen.findByRole(
- "button",
- { name: /continue on chatgpt/i },
- { timeout: 5000 },
- ),
- );
+ renderHost();
+ await typeAndSend("over the cap");
+
+ // Our own cap, so our own dialog: the upgrade path survives ...
+ expect(
+ await screen.findByText(/daily usage limit reached/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ expect(screen.queryByText(/hit this connection's limit/i)).toBeNull();
+ expect(
+ screen.getByRole("button", { name: /upgrade plan|contact us/i }),
+ ).toBeDefined();
+
+ // ... and the linked subscription is offered next to it, because the cap
+ // does not apply to a turn billed to the user's own credential.
+ const user = userEvent.setup();
+ await user.click(
+ await screen.findByRole(
+ "button",
+ { name: /continue on chatgpt/i },
+ { timeout: 5000 },
+ ),
+ );
- await waitFor(() =>
- expect(switchedTo).toEqual({
- llm_auth_provider: "codex",
- llm_credential_id: "cred-1",
- }),
- );
- await waitFor(() =>
- expect(screen.queryByText(/daily usage limit reached/i)).toBeNull(),
- );
- });
+ await waitFor(() =>
+ expect(switchedTo).toEqual({
+ llm_auth_provider: "codex",
+ llm_credential_id: "cred-1",
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.queryByText(/daily usage limit reached/i)).toBeNull(),
+ );
+ });
- it("offers nothing to continue on when the platform is the only connection", async () => {
- server.use(
- copilotStreamErrorHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- status: 429,
- body: ourCap,
- }),
- getGetV2ListChatConnectionsMockHandler200({
- offers: [platformOffer()],
- }),
- );
+ it("offers nothing to continue on when the platform is the only connection", async () => {
+ server.use(
+ copilotStreamErrorHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ status: 429,
+ body: ourCap,
+ }),
+ getGetV2ListChatConnectionsMockHandler200({
+ offers: [platformOffer()],
+ }),
+ );
- renderHost();
- await typeAndSend("over the cap");
-
- expect(
- await screen.findByText(/daily usage limit reached/i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- expect(
- screen.getByRole("button", { name: /upgrade plan|contact us/i }),
- ).toBeDefined();
- // The connection that just refused is never offered back. Were it not
- // excluded, "Continue on AutoGPT Platform" would appear once the offers
- // load, so give that long enough to have happened.
- await expect(
- screen.findByRole("button", { name: /continue on/i }, { timeout: 1500 }),
- ).rejects.toThrow();
- });
+ renderHost();
+ await typeAndSend("over the cap");
+
+ expect(
+ await screen.findByText(/daily usage limit reached/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: /upgrade plan|contact us/i }),
+ ).toBeDefined();
+ // The connection that just refused is never offered back. Were it not
+ // excluded, "Continue on AutoGPT Platform" would appear once the offers
+ // load, so give that long enough to have happened.
+ await expect(
+ screen.findByRole(
+ "button",
+ { name: /continue on/i },
+ { timeout: 1500 },
+ ),
+ ).rejects.toThrow();
+ });
- it("treats a mid-turn limit on the platform route as the provider's, not ours", async () => {
- // A self-host runs its own OpenRouter or local gateway on the "platform"
- // route, so its upstream 429 arrives with the same authProvider as our
- // cap. It came on the stream, mid-turn, which our cap never does -- and
- // it must not be answered with "upgrade your plan" for an account we
- // do not bill.
- const chunks: UIMessageChunk[] = [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- {
- type: "data-provider-failure",
- data: {
- kind: "usage_limit",
- message: "OpenRouter rate-limited this deployment.",
- authProvider: "platform",
- credentialId: null,
- resetsAt: null,
- retryable: false,
- reconnectFixesIt: false,
+ it("treats a mid-turn limit on the platform route as the provider's, not ours", async () => {
+ // A self-host runs its own OpenRouter or local gateway on the "platform"
+ // route, so its upstream 429 arrives with the same authProvider as our
+ // cap. It came on the stream, mid-turn, which our cap never does -- and
+ // it must not be answered with "upgrade your plan" for an account we
+ // do not bill.
+ const chunks: UIMessageChunk[] = [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ {
+ type: "data-provider-failure",
+ data: {
+ kind: "usage_limit",
+ message: "OpenRouter rate-limited this deployment.",
+ authProvider: "platform",
+ credentialId: null,
+ resetsAt: null,
+ retryable: false,
+ reconnectFixesIt: false,
+ },
},
- },
- { type: "error", errorText: "OpenRouter rate-limited this deployment." },
- ];
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks,
- }),
- getGetV2ListChatConnectionsMockHandler200({
- offers: [platformOffer()],
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
+ {
+ type: "error",
+ errorText: "OpenRouter rate-limited this deployment.",
+ },
+ ];
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks,
+ }),
+ getGetV2ListChatConnectionsMockHandler200({
+ offers: [platformOffer()],
+ }),
+ );
- expect(
- await screen.findByText(/hit this connection's limit/i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- expect(screen.queryByText(/daily usage limit reached/i)).toBeNull();
+ renderHost();
+ await typeAndSend("hi");
+
+ expect(
+ await screen.findByText(/hit this connection's limit/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ expect(screen.queryByText(/daily usage limit reached/i)).toBeNull();
+ });
});
});
+
+// The runtime settles a turn in its own phase, which the page maps to a status.
+const RUNTIME_PHASE = { ready: "finished", error: "failed" } as const;
+
+function settledStatus(path: StreamPath) {
+ return path === "stream runtime"
+ ? getTurnRuntime(TEST_SESSION_ID).getSnapshot().phase
+ : getOrCreateCopilotChatRuntime(TEST_SESSION_ID).chat.status;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-lifecycle.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-lifecycle.test.tsx
index c34705e3e0..096383037b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-lifecycle.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-lifecycle.test.tsx
@@ -6,10 +6,11 @@ import {
} from "@/tests/integrations/copilot-sse";
import { screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { resetCopilotChatRegistry } from "../copilotChatRegistry";
import {
clickStop,
renderHost,
+ resetChatRuntimes,
+ STREAM_PATHS,
TEST_BACKEND_BASE_URL,
TEST_SESSION_ID,
typeAndSend,
@@ -38,112 +39,124 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),
}));
+const streamPath = vi.hoisted(() => ({ runtime: false }));
+
vi.mock("@/services/feature-flags/use-get-flag", () => ({
Flag: {
CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ COPILOT_STREAM_RUNTIME: "copilot-stream-runtime",
},
- useGetFlag: () => false,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
}));
beforeEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
});
afterEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
});
-describe("Otto streaming — submit / stop lifecycle", () => {
- it("swaps the submit button to Stop while streaming and back to Submit when done", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: assistantTextChunks("Hi."),
- delayMsBetweenChunks: 30,
- }),
- );
-
- renderHost();
- expect(screen.getByRole("button", { name: /submit/i })).toBeDefined();
-
- await typeAndSend("hi");
-
- expect(await screen.findByRole("button", { name: /stop/i })).toBeDefined();
-
- expect(
- await screen.findByText("Hi.", undefined, { timeout: 5000 }),
- ).toBeDefined();
- await waitFor(() => {
- expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();
- });
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
+ beforeEach(() => {
+ streamPath.runtime = path === "stream runtime";
});
- it("ends the stream and shows the manual-stop marker when Stop is clicked mid-stream", async () => {
- server.use(
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: [
- { type: "start", messageId: "msg-1" },
- { type: "start-step" },
- { type: "text-start", id: "t1" },
- { type: "text-delta", id: "t1", delta: "Streaming " },
- { type: "text-delta", id: "t1", delta: "in progress " },
- { type: "text-delta", id: "t1", delta: "should be cut off" },
- { type: "text-end", id: "t1" },
- { type: "finish-step" },
- { type: "finish" },
- ],
- // Setup + first delta emit instantly; stall before the "should be cut
- // off" delta so the stop click has a wide window to land.
- perChunkDelaysMs: [0, 0, 0, 0, 5000, 0, 0, 0, 0],
- }),
- );
-
- renderHost();
- await typeAndSend("hi");
-
- // Wait for the first delta so Stop has something live to abort.
- await screen.findByText(/streaming/i, undefined, { timeout: 5000 });
-
- await clickStop();
-
- expect(
- await screen.findByText(/task stopped/i, undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
- // Post-stop chunks never reach the bubble.
- expect(screen.queryByText(/should be cut off/i)).toBeNull();
+ describe("Otto streaming — submit / stop lifecycle", () => {
+ it("swaps the submit button to Stop while streaming and back to Submit when done", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: assistantTextChunks("Hi."),
+ delayMsBetweenChunks: 30,
+ }),
+ );
+
+ renderHost();
+ expect(screen.getByRole("button", { name: /submit/i })).toBeDefined();
+
+ await typeAndSend("hi");
+
+ expect(
+ await screen.findByRole("button", { name: /stop/i }),
+ ).toBeDefined();
+
+ expect(
+ await screen.findByText("Hi.", undefined, { timeout: 5000 }),
+ ).toBeDefined();
+ await waitFor(() => {
+ expect(screen.queryByRole("button", { name: /stop/i })).toBeNull();
+ });
+ });
+
+ it("ends the stream and shows the manual-stop marker when Stop is clicked mid-stream", async () => {
+ server.use(
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: [
+ { type: "start", messageId: "msg-1" },
+ { type: "start-step" },
+ { type: "text-start", id: "t1" },
+ { type: "text-delta", id: "t1", delta: "Streaming " },
+ { type: "text-delta", id: "t1", delta: "in progress " },
+ { type: "text-delta", id: "t1", delta: "should be cut off" },
+ { type: "text-end", id: "t1" },
+ { type: "finish-step" },
+ { type: "finish" },
+ ],
+ // Setup + first delta emit instantly; stall before the "should be cut
+ // off" delta so the stop click has a wide window to land.
+ perChunkDelaysMs: [0, 0, 0, 0, 5000, 0, 0, 0, 0],
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("hi");
+
+ // Wait for the first delta so Stop has something live to abort.
+ await screen.findByText(/streaming/i, undefined, { timeout: 5000 });
+
+ await clickStop();
+
+ expect(
+ await screen.findByText(/task stopped/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ // Post-stop chunks never reach the bubble.
+ expect(screen.queryByText(/should be cut off/i)).toBeNull();
+ });
});
-});
-describe("Otto streaming — resume on mount", () => {
- it("issues a GET resume and renders streamed content when the session has an active_stream", async () => {
- server.use(
- copilotResumeHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: assistantTextChunks("Resumed content here."),
- }),
- );
-
- renderHost({
- sessionOverride: {
- active_stream: {
- turn_id: "turn-1",
- last_message_id: "msg-prev",
- started_at: "2026-05-13T00:00:00Z",
+ describe("Otto streaming — resume on mount", () => {
+ it("issues a GET resume and renders streamed content when the session has an active_stream", async () => {
+ server.use(
+ copilotResumeHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: assistantTextChunks("Resumed content here."),
+ }),
+ );
+
+ renderHost({
+ sessionOverride: {
+ active_stream: {
+ turn_id: "turn-1",
+ last_message_id: "msg-prev",
+ started_at: "2026-05-13T00:00:00Z",
+ },
},
- },
- });
+ });
- expect(
- await screen.findByText("Resumed content here.", undefined, {
- timeout: 5000,
- }),
- ).toBeDefined();
+ expect(
+ await screen.findByText("Resumed content here.", undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ });
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/compaction-progress.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/compaction-progress.test.tsx
index b156f9f1b8..0c8fd6877f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/compaction-progress.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/compaction-progress.test.tsx
@@ -4,10 +4,11 @@ import { copilotStreamHandler } from "@/tests/integrations/copilot-sse";
import { screen, waitFor } from "@testing-library/react";
import type { UIMessageChunk } from "ai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { resetCopilotChatRegistry } from "../copilotChatRegistry";
import {
renderHost,
+ resetChatRuntimes,
sessionHandler,
+ STREAM_PATHS,
TEST_BACKEND_BASE_URL,
TEST_SESSION_ID,
typeAndSend,
@@ -44,12 +45,16 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
// Keep mode/model toggles and artifacts off so the chat input renders a
// single, predictable Submit button.
+const streamPath = vi.hoisted(() => ({ runtime: false }));
+
vi.mock("@/services/feature-flags/use-get-flag", () => ({
Flag: {
CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ COPILOT_STREAM_RUNTIME: "copilot-stream-runtime",
},
- useGetFlag: () => false,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
}));
// Shared chunk builders — every scenario below is "open row → phase(s) →
@@ -327,370 +332,380 @@ const SUMMARIZING_HOLD_INDEX = COMPACTION_TURN.findIndex(
(c) => c.type === "tool-output-available",
);
-describe("context compaction progress", () => {
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
beforeEach(() => {
- resetCopilotChatRegistry();
- server.use(
- sessionHandler(),
- // A uniform 15ms gap keeps the stream from resolving inside a single
- // microtask tick, but the "summarizing" phase itself only spans the
- // single gap between the `data-compaction` chunk and
- // `tool-output-available` — at 15ms that's narrower than
- // `waitFor`'s ~50ms poll interval, so the assertion below could miss
- // it entirely depending on scheduling. Hold specifically at that
- // gap for long enough to make the phase reliably observable.
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: COMPACTION_TURN,
- perChunkDelaysMs: COMPACTION_TURN.map((_, i) =>
- i === SUMMARIZING_HOLD_INDEX ? HOLD_MS : 15,
- ),
- }),
- );
- });
-
- afterEach(() => {
- resetCopilotChatRegistry();
+ streamPath.runtime = path === "stream runtime";
});
- it("shows a live bar while compacting, not a completed message", async () => {
- renderHost();
- await typeAndSend("summarise this");
+ describe("context compaction progress", () => {
+ beforeEach(() => {
+ resetChatRuntimes();
+ server.use(
+ sessionHandler(),
+ // A uniform 15ms gap keeps the stream from resolving inside a single
+ // microtask tick, but the "summarizing" phase itself only spans the
+ // single gap between the `data-compaction` chunk and
+ // `tool-output-available` — at 15ms that's narrower than
+ // `waitFor`'s ~50ms poll interval, so the assertion below could miss
+ // it entirely depending on scheduling. Hold specifically at that
+ // gap for long enough to make the phase reliably observable.
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: COMPACTION_TURN,
+ perChunkDelaysMs: COMPACTION_TURN.map((_, i) =>
+ i === SUMMARIZING_HOLD_INDEX ? HOLD_MS : 15,
+ ),
+ }),
+ );
+ });
- await waitFor(() => {
- expect(screen.getByRole("progressbar")).toBeDefined();
- expect(screen.getByText("Condensing our conversation…")).toBeDefined();
- // CompactionCard owns its own spinner/label — the generic
- // ThinkingIndicator must not double up alongside it. The tool row
- // (or, before it opens, the step-start marker) keeps `hasInflight`
- // true throughout the compaction turn, so this holds from the very
- // first chunk onward — not just once the bar is visible.
- expect(screen.queryByText("Thinking…")).toBeNull();
+ afterEach(() => {
+ resetChatRuntimes();
});
- });
- it("lands on the payoff copy with real numbers", async () => {
- renderHost();
- await typeAndSend("summarise this");
+ it("shows a live bar while compacting, not a completed message", async () => {
+ renderHost();
+ await typeAndSend("summarise this");
+
+ await waitFor(() => {
+ expect(screen.getByRole("progressbar")).toBeDefined();
+ expect(screen.getByText("Condensing our conversation…")).toBeDefined();
+ // CompactionCard owns its own spinner/label — the generic
+ // ThinkingIndicator must not double up alongside it. The tool row
+ // (or, before it opens, the step-start marker) keeps `hasInflight`
+ // true throughout the compaction turn, so this holds from the very
+ // first chunk onward — not just once the bar is visible.
+ expect(screen.queryByText("Thinking…")).toBeNull();
+ });
+ });
- await waitFor(() => {
- expect(
- screen.getByText(/Condensed 412 messages · 128K → 31K tokens/),
- ).toBeDefined();
- }, POST_HOLD_TIMEOUT);
- });
+ it("lands on the payoff copy with real numbers", async () => {
+ renderHost();
+ await typeAndSend("summarise this");
- it("never shows the old apologetic copy", async () => {
- renderHost();
- await typeAndSend("summarise this");
+ await waitFor(() => {
+ expect(
+ screen.getByText(/Condensed 412 messages · 128K → 31K tokens/),
+ ).toBeDefined();
+ }, POST_HOLD_TIMEOUT);
+ });
- await waitFor(() => {
- expect(screen.getByText("All caught up.")).toBeDefined();
- }, POST_HOLD_TIMEOUT);
- expect(screen.queryByText(/Earlier messages were summarized/)).toBeNull();
- });
+ it("never shows the old apologetic copy", async () => {
+ renderHost();
+ await typeAndSend("summarise this");
- it("keeps a settled compaction row out of a collapsed tool group when another tool call follows it", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: COMPACTION_THEN_TOOL_TURN,
- delayMsBetweenChunks: 15,
- }),
- );
-
- renderHost();
- await typeAndSend("search and summarise");
-
- await waitFor(() => {
- expect(
- screen.getByText(/Condensed 412 messages · 128K → 31K tokens/),
- ).toBeDefined();
+ await waitFor(() => {
+ expect(screen.getByText("All caught up.")).toBeDefined();
+ }, POST_HOLD_TIMEOUT);
+ expect(screen.queryByText(/Earlier messages were summarized/)).toBeNull();
});
- // If the compaction row had folded into a CollapsedToolGroup with the
- // adjacent web_search call, the payoff copy above would be hidden
- // behind a "N tool calls completed" toggle instead of standing alone.
- expect(screen.queryByText(/tool calls/)).toBeNull();
- });
- it("renders nothing for a compaction that failed", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: FAILED_COMPACTION_TURN,
- delayMsBetweenChunks: 15,
- }),
- );
-
- renderHost();
- await typeAndSend("summarise this");
-
- await waitFor(() => {
- expect(screen.getByText("Carrying on regardless.")).toBeDefined();
+ it("keeps a settled compaction row out of a collapsed tool group when another tool call follows it", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: COMPACTION_THEN_TOOL_TURN,
+ delayMsBetweenChunks: 15,
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("search and summarise");
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(/Condensed 412 messages · 128K → 31K tokens/),
+ ).toBeDefined();
+ });
+ // If the compaction row had folded into a CollapsedToolGroup with the
+ // adjacent web_search call, the payoff copy above would be hidden
+ // behind a "N tool calls completed" toggle instead of standing alone.
+ expect(screen.queryByText(/tool calls/)).toBeNull();
});
- // A failed compaction condensed nothing — neither the live copy nor
- // the settled "Condensed…" claim may render for it.
- expect(screen.queryByText(/Condensing our conversation/)).toBeNull();
- expect(screen.queryByText(/Condensed/)).toBeNull();
- expect(screen.queryByRole("progressbar")).toBeNull();
- });
- it("tells the user the context was reset when history was dropped", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: DROPPED_COMPACTION_TURN,
- delayMsBetweenChunks: 15,
- }),
- );
-
- renderHost();
- await typeAndSend("summarise this");
-
- await waitFor(() => {
- expect(screen.getByText("Starting over from here.")).toBeDefined();
- expect(
- screen.getByText(
- "Started a fresh context — earlier messages were dropped",
- ),
- ).toBeDefined();
+ // `tool-output-error` is not on the backend's wire (design §1.3), which
+ // closes every compaction row with an output; the runtime does not read
+ // it, and CI refuses a skipped test, so the case exists on one path only.
+ const sdkOnly = path === "AI SDK" ? it : () => {};
+ sdkOnly("renders nothing for a compaction that failed", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: FAILED_COMPACTION_TURN,
+ delayMsBetweenChunks: 15,
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("summarise this");
+
+ await waitFor(() => {
+ expect(screen.getByText("Carrying on regardless.")).toBeDefined();
+ });
+ // A failed compaction condensed nothing — neither the live copy nor
+ // the settled "Condensed…" claim may render for it.
+ expect(screen.queryByText(/Condensing our conversation/)).toBeNull();
+ expect(screen.queryByText(/Condensed/)).toBeNull();
+ expect(screen.queryByRole("progressbar")).toBeNull();
});
- // A drop condensed nothing: no payoff claim, no lingering bar.
- expect(screen.queryByText(/Condensed/)).toBeNull();
- expect(screen.queryByRole("progressbar")).toBeNull();
- });
- it("renders nothing for a row retired by an aborted prediction", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: ABORTED_COMPACTION_TURN,
- delayMsBetweenChunks: 15,
- }),
- );
-
- renderHost();
- await typeAndSend("quick question");
-
- await waitFor(() => {
- expect(screen.getByText("No condensing needed.")).toBeDefined();
+ it("tells the user the context was reset when history was dropped", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: DROPPED_COMPACTION_TURN,
+ delayMsBetweenChunks: 15,
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("summarise this");
+
+ await waitFor(() => {
+ expect(screen.getByText("Starting over from here.")).toBeDefined();
+ expect(
+ screen.getByText(
+ "Started a fresh context — earlier messages were dropped",
+ ),
+ ).toBeDefined();
+ });
+ // A drop condensed nothing: no payoff claim, no lingering bar.
+ expect(screen.queryByText(/Condensed/)).toBeNull();
+ expect(screen.queryByRole("progressbar")).toBeNull();
});
- // The abort sentinel (output "") must not read as a real compaction —
- // neither the live copy nor the settled payoff copy may survive.
- expect(screen.queryByText(/Condensing our conversation/)).toBeNull();
- expect(screen.queryByText(/Condensed the conversation/)).toBeNull();
- expect(screen.queryByRole("progressbar")).toBeNull();
- });
- it("keeps the first cycle settled while a second cycle streams", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: TWO_CYCLE_TURN,
- perChunkDelaysMs: TWO_CYCLE_TURN.map((_, i) =>
- i === SECOND_CYCLE_HOLD_INDEX ? HOLD_MS : 15,
- ),
- }),
- );
-
- renderHost();
- await typeAndSend("summarise twice");
-
- await waitFor(() => {
- // Second cycle live in `summarizing`…
- expect(screen.getByText("Condensing our conversation…")).toBeDefined();
- // …while the first row keeps its settled payoff copy…
- expect(
- screen.getByText(/Condensed the conversation · 128K → 31K tokens/),
- ).toBeDefined();
- // …and only the live row carries a progress bar. Without the
- // per-row phase gate, the second cycle's phase re-animates the
- // first (closed) row and two bars render.
- expect(screen.getAllByRole("progressbar")).toHaveLength(1);
+ it("renders nothing for a row retired by an aborted prediction", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: ABORTED_COMPACTION_TURN,
+ delayMsBetweenChunks: 15,
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("quick question");
+
+ await waitFor(() => {
+ expect(screen.getByText("No condensing needed.")).toBeDefined();
+ });
+ // The abort sentinel (output "") must not read as a real compaction —
+ // neither the live copy nor the settled payoff copy may survive.
+ expect(screen.queryByText(/Condensing our conversation/)).toBeNull();
+ expect(screen.queryByText(/Condensed the conversation/)).toBeNull();
+ expect(screen.queryByRole("progressbar")).toBeNull();
});
- });
- it("retires the live bar when the stream dies after a compaction phase", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: DEAD_STREAM_TURN,
- perChunkDelaysMs: DEAD_STREAM_TURN.map((_, i) =>
- i === DEAD_STREAM_HOLD_INDEX ? HOLD_MS : 15,
- ),
- }),
- );
-
- renderHost();
- await typeAndSend("summarise this");
-
- // Live during the stream: the trailing `rebuilding` phase keeps the
- // bar up while the connection is open.
- await waitFor(() => {
- expect(screen.getByRole("progressbar")).toBeDefined();
+ it("keeps the first cycle settled while a second cycle streams", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: TWO_CYCLE_TURN,
+ perChunkDelaysMs: TWO_CYCLE_TURN.map((_, i) =>
+ i === SECOND_CYCLE_HOLD_INDEX ? HOLD_MS : 15,
+ ),
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("summarise twice");
+
+ await waitFor(() => {
+ // Second cycle live in `summarizing`…
+ expect(screen.getByText("Condensing our conversation…")).toBeDefined();
+ // …while the first row keeps its settled payoff copy…
+ expect(
+ screen.getByText(/Condensed the conversation · 128K → 31K tokens/),
+ ).toBeDefined();
+ // …and only the live row carries a progress bar. Without the
+ // per-row phase gate, the second cycle's phase re-animates the
+ // first (closed) row and two bars render.
+ expect(screen.getAllByRole("progressbar")).toHaveLength(1);
+ });
});
- // Once the stream closes with no trailing text, the streaming gate
- // must null the phase — the row settles instead of spinning forever.
- await waitFor(() => {
- expect(screen.queryByRole("progressbar")).toBeNull();
- expect(
- screen.getByText(/Condensed the conversation · 128K → 31K tokens/),
- ).toBeDefined();
- }, POST_HOLD_TIMEOUT);
- });
- it("keeps the bar live through the rebuild that follows the closed row", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: COMPACTION_TURN,
- perChunkDelaysMs: COMPACTION_TURN.map((_, i) =>
- i === REBUILDING_HOLD_INDEX ? HOLD_MS : 15,
- ),
- }),
- );
-
- renderHost();
- await typeAndSend("summarise this");
-
- // The tool row has already closed with its JSON output by this point;
- // the row must still be live and narrating the rebuild.
- await waitFor(() => {
- expect(screen.getByText("Reloading context…")).toBeDefined();
- // With the row closed, `hasInflight` is false — without the live-
- // compaction gate the ThinkingIndicator would stack its own spinner
- // and timer directly under the CompactionCard's.
- expect(screen.queryByText("Thinking…")).toBeNull();
+ it("retires the live bar when the stream dies after a compaction phase", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: DEAD_STREAM_TURN,
+ perChunkDelaysMs: DEAD_STREAM_TURN.map((_, i) =>
+ i === DEAD_STREAM_HOLD_INDEX ? HOLD_MS : 15,
+ ),
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("summarise this");
+
+ // Live during the stream: the trailing `rebuilding` phase keeps the
+ // bar up while the connection is open.
+ await waitFor(() => {
+ expect(screen.getByRole("progressbar")).toBeDefined();
+ });
+ // Once the stream closes with no trailing text, the streaming gate
+ // must null the phase — the row settles instead of spinning forever.
+ await waitFor(() => {
+ expect(screen.queryByRole("progressbar")).toBeNull();
+ expect(
+ screen.getByText(/Condensed the conversation · 128K → 31K tokens/),
+ ).toBeDefined();
+ }, POST_HOLD_TIMEOUT);
});
- expect(screen.getByRole("progressbar")).toBeDefined();
- });
- it("renders nothing for a row left open when the stream is interrupted", async () => {
- server.use(
- sessionHandler(),
- copilotStreamHandler({
- baseUrl: TEST_BACKEND_BASE_URL,
- sessionId: TEST_SESSION_ID,
- chunks: INTERRUPTED_OPEN_ROW_TURN,
- perChunkDelaysMs: INTERRUPTED_OPEN_ROW_TURN.map((_, i) =>
- i === INTERRUPTED_HOLD_INDEX ? HOLD_MS : 15,
- ),
- }),
- );
-
- renderHost();
- await typeAndSend("summarise this");
-
- // Live while the connection is open.
- await waitFor(() => {
+ it("keeps the bar live through the rebuild that follows the closed row", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: COMPACTION_TURN,
+ perChunkDelaysMs: COMPACTION_TURN.map((_, i) =>
+ i === REBUILDING_HOLD_INDEX ? HOLD_MS : 15,
+ ),
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("summarise this");
+
+ // The tool row has already closed with its JSON output by this point;
+ // the row must still be live and narrating the rebuild.
+ await waitFor(() => {
+ expect(screen.getByText("Reloading context…")).toBeDefined();
+ // With the row closed, `hasInflight` is false — without the live-
+ // compaction gate the ThinkingIndicator would stack its own spinner
+ // and timer directly under the CompactionCard's.
+ expect(screen.queryByText("Thinking…")).toBeNull();
+ });
expect(screen.getByRole("progressbar")).toBeDefined();
});
- // The row never closed, so once the stream is gone it is neither a live
- // bar nor a "Condensed…" claim — it disappears.
- await waitFor(() => {
- expect(screen.queryByRole("progressbar")).toBeNull();
- }, POST_HOLD_TIMEOUT);
- expect(screen.queryByText(/Condensed/)).toBeNull();
- expect(screen.queryByText(/Condensing/)).toBeNull();
- });
-});
-// A row restored from the DB never carries a `data-compaction` part — that
-// part only ever exists on a live stream. `getLatestCompactionPhase` reads
-// null in that case, and the tool part's persisted output makes it
-// `output-available`, so the card renders settled — this proves the
-// back-compat path for both the new JSON payload and the old plain-sentence
-// rows some sessions still have on disk.
-describe("compaction rows restored from the database", () => {
- beforeEach(() => {
- resetCopilotChatRegistry();
+ it("renders nothing for a row left open when the stream is interrupted", async () => {
+ server.use(
+ sessionHandler(),
+ copilotStreamHandler({
+ baseUrl: TEST_BACKEND_BASE_URL,
+ sessionId: TEST_SESSION_ID,
+ chunks: INTERRUPTED_OPEN_ROW_TURN,
+ perChunkDelaysMs: INTERRUPTED_OPEN_ROW_TURN.map((_, i) =>
+ i === INTERRUPTED_HOLD_INDEX ? HOLD_MS : 15,
+ ),
+ }),
+ );
+
+ renderHost();
+ await typeAndSend("summarise this");
+
+ // Live while the connection is open.
+ await waitFor(() => {
+ expect(screen.getByRole("progressbar")).toBeDefined();
+ });
+ // The row never closed, so once the stream is gone it is neither a live
+ // bar nor a "Condensed…" claim — it disappears.
+ await waitFor(() => {
+ expect(screen.queryByRole("progressbar")).toBeNull();
+ }, POST_HOLD_TIMEOUT);
+ expect(screen.queryByText(/Condensed/)).toBeNull();
+ expect(screen.queryByText(/Condensing/)).toBeNull();
+ });
});
- afterEach(() => {
- resetCopilotChatRegistry();
- });
+ // A row restored from the DB never carries a `data-compaction` part — that
+ // part only ever exists on a live stream. `getLatestCompactionPhase` reads
+ // null in that case, and the tool part's persisted output makes it
+ // `output-available`, so the card renders settled — this proves the
+ // back-compat path for both the new JSON payload and the old plain-sentence
+ // rows some sessions still have on disk.
+ describe("compaction rows restored from the database", () => {
+ beforeEach(() => {
+ resetChatRuntimes();
+ });
- it("renders new JSON rows with their numbers and no bar", async () => {
- const messages: SessionDetailResponseMessagesItem[] = [
- { role: "user", content: "hi", sequence: 0 },
- {
- role: "assistant",
- content: "",
- sequence: 1,
- tool_calls: [
- {
- id: "compaction-1",
- type: "function",
- function: { name: "context_compaction", arguments: "{}" },
- },
- ],
- },
- {
- role: "tool",
- tool_call_id: "compaction-1",
- sequence: 2,
- content: JSON.stringify({
- summary:
- "Earlier messages were summarized to fit within context limits.",
- tokensBefore: 128000,
- tokensAfter: 31000,
- }),
- },
- ];
- renderHost({ sessionOverride: { messages } });
-
- await waitFor(() => {
- expect(
- screen.getByText("Condensed the conversation · 128K → 31K tokens"),
- ).toBeDefined();
+ afterEach(() => {
+ resetChatRuntimes();
});
- expect(screen.queryByRole("progressbar")).toBeNull();
- });
- it("renders legacy plain-sentence rows without crashing", async () => {
- const messages: SessionDetailResponseMessagesItem[] = [
- { role: "user", content: "hi", sequence: 0 },
- {
- role: "assistant",
- content: "",
- sequence: 1,
- tool_calls: [
- {
- id: "compaction-1",
- type: "function",
- function: { name: "context_compaction", arguments: "{}" },
- },
- ],
- },
- {
- role: "tool",
- tool_call_id: "compaction-1",
- sequence: 2,
- content:
- "Earlier messages were summarized to fit within context limits.",
- },
- ];
- renderHost({ sessionOverride: { messages } });
-
- await waitFor(() => {
- expect(
- screen.getByText("Condensed the conversation to keep going"),
- ).toBeDefined();
+ it("renders new JSON rows with their numbers and no bar", async () => {
+ const messages: SessionDetailResponseMessagesItem[] = [
+ { role: "user", content: "hi", sequence: 0 },
+ {
+ role: "assistant",
+ content: "",
+ sequence: 1,
+ tool_calls: [
+ {
+ id: "compaction-1",
+ type: "function",
+ function: { name: "context_compaction", arguments: "{}" },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ tool_call_id: "compaction-1",
+ sequence: 2,
+ content: JSON.stringify({
+ summary:
+ "Earlier messages were summarized to fit within context limits.",
+ tokensBefore: 128000,
+ tokensAfter: 31000,
+ }),
+ },
+ ];
+ renderHost({ sessionOverride: { messages } });
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("Condensed the conversation · 128K → 31K tokens"),
+ ).toBeDefined();
+ });
+ expect(screen.queryByRole("progressbar")).toBeNull();
+ });
+
+ it("renders legacy plain-sentence rows without crashing", async () => {
+ const messages: SessionDetailResponseMessagesItem[] = [
+ { role: "user", content: "hi", sequence: 0 },
+ {
+ role: "assistant",
+ content: "",
+ sequence: 1,
+ tool_calls: [
+ {
+ id: "compaction-1",
+ type: "function",
+ function: { name: "context_compaction", arguments: "{}" },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ tool_call_id: "compaction-1",
+ sequence: 2,
+ content:
+ "Earlier messages were summarized to fit within context limits.",
+ },
+ ];
+ renderHost({ sessionOverride: { messages } });
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("Condensed the conversation to keep going"),
+ ).toBeDefined();
+ });
});
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts
index 5d3c26f6d9..28a707e046 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts
@@ -7,6 +7,7 @@ import { http, HttpResponse } from "msw";
import fs from "node:fs";
import path from "node:path";
import { expect } from "vitest";
+import { compareEntryIds } from "../../stream/turnConverter";
import {
renderHost,
TEST_BACKEND_BASE_URL,
@@ -56,9 +57,10 @@ interface TurnPlan {
}
/**
- * The backend as the chat sees it: a turn's frames published one by one into
- * a stream every connection replays from its first held entry, and a session
- * GET whose rows and `active_stream` follow the turn.
+ * The backend as the chat sees it: each turn's frames published one by one
+ * under its own turn id, persisted at every checkpoint, served whole to a
+ * resume without a cursor and from the cursor to one with it, and a session
+ * GET whose rows, `active_stream` and checkpoint follow the turn.
*/
export function createBackendSim(plans: TurnPlan[]) {
const state = {
@@ -66,8 +68,10 @@ export function createBackendSim(plans: TurnPlan[]) {
trimmedBefore: 0,
running: false,
startedAt: "",
- rows: [] as Row[],
+ committed: [] as Row[],
+ current: [] as Row[],
};
+ const turns = plans.map(simulatedTurn);
const published = new Map<number, number>();
const connections: { closed: boolean; cut: () => void }[] = [];
const wakers = new Set<() => void>();
@@ -77,17 +81,25 @@ export function createBackendSim(plans: TurnPlan[]) {
state.startedAt = new Date().toISOString();
state.trimmedBefore = 0;
state.running = true;
- state.rows = [...state.rows, ...leadingUserRows(plans[index].turn.rows)];
+ state.current = leadingUserRows(plans[index].turn.rows);
published.set(index, 0);
}
+ // A checkpoint names the rows a persist landed; the GET reads them from then on.
+ function persistThrough(index: number, end: number) {
+ const rows = plans[index].persistedRows ?? plans[index].turn.rows;
+ state.current = rows.filter((row) => Number(row.sequence ?? 0) < end);
+ }
+
// The backend persists, marks the turn completed and wakes any chained
// turn before it publishes the finish.
function endTurn(index: number) {
const plan = plans[index];
- const alreadyPersisted = leadingUserRows(plan.turn.rows).length;
- const turnRows = plan.persistedRows ?? plan.turn.rows;
- state.rows = [...state.rows, ...turnRows.slice(alreadyPersisted)];
+ state.committed = [
+ ...state.committed,
+ ...(plan.persistedRows ?? plan.turn.rows),
+ ];
+ state.current = [];
state.running = false;
if (plans[index + 1]?.chained) startTurn(index + 1);
}
@@ -95,10 +107,13 @@ export function createBackendSim(plans: TurnPlan[]) {
/** Publish the running turn's next `count` frames (default: all of them). */
function publish(count = Infinity) {
const index = state.turnIndex;
- const frames = plans[index].turn.frames;
+ const frames = turns[index].frames;
let next = published.get(index) ?? 0;
const target = Math.min(frames.length, next + count);
while (next < target) {
+ const checkpoint = turns[index].recordedCheckpoints.get(next);
+ if (checkpoint)
+ persistThrough(index, checkpoint.sequence + checkpoint.rows);
if (isFinish(frames[next])) endTurn(index);
next += 1;
published.set(index, next);
@@ -106,9 +121,38 @@ export function createBackendSim(plans: TurnPlan[]) {
wakers.forEach((wake) => wake());
}
- function open(turnIndex: number) {
- const frames = plans[turnIndex].turn.frames;
- let index = state.trimmedBefore;
+ function lastCheckpoint(index: number, before = Infinity) {
+ const end = Math.min(published.get(index) ?? 0, before);
+ for (let i = end - 1; i >= 0; i--) {
+ const checkpoint = turns[index].checkpoints.get(i);
+ if (checkpoint) return checkpoint;
+ }
+ return null;
+ }
+
+ function resume(turn: string, after: string) {
+ const index = turns.findIndex((t) => t.id === turn);
+ if (index === -1 || !published.has(index)) {
+ connections.push({ closed: true, cut() {} });
+ return HttpResponse.json({ reason: "expired" }, { status: 410 });
+ }
+ const frames = turns[index].frames;
+ let from = frames.findIndex((f) => compareEntryIds(f.id, after) > 0);
+ if (from === -1) from = frames.length;
+ const floor = index === state.turnIndex ? state.trimmedBefore : 0;
+ if (from < floor) {
+ connections.push({ closed: true, cut() {} });
+ return HttpResponse.json(
+ { reason: "trimmed", checkpoint: lastCheckpoint(index, floor) },
+ { status: 409 },
+ );
+ }
+ return open(index, from);
+ }
+
+ function open(turnIndex: number, from = state.trimmedBefore) {
+ const frames = turns[turnIndex].frames;
+ let index = from;
let cutRequested = false;
let wake: (() => void) | null = null;
const connection = {
@@ -168,7 +212,10 @@ export function createBackendSim(plans: TurnPlan[]) {
startTurn(state.turnIndex + 1);
return open(state.turnIndex);
}),
- http.get(STREAM_URL, () => {
+ http.get(STREAM_URL, ({ request }) => {
+ const params = new URL(request.url).searchParams;
+ const turn = params.get("turn");
+ if (turn !== null) return resume(turn, params.get("after") ?? "0-0");
if (!state.running) return new HttpResponse(null, { status: 204 });
return open(state.turnIndex);
}),
@@ -196,12 +243,13 @@ export function createBackendSim(plans: TurnPlan[]) {
oldest_sequence: null,
metadata: { dry_run: false, builder_graph_id: null },
expert_id: null,
- messages: numbered(state.rows),
+ messages: numbered([...state.committed, ...state.current]),
active_stream: state.running
? {
- turn_id: `drift-turn-${state.turnIndex}`,
+ turn_id: turns[state.turnIndex].id,
last_message_id: "0-0",
started_at: state.startedAt,
+ checkpoint: lastCheckpoint(state.turnIndex),
}
: null,
chat_status: state.running ? "running" : "idle",
@@ -260,6 +308,46 @@ export function streamedTextBlocks(turn: RecordedTurn) {
return [...blocks.values()];
}
+/**
+ * A recorded turn as the sim serves it: under its own turn id, so a chained
+ * turn's entries never sit at or before the cursor the previous one left,
+ * and with its checkpoints' sequences moved to where its rows land here.
+ */
+function simulatedTurn(plan: TurnPlan, index: number, plans: TurnPlan[]) {
+ const id = `drift-turn-${index}`;
+ const base = plans
+ .slice(0, index)
+ .reduce((n, p) => n + (p.persistedRows ?? p.turn.rows).length, 0);
+ const shift = base - Number(plan.turn.rows[0]?.sequence ?? 0);
+ const recordedCheckpoints = new Map<number, CheckpointData>();
+ const checkpoints = new Map<number, CheckpointData & { entry_id: string }>();
+ const frames = plan.turn.frames.map((frame, i) => {
+ let sse = frame.sse.replace(/^id: [^\n]*:/, `id: ${id}:`);
+ const data = frameData(frame);
+ const chunk = data
+ ? (JSON.parse(data) as { type: string; data?: CheckpointData })
+ : null;
+ if (chunk?.type === "data-checkpoint" && chunk.data) {
+ recordedCheckpoints.set(i, chunk.data);
+ const moved = { ...chunk.data, sequence: chunk.data.sequence + shift };
+ checkpoints.set(i, {
+ entry_id: frame.id,
+ rows: moved.rows,
+ sequence: moved.sequence,
+ });
+ sse = `id: ${id}:${frame.id}\ndata: ${JSON.stringify({ ...chunk, data: moved })}\n\n`;
+ }
+ return { id: frame.id, sse };
+ });
+ return { id, frames, checkpoints, recordedCheckpoints };
+}
+
+interface CheckpointData {
+ rows: number;
+ sequence: number;
+ digest?: string;
+}
+
function isFinish(frame: { sse: string }) {
return frameData(frame)?.startsWith('{"type":"finish"}') ?? false;
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts
index 3d6a36c22c..61a73b81f9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts
@@ -4,6 +4,7 @@ import { http, HttpResponse } from "msw";
import { expect, type Mock } from "vitest";
import { resetCopilotChatRegistry } from "../../copilotChatRegistry";
import { useCopilotStreamStore } from "../../copilotStreamStore";
+import { resetTurnRuntimes } from "../../stream/turnRuntime";
import { renderHost } from "../sse-helpers";
import {
type BackendSim,
@@ -148,6 +149,7 @@ export function expectDrift(
export function resetChatState() {
resetCopilotChatRegistry();
+ resetTurnRuntimes();
useCopilotStreamStore.getState().resetAll();
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-content.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-content.test.tsx
index 5cfae1677b..3f177222b0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-content.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-content.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, it, vi } from "vitest";
-import { TEST_BACKEND_BASE_URL } from "../sse-helpers";
+import { STREAM_PATHS, TEST_BACKEND_BASE_URL } from "../sse-helpers";
import {
createBackendSim,
loadRecordedTurn,
@@ -33,12 +33,17 @@ vi.mock("../../helpers", async (importActual) => {
vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),
}));
+const streamPath = vi.hoisted(() => ({ runtime: false }));
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
const actual =
await importActual<
typeof import("@/services/feature-flags/use-get-flag")
>();
- return { ...actual, useGetFlag: () => false };
+ return {
+ ...actual,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
+ };
});
const { toastMock } = vi.hoisted(() => ({ toastMock: vi.fn() }));
vi.mock("@/components/molecules/Toast/use-toast", async (importActual) => {
@@ -67,94 +72,114 @@ afterEach(() => {
resetChatState();
});
-describe("stream drift — what the stream and the rows hold", () => {
- it(
- "W5: a reload into a turn whose stream lost its head still renders the turn",
- { timeout: 90_000 },
- async () => {
- const sim = createBackendSim([{ turn: toolTurn }]);
- sim.beginRunning();
- sim.publish(TOOL_OUTPUT_DONE);
- // Simulated: the length cap dropped the stream's first entries, so the
- // replay opens on a text-delta whose text-start is gone.
- sim.trimHead(SECOND_DELTA);
- renderAgainst(sim);
- const painted = sampleTranscripts();
- await waitForConnections(sim, 1);
- // The second block reaches the stream whole, start included.
- sim.publish(SECOND_BLOCK_DONE - TOOL_OUTPUT_DONE);
- await turnKeepsRunning();
- const missingWhileRunning = notOnScreen(["It says Example Domain."]);
- sim.publish();
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
+ beforeEach(() => {
+ streamPath.runtime = path === "stream runtime";
+ });
- expectDrift(
- await reportDrift({
- sim,
- turns: [toolTurn],
- painted,
- toast: toastMock,
- missingWhileRunning,
- quietMs: 8000,
- }),
- // The parser throws on the orphan delta and every reconnect replays
- // the same head, so nothing of the running turn renders and the
- // reconnects announce "Connection lost". Only the turn's end repairs
- // the transcript, from the rows.
- { today: ["connectionToast", "missingWhileRunning"] },
- );
- },
- );
+ describe("stream drift — what the stream and the rows hold", () => {
+ it(
+ "W5: a reload into a turn whose stream lost its head still renders the turn",
+ { timeout: 90_000 },
+ async () => {
+ const sim = createBackendSim([{ turn: toolTurn }]);
+ sim.beginRunning();
+ sim.publish(TOOL_OUTPUT_DONE);
+ // Simulated: the length cap dropped the stream's first entries, so the
+ // replay opens on a text-delta whose text-start is gone.
+ sim.trimHead(SECOND_DELTA);
+ renderAgainst(sim);
+ const painted = sampleTranscripts();
+ await waitForConnections(sim, 1);
+ // The second block reaches the stream whole, start included.
+ sim.publish(SECOND_BLOCK_DONE - TOOL_OUTPUT_DONE);
+ await turnKeepsRunning();
+ const missingWhileRunning = notOnScreen(["It says Example Domain."]);
+ sim.publish();
- it(
- "approval wake: a reload into a turn no executor runs raises no connection alarm",
- { timeout: 60_000 },
- async () => {
- const [prompt] = textTurn.rows;
- // The executor dropped the turn, so its stream never gets an entry.
- const sim = createBackendSim([{ turn: { frames: [], rows: [prompt] } }]);
- sim.beginRunning();
- vi.useFakeTimers({ shouldAdvanceTime: true });
- renderAgainst(sim);
- const painted = sampleTranscripts();
- await waitForConnections(sim, 1);
- // Heartbeats keep arriving every 10 s: the connection is alive, only
- // the turn is dead, and only the server can say so.
- await vi.advanceTimersByTimeAsync(60_000);
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [toolTurn],
+ painted,
+ toast: toastMock,
+ missingWhileRunning,
+ quietMs: 8000,
+ }),
+ // AI SDK: the parser throws on the orphan delta and every reconnect
+ // replays the same head, so nothing of the running turn renders and
+ // the reconnects announce "Connection lost". Only the turn's end
+ // repairs the transcript, from the rows.
+ // Runtime: the trimmed stream names no checkpoint, so there is no
+ // seed to tail from; it shows the rows until the turn ends, silently.
+ // A backend with L0 never trims a running turn, so this needs a
+ // stream the length cap cut.
+ {
+ today:
+ path === "stream runtime"
+ ? ["missingWhileRunning"]
+ : ["connectionToast", "missingWhileRunning"],
+ },
+ );
+ },
+ );
- expectDrift(
- await reportDrift({ sim, turns: [], painted, toast: toastMock }),
- // The 6 s restore watchdog sees no content, reconnects three times and
- // ends on "Unable to reconnect. Please refresh the page."
- { today: ["connectionToast"] },
- );
- },
- );
+ it(
+ "approval wake: a reload into a turn no executor runs raises no connection alarm",
+ { timeout: 60_000 },
+ async () => {
+ const [prompt] = textTurn.rows;
+ // The executor dropped the turn, so its stream never gets an entry.
+ const sim = createBackendSim([
+ { turn: { frames: [], rows: [prompt] } },
+ ]);
+ sim.beginRunning();
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ renderAgainst(sim);
+ const painted = sampleTranscripts();
+ await waitForConnections(sim, 1);
+ // Heartbeats keep arriving every 10 s: the connection is alive, only
+ // the turn is dead, and only the server can say so.
+ await vi.advanceTimersByTimeAsync(60_000);
- it(
- "W8: a reply whose final persist failed stays on screen",
- { timeout: 60_000 },
- async () => {
- const [prompt] = textTurn.rows;
- const sim = createBackendSim([
- { turn: textTurn, persistedRows: [prompt] },
- ]);
- renderAgainst(sim);
- await sendPrompt(sim, textTurn);
- const painted = sampleTranscripts();
- sim.publish();
+ expectDrift(
+ await reportDrift({ sim, turns: [], painted, toast: toastMock }),
+ // AI SDK: the 6 s restore watchdog sees no content, reconnects three
+ // times and ends on "Unable to reconnect. Please refresh the page."
+ { today: path === "stream runtime" ? [] : ["connectionToast"] },
+ );
+ },
+ );
- expectDrift(
- await reportDrift({
- sim,
- turns: [textTurn],
- painted,
- toast: toastMock,
- }),
- // The end-of-turn hydrate replaces the list with rows that lack the
- // reply, so it vanishes in front of the user. The rows are the fault
- // here, so a reload is no oracle for this case.
- { today: ["lostStreamedText"], unchecked: ["differsFromReload"] },
- );
- },
- );
+ it(
+ "W8: a reply whose final persist failed stays on screen",
+ { timeout: 60_000 },
+ async () => {
+ const [prompt] = textTurn.rows;
+ const sim = createBackendSim([
+ { turn: textTurn, persistedRows: [prompt] },
+ ]);
+ renderAgainst(sim);
+ await sendPrompt(sim, textTurn);
+ const painted = sampleTranscripts();
+ sim.publish();
+
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [textTurn],
+ painted,
+ toast: toastMock,
+ }),
+ // AI SDK: the end-of-turn hydrate replaces the list with rows that
+ // lack the reply, so it vanishes in front of the user. The rows are
+ // the fault here, so a reload is no oracle for this case.
+ {
+ today: path === "stream runtime" ? [] : ["lostStreamedText"],
+ unchecked: ["differsFromReload"],
+ },
+ );
+ },
+ );
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-guards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-guards.test.tsx
index 61ad8c0559..0c30900ebc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-guards.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-guards.test.tsx
@@ -1,5 +1,6 @@
-import { afterEach, beforeEach, describe, it, vi } from "vitest";
-import { TEST_BACKEND_BASE_URL } from "../sse-helpers";
+import { screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { STREAM_PATHS, TEST_BACKEND_BASE_URL } from "../sse-helpers";
import {
createBackendSim,
loadRecordedTurn,
@@ -35,12 +36,17 @@ vi.mock("../../helpers", async (importActual) => {
vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),
}));
+const streamPath = vi.hoisted(() => ({ runtime: false }));
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
const actual =
await importActual<
typeof import("@/services/feature-flags/use-get-flag")
>();
- return { ...actual, useGetFlag: () => false };
+ return {
+ ...actual,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
+ };
});
const { toastMock } = vi.hoisted(() => ({ toastMock: vi.fn() }));
vi.mock("@/components/molecules/Toast/use-toast", async (importActual) => {
@@ -58,67 +64,111 @@ beforeEach(() => {
afterEach(() => resetChatState());
-describe("stream drift — guards", () => {
- it.each([
- "dummy-text-turn",
- "baseline-tool-turn",
- // A tool result that lands after the next text: the backend ends the
- // text block before the step closes (#14762), or the parser dies.
- "sdk-late-tool-result",
- ])(
- "a sent turn renders what a reload renders (%s)",
- { timeout: 60_000 },
- async (name) => {
- const turn = loadRecordedTurn(name);
- const sim = createBackendSim([{ turn }]);
- renderAgainst(sim);
- await sendPrompt(sim, turn);
- const painted = sampleTranscripts();
- sim.publish(turn.frames.length - 1);
- await waitForStableTranscript(1000);
- const missingWhileRunning = notOnScreen(streamedTextBlocks(turn));
- sim.publish();
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
+ beforeEach(() => {
+ streamPath.runtime = path === "stream runtime";
+ });
- expectDrift(
- await reportDrift({
- sim,
- turns: [turn],
- painted,
- toast: toastMock,
- missingWhileRunning,
- }),
- {},
- );
- },
- );
+ describe("stream drift — guards", () => {
+ it.each([
+ "dummy-text-turn",
+ "baseline-tool-turn",
+ // A tool result that lands after the next text: the backend ends the
+ // text block before the step closes (#14762), or the parser dies.
+ "sdk-late-tool-result",
+ ])(
+ "a sent turn renders what a reload renders (%s)",
+ { timeout: 60_000 },
+ async (name) => {
+ const turn = loadRecordedTurn(name);
+ const sim = createBackendSim([{ turn }]);
+ renderAgainst(sim);
+ await sendPrompt(sim, turn);
+ const painted = sampleTranscripts();
+ sim.publish(turn.frames.length - 1);
+ await waitForStableTranscript(1000);
+ const missingWhileRunning = notOnScreen(streamedTextBlocks(turn));
+ sim.publish();
- it(
- "a reload into a running turn resumes it once",
- { timeout: 60_000 },
- async () => {
- const turn = loadRecordedTurn("baseline-tool-turn");
- const sim = createBackendSim([{ turn }]);
- sim.beginRunning();
- sim.publish(9);
- renderAgainst(sim);
- const painted = sampleTranscripts();
- await waitForConnections(sim, 1);
- await turnKeepsRunning();
- sim.publish(turn.frames.length - 1 - 9);
- await waitForStableTranscript(1000);
- const missingWhileRunning = notOnScreen(streamedTextBlocks(turn));
- sim.publish();
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [turn],
+ painted,
+ toast: toastMock,
+ missingWhileRunning,
+ }),
+ {},
+ );
+ },
+ );
- expectDrift(
- await reportDrift({
- sim,
- turns: [turn],
- painted,
- toast: toastMock,
- missingWhileRunning,
- }),
- {},
- );
- },
- );
+ // The AI SDK path swaps every id for the rows' `-seq-N` ones at the end
+ // of the turn, which remounts the transcript; the runtime adopts the rows
+ // into the messages it already drew.
+ const runtimeOnly = path === "stream runtime" ? it : it.fails;
+ runtimeOnly(
+ "the end-of-turn reconcile keeps every message's element",
+ { timeout: 60_000 },
+ async () => {
+ const turn = loadRecordedTurn("baseline-tool-turn");
+ const sim = createBackendSim([{ turn }]);
+ renderAgainst(sim);
+ await sendPrompt(sim, turn);
+ sim.publish(turn.frames.length - 1);
+ await waitForStableTranscript(1000);
+ const before = messageElements();
+
+ sim.publish();
+ // The reconcile adopts the prompt's persisted row, timestamp included.
+ const stamp = new Date(String(turn.rows[0].created_at)).toLocaleString(
+ undefined,
+ { dateStyle: "medium", timeStyle: "short" },
+ );
+ await waitFor(() => expect(screen.getByText(stamp)).toBeDefined(), {
+ timeout: 10_000,
+ });
+ await waitForStableTranscript(1000);
+ const after = messageElements();
+ expect(after).toHaveLength(2);
+ expect(after.filter((element) => !before.includes(element))).toEqual(
+ [],
+ );
+ },
+ );
+
+ it(
+ "a reload into a running turn resumes it once",
+ { timeout: 60_000 },
+ async () => {
+ const turn = loadRecordedTurn("baseline-tool-turn");
+ const sim = createBackendSim([{ turn }]);
+ sim.beginRunning();
+ sim.publish(9);
+ renderAgainst(sim);
+ const painted = sampleTranscripts();
+ await waitForConnections(sim, 1);
+ await turnKeepsRunning();
+ sim.publish(turn.frames.length - 1 - 9);
+ await waitForStableTranscript(1000);
+ const missingWhileRunning = notOnScreen(streamedTextBlocks(turn));
+ sim.publish();
+
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [turn],
+ painted,
+ toast: toastMock,
+ missingWhileRunning,
+ }),
+ {},
+ );
+ },
+ );
+ });
});
+
+function messageElements() {
+ return Array.from(document.querySelectorAll("[data-message-id]"));
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-reconnects.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-reconnects.test.tsx
index e359e2f75d..1983a43f09 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-reconnects.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-drift-reconnects.test.tsx
@@ -1,6 +1,6 @@
import { screen } from "@testing-library/react";
-import { afterEach, beforeEach, describe, it, vi } from "vitest";
-import { TEST_BACKEND_BASE_URL } from "../sse-helpers";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { STREAM_PATHS, TEST_BACKEND_BASE_URL } from "../sse-helpers";
import {
createBackendSim,
loadRecordedTurn,
@@ -33,12 +33,17 @@ vi.mock("../../helpers", async (importActual) => {
vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),
}));
+const streamPath = vi.hoisted(() => ({ runtime: false }));
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
const actual =
await importActual<
typeof import("@/services/feature-flags/use-get-flag")
>();
- return { ...actual, useGetFlag: () => false };
+ return {
+ ...actual,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
+ };
});
const { toastMock } = vi.hoisted(() => ({ toastMock: vi.fn() }));
vi.mock("@/components/molecules/Toast/use-toast", async (importActual) => {
@@ -66,146 +71,200 @@ afterEach(() => {
resetChatState();
});
-describe("stream drift — a second connection onto a live turn", () => {
- it(
- "W1: a tab shown again after 30 s resumes over the stream it never lost",
- { timeout: 60_000 },
- async () => {
- const sim = createBackendSim([{ turn: toolTurn }]);
- renderAgainst(sim);
- await sendPrompt(sim, toolTurn);
- const painted = sampleTranscripts();
- sim.publish(FIRST_TEXT_BLOCK_DONE);
- await screen.findByText("Let me fetch that page.", undefined, {
- timeout: 5000,
- });
-
- // Desktop browsers keep a hidden tab's fetch open, so the POST stream is
- // still healthy when the wake re-sync fires.
- vi.useFakeTimers({ toFake: ["Date"], shouldAdvanceTime: true });
- setTabVisibility("hidden");
- vi.setSystemTime(Date.now() + 31_000);
- setTabVisibility("visible");
- vi.useRealTimers();
- await waitForConnections(sim, 2);
- sim.publish();
-
- expectDrift(
- await reportDrift({
- sim,
- turns: [toolTurn],
- painted,
- toast: toastMock,
- }),
- // The resume replays the turn into the list while the POST stream
- // still writes it: both copies of the first block are on screen.
- { today: ["paintedTwice"] },
- );
- },
- );
-
- it(
- "W7: a tool call silent for 70 s keeps its stream, heartbeats included",
- { timeout: 60_000 },
- async () => {
- const sim = createBackendSim([{ turn: toolTurn }]);
- renderAgainst(sim);
- await sendPrompt(sim, toolTurn);
- const painted = sampleTranscripts();
- sim.publish(FIRST_TEXT_BLOCK_DONE);
- await screen.findByText("Let me fetch that page.", undefined, {
- timeout: 5000,
- });
-
- vi.useFakeTimers({ shouldAdvanceTime: true });
- sim.publish(TOOL_CALL_OPEN - FIRST_TEXT_BLOCK_DONE);
- // The route writes a heartbeat comment every 10 s; the parser drops them.
- await vi.advanceTimersByTimeAsync(70_000);
- sim.publish();
-
- expectDrift(
- await reportDrift({
- sim,
- turns: [toolTurn],
- painted,
- toast: toastMock,
- }),
- // The 60 s stall watchdog reads the silence as a dead stream and
- // reconnects with a toast.
- { today: ["connectionToast"] },
- );
- },
- );
-});
+describe.each(STREAM_PATHS)("on the %s path", (path) => {
+ beforeEach(() => {
+ streamPath.runtime = path === "stream runtime";
+ });
+
+ describe("stream drift — a second connection onto a live turn", () => {
+ // The AI SDK path holds one response per resume and aborts none of them,
+ // so this case is the bug the runtime's single slot exists to fix.
+ const runtimeOnly = path === "stream runtime" ? it : it.fails;
+ runtimeOnly(
+ "W1: two resumes inside the window open one connection and draw one bubble",
+ { timeout: 60_000 },
+ async () => {
+ const sim = createBackendSim([{ turn: toolTurn }]);
+ renderAgainst(sim);
+ await sendPrompt(sim, toolTurn);
+ const painted = sampleTranscripts();
+ sim.publish(FIRST_TEXT_BLOCK_DONE);
+ await screen.findByText("Let me fetch that page.", undefined, {
+ timeout: 5000,
+ });
-describe("stream drift — a stream that ends while its turn runs on", () => {
- it(
- "W4: the load balancer's 30-minute cut is resumed silently",
- { timeout: 60_000 },
- async () => {
- const sim = createBackendSim([{ turn: toolTurn }]);
- renderAgainst(sim);
- await sendPrompt(sim, toolTurn);
- const painted = sampleTranscripts();
- sim.publish(FIRST_TEXT_BLOCK_DONE);
- await screen.findByText("Let me fetch that page.", undefined, {
- timeout: 5000,
- });
-
- // Simulated: the cut is a clean close with no finish, whatever the age.
- sim.cutOpenConnections();
- await waitForConnections(sim, 2);
- await turnKeepsRunning();
- sim.publish();
-
- expectDrift(
- await reportDrift({
+ // The stream drops while the tab is hidden. Coming back after 30 s
+ // resumes it; the network event that follows is a second trigger
+ // inside the liveness window of a resume already on the wire.
+ vi.useFakeTimers({ toFake: ["Date"], shouldAdvanceTime: true });
+ setTabVisibility("hidden");
+ sim.cutOpenConnections();
+ vi.setSystemTime(Date.now() + 31_000);
+ setTabVisibility("visible");
+ vi.useRealTimers();
+ await waitForConnections(sim, 2);
+ window.dispatchEvent(new Event("online"));
+ await turnKeepsRunning();
+ sim.publish();
+
+ const report = await reportDrift({
sim,
turns: [toolTurn],
painted,
toast: toastMock,
- }),
- // Two resumes attach to one running turn: the once-per-mount resume,
- // and the post-finish probe's reconnect with "Connection lost".
- // Neither aborts the other, so the first block is painted three times.
- { today: ["connectionToast", "paintedTwice"] },
- );
- },
- );
-
- it(
- "chained turn: the turn a finished turn wakes is attached to quietly",
- { timeout: 60_000 },
- async () => {
- const continuation = {
- ...textTurn,
- rows: textTurn.rows.filter((row) => row.role !== "user"),
- };
- const sim = createBackendSim([
- { turn: toolTurn },
- { turn: continuation, chained: true },
- ]);
- renderAgainst(sim);
- await sendPrompt(sim, toolTurn);
- const painted = sampleTranscripts();
- // The first turn's end starts the continuation before its finish lands.
- sim.publish();
- await waitForConnections(sim, 2);
- await turnKeepsRunning();
- sim.publish();
-
- expectDrift(
- await reportDrift({
- sim,
- turns: [toolTurn, continuation],
- painted,
- toast: toastMock,
- }),
- // The probe cannot tell the new turn from a dropped stream (#15044).
- { today: ["connectionToast"] },
- );
- },
- );
+ });
+ expect(sim.connections).toHaveLength(2);
+ expectDrift(report, {});
+ },
+ );
+
+ it(
+ "W1: a tab shown again after 30 s resumes over the stream it never lost",
+ { timeout: 60_000 },
+ async () => {
+ const sim = createBackendSim([{ turn: toolTurn }]);
+ renderAgainst(sim);
+ await sendPrompt(sim, toolTurn);
+ const painted = sampleTranscripts();
+ sim.publish(FIRST_TEXT_BLOCK_DONE);
+ await screen.findByText("Let me fetch that page.", undefined, {
+ timeout: 5000,
+ });
+
+ // Desktop browsers keep a hidden tab's fetch open, so the POST stream is
+ // still healthy when the wake re-sync fires.
+ vi.useFakeTimers({ toFake: ["Date"], shouldAdvanceTime: true });
+ setTabVisibility("hidden");
+ vi.setSystemTime(Date.now() + 31_000);
+ setTabVisibility("visible");
+ vi.useRealTimers();
+ await waitForConnections(sim, 2);
+ sim.publish();
+
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [toolTurn],
+ painted,
+ toast: toastMock,
+ }),
+ // AI SDK: the resume replays the turn into the list while the POST
+ // stream still writes it: both copies of the first block are on screen.
+ { today: path === "stream runtime" ? [] : ["paintedTwice"] },
+ );
+ },
+ );
+
+ it(
+ "W7: a tool call silent for 70 s keeps its stream, heartbeats included",
+ { timeout: 60_000 },
+ async () => {
+ const sim = createBackendSim([{ turn: toolTurn }]);
+ renderAgainst(sim);
+ await sendPrompt(sim, toolTurn);
+ const painted = sampleTranscripts();
+ sim.publish(FIRST_TEXT_BLOCK_DONE);
+ await screen.findByText("Let me fetch that page.", undefined, {
+ timeout: 5000,
+ });
+
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ sim.publish(TOOL_CALL_OPEN - FIRST_TEXT_BLOCK_DONE);
+ // The route writes a heartbeat comment every 10 s; the parser drops them.
+ await vi.advanceTimersByTimeAsync(70_000);
+ sim.publish();
+
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [toolTurn],
+ painted,
+ toast: toastMock,
+ }),
+ // AI SDK: the 60 s stall watchdog reads the silence as a dead stream
+ // and reconnects with a toast.
+ { today: path === "stream runtime" ? [] : ["connectionToast"] },
+ );
+ },
+ );
+ });
+
+ describe("stream drift — a stream that ends while its turn runs on", () => {
+ it(
+ "W4: the load balancer's 30-minute cut is resumed silently",
+ { timeout: 60_000 },
+ async () => {
+ const sim = createBackendSim([{ turn: toolTurn }]);
+ renderAgainst(sim);
+ await sendPrompt(sim, toolTurn);
+ const painted = sampleTranscripts();
+ sim.publish(FIRST_TEXT_BLOCK_DONE);
+ await screen.findByText("Let me fetch that page.", undefined, {
+ timeout: 5000,
+ });
+
+ // Simulated: the cut is a clean close with no finish, whatever the age.
+ sim.cutOpenConnections();
+ await waitForConnections(sim, 2);
+ await turnKeepsRunning();
+ sim.publish();
+
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [toolTurn],
+ painted,
+ toast: toastMock,
+ }),
+ // AI SDK: two resumes attach to one running turn: the once-per-mount
+ // resume, and the post-finish probe's reconnect with "Connection
+ // lost". Neither aborts the other, so the first block is painted
+ // three times.
+ {
+ today:
+ path === "stream runtime"
+ ? []
+ : ["connectionToast", "paintedTwice"],
+ },
+ );
+ },
+ );
+
+ it(
+ "chained turn: the turn a finished turn wakes is attached to quietly",
+ { timeout: 60_000 },
+ async () => {
+ const continuation = {
+ ...textTurn,
+ rows: textTurn.rows.filter((row) => row.role !== "user"),
+ };
+ const sim = createBackendSim([
+ { turn: toolTurn },
+ { turn: continuation, chained: true },
+ ]);
+ renderAgainst(sim);
+ await sendPrompt(sim, toolTurn);
+ const painted = sampleTranscripts();
+ // The first turn's end starts the continuation before its finish lands.
+ sim.publish();
+ await waitForConnections(sim, 2);
+ await turnKeepsRunning();
+ sim.publish();
+
+ expectDrift(
+ await reportDrift({
+ sim,
+ turns: [toolTurn, continuation],
+ painted,
+ toast: toastMock,
+ }),
+ // AI SDK: the probe cannot tell the new turn from a dropped stream
+ // (#15044).
+ { today: path === "stream runtime" ? [] : ["connectionToast"] },
+ );
+ },
+ );
+ });
});
function setTabVisibility(state: "hidden" | "visible") {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx
index 1d1fb4224f..579fc899a9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx
@@ -4,10 +4,10 @@ import { screen, waitFor } from "@testing-library/react";
import type { UIMessageChunk } from "ai";
import { http, HttpResponse } from "msw";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { resetCopilotChatRegistry } from "../copilotChatRegistry";
import { useCopilotStreamStore } from "../copilotStreamStore";
import {
renderHost,
+ resetChatRuntimes,
TEST_BACKEND_BASE_URL,
TEST_SESSION_ID,
} from "./sse-helpers";
@@ -35,12 +35,18 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),
}));
+const streamPath = vi.hoisted(() => ({ runtime: false }));
+
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
const actual =
await importActual<
typeof import("@/services/feature-flags/use-get-flag")
>();
- return { ...actual, useGetFlag: () => false };
+ return {
+ ...actual,
+ useGetFlag: (flag: string) =>
+ flag === "copilot-stream-runtime" ? streamPath.runtime : false,
+ };
});
const EARLIER_PROMPT = "What is on my calendar";
@@ -279,7 +285,7 @@ function renderResumedSession(
}
beforeEach(() => {
- resetCopilotChatRegistry();
+ resetChatRuntimes();
// Message snapshots are keyed by session id in a module-level store, so
// without this each case starts by rendering the previous case's
// transcript and its assertions pass against stale DOM.
@@ -288,10 +294,14 @@ beforeEach(() => {
afterEach(() => {
releaseParkedStreams();
- resetCopilotChatRegistry();
+ resetChatRuntimes();
});
describe("useCopilotStream — resume replays a db-hydrated turn", () => {
+ beforeEach(() => {
+ streamPath.runtime = false;
+ });
+
it(
"drops the hydrated partial so the replayed turn renders one bubble, not two",
{ timeout: 20000 },
@@ -520,3 +530,257 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {
},
);
});
+
+/**
+ * The same reloads on the stream runtime, against the backend that names a
+ * checkpoint: the persisted rows seed the turn and the stream is read from
+ * the checkpoint on, so nothing is replayed and nothing is trimmed.
+ */
+describe("stream runtime — a reload into a running turn", () => {
+ beforeEach(() => {
+ streamPath.runtime = true;
+ });
+
+ afterEach(() => {
+ streamPath.runtime = false;
+ });
+
+ it(
+ "seeds the persisted half and tails the rest into the same bubble",
+ { timeout: 20000 },
+ async () => {
+ const { resumeCursors } = renderRuntimeReload(PERSISTED_TOOL_ROUND, {
+ rows: 2,
+ sequence: 4,
+ });
+
+ expect(
+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),
+ ).toBeDefined();
+ expect(resumeCursors()).toEqual([`${CHECKPOINT_ENTRY}-0`]);
+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);
+ expect(screen.getAllByText(RESUMED_PROMPT)).toHaveLength(1);
+ expect(screen.getAllByText(EARLIER_PROMPT)).toHaveLength(1);
+ expect(screen.getAllByText(EARLIER_ANSWER)).toHaveLength(1);
+ expect(transcriptRoles()).toEqual([
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ ]);
+ },
+ );
+
+ it(
+ "draws a drained follow-up once, between the halves it split",
+ { timeout: 20000 },
+ async () => {
+ renderRuntimeReload(
+ [...PERSISTED_TOOL_ROUND, sessionMessage(6, "user", MIDTURN_FOLLOWUP)],
+ { rows: 3, sequence: 4 },
+ );
+
+ expect(
+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),
+ ).toBeDefined();
+ expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);
+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);
+ expect(transcriptRoles()).toEqual([
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ ]);
+ },
+ );
+
+ it.each([
+ ["a plain mount", false],
+ ["a Strict Mode mount", true],
+ ])(
+ "keeps a follow-up the backend still holds as a queued bubble under the live turn on %s",
+ { timeout: 20000 },
+ async (_label, strictMode) => {
+ renderRuntimeReload(
+ PERSISTED_TOOL_ROUND,
+ { rows: 2, sequence: 4 },
+ [QUEUED_FOLLOWUP],
+ strictMode,
+ );
+
+ expect(
+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),
+ ).toBeDefined();
+ await waitFor(() => expect(screen.getByText("Queued")).toBeDefined());
+ expect(screen.getAllByText(QUEUED_FOLLOWUP)).toHaveLength(1);
+ const assistant = screen.getByText(REPLAYED_HALF);
+ expect(
+ assistant.compareDocumentPosition(screen.getByText(QUEUED_FOLLOWUP)) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ },
+ );
+
+ it(
+ "keeps the completed answer when the running turn started without a user row",
+ { timeout: 20000 },
+ async () => {
+ renderRuntimeReload(
+ [
+ sessionMessage(1, "user", EARLIER_PROMPT),
+ sessionMessage(2, "assistant", EARLIER_ANSWER),
+ { ...sessionMessage(3, "assistant", PERSISTED_HALF), ...CALL },
+ { ...sessionMessage(4, "assistant", "{}"), ...RESULT },
+ ],
+ { rows: 2, sequence: 3 },
+ );
+
+ expect(
+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),
+ ).toBeDefined();
+ expect(screen.getAllByText(EARLIER_ANSWER)).toHaveLength(1);
+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);
+ },
+ );
+
+ it(
+ "replays a turn with nothing persisted yet from its first entry, once",
+ { timeout: 20000 },
+ async () => {
+ const { resumeCursors } = renderRuntimeReload(
+ HYDRATED_SESSION_MESSAGES.slice(0, 3),
+ null,
+ );
+
+ expect(
+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),
+ ).toBeDefined();
+ expect(resumeCursors()).toEqual(["0-0"]);
+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);
+ expect(screen.getAllByText(RESUMED_PROMPT)).toHaveLength(1);
+ },
+ );
+});
+
+const CALL = {
+ tool_calls: [
+ {
+ id: "call-1",
+ type: "function",
+ function: { name: "list_calendar", arguments: "{}" },
+ },
+ ],
+};
+const RESULT = { role: "tool", tool_call_id: "call-1" } as const;
+
+/** The resumed prompt's turn, persisted up to its first tool round. */
+const PERSISTED_TOOL_ROUND: SessionDetailResponseMessagesItem[] = [
+ ...HYDRATED_SESSION_MESSAGES.slice(0, 3),
+ { ...sessionMessage(4, "assistant", PERSISTED_HALF), ...CALL },
+ { ...sessionMessage(5, "assistant", "{}"), ...RESULT },
+];
+
+/** The whole turn on its stream: the round the rows hold, a checkpoint, then the rest. */
+const RUNTIME_TURN: UIMessageChunk[] = [
+ { type: "start", messageId: "resumed-turn" },
+ { type: "start-step" },
+ { type: "text-start", id: "half-1" },
+ { type: "text-delta", id: "half-1", delta: PERSISTED_HALF },
+ { type: "text-end", id: "half-1" },
+ { type: "tool-input-start", toolCallId: "call-1", toolName: "list_calendar" },
+ {
+ type: "tool-input-available",
+ toolCallId: "call-1",
+ toolName: "list_calendar",
+ input: {},
+ },
+ { type: "tool-output-available", toolCallId: "call-1", output: {} },
+ { type: "finish-step" },
+ { type: "start-step" },
+ { type: "text-start", id: "half-2" },
+ { type: "text-delta", id: "half-2", delta: REPLAYED_HALF },
+ { type: "text-end", id: "half-2" },
+];
+
+// The rows' checkpoint names the entry that closes the tool round's step.
+const CHECKPOINT_ENTRY = 9;
+
+function renderRuntimeReload(
+ messages: SessionDetailResponseMessagesItem[],
+ checkpoint: { rows: number; sequence: number } | null,
+ pendingMessages: string[] = [],
+ strictMode = false,
+) {
+ const cursors: string[] = [];
+ server.use(
+ http.get(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,
+ ({ request }) => {
+ const params = new URL(request.url).searchParams;
+ const after = params.get("after") ?? "0-0";
+ cursors.push(after);
+ return parkedRuntimeResponse(params.get("turn") ?? "", after);
+ },
+ ),
+ );
+ renderHost({
+ sessionOverride: {
+ messages,
+ active_stream: {
+ turn_id: "turn-1",
+ last_message_id: "0-0",
+ started_at: "2026-05-13T00:04:00Z",
+ checkpoint: checkpoint && {
+ entry_id: `${CHECKPOINT_ENTRY}-0`,
+ ...checkpoint,
+ },
+ },
+ },
+ pendingMessages,
+ strictMode,
+ });
+ // Under Strict Mode the effects run twice; the runtime's one slot opens once.
+ return { resumeCursors: () => [...new Set(cursors)] };
+}
+
+/** The turn's entries after `after`, each with its id; then the stream parks. */
+function parkedRuntimeResponse(turn: string, after: string) {
+ const encoder = new TextEncoder();
+ const from = Number(after.split("-")[0]);
+ const entries = RUNTIME_TURN.map((chunk, i) => ({ n: i + 1, chunk })).filter(
+ ({ n }) => n > from,
+ );
+ let index = 0;
+ const stream = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ if (index < entries.length) {
+ const { n, chunk } = entries[index++];
+ controller.enqueue(
+ encoder.encode(
+ `id: ${turn}:${n}-0\ndata: ${JSON.stringify(chunk)}\n\n`,
+ ),
+ );
+ return;
+ }
+ return new Promise<void>((resolve) => {
+ parkedStreamReleases.push(() => {
+ try {
+ controller.close();
+ } catch {
+ // already closed
+ }
+ resolve();
+ });
+ });
+ },
+ });
+ return new HttpResponse(stream, { status: 200, headers: SSE_HEADERS });
+}
+
+function transcriptRoles() {
+ return Array.from(document.querySelectorAll("[data-message-id]")).map((el) =>
+ el.classList.contains("is-user") ? "user" : "assistant",
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx
index ddaa0b76e3..86f0f20d0e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx
@@ -19,10 +19,24 @@ import { NuqsTestingAdapter } from "nuqs/adapters/testing";
import { ReactNode, StrictMode, useState } from "react";
import { expect } from "vitest";
import { CopilotChatHost } from "../CopilotChatHost";
+import { resetCopilotChatRegistry } from "../copilotChatRegistry";
+import { resetTurnRuntimes } from "../stream/turnRuntime";
export const TEST_BACKEND_BASE_URL = "http://localhost:18006";
export const TEST_SESSION_ID = "test-session-stream-1";
+/** The two chat streams a test can drive: the AI SDK's, the default, and the
+ * turn runtime behind `copilot-stream-runtime`. */
+export const STREAM_PATHS = ["AI SDK", "stream runtime"] as const;
+export type StreamPath = (typeof STREAM_PATHS)[number];
+export const STREAM_RUNTIME_FLAG = "copilot-stream-runtime";
+
+/** Both paths keep a per-session runtime in a module-level map. */
+export function resetChatRuntimes() {
+ resetCopilotChatRegistry();
+ resetTurnRuntimes();
+}
+
export interface SessionOverride {
active_stream?: SessionDetailResponse["active_stream"];
messages?: SessionDetailResponse["messages"];
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
index b70908e062..272a36abbe 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
@@ -13,7 +13,7 @@ import type { UIMessage } from "ai";
import { useRef } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChatInput } from "../ChatInput";
-import { useCopilotStop } from "../../../useCopilotStop";
+import { sdkStopStream, useCopilotStop } from "../../../useCopilotStop";
import { toast } from "@/components/molecules/Toast/use-toast";
const mockCancel =
@@ -1014,10 +1014,7 @@ function StopHarness({
const isUserStoppingRef = useRef(false);
const stop = useCopilotStop({
sessionId,
- sdkStop,
- setMessages: setMessages as Parameters<
- typeof useCopilotStop
- >[0]["setMessages"],
+ stopStream: sdkStopStream(sdkStop, setMessages),
isUserStoppingRef,
setIsUserStopping,
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamSmoothing.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamSmoothing.ts
index 7c85d87a26..6862ba1ecd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamSmoothing.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamSmoothing.ts
@@ -28,8 +28,8 @@ import type { UIMessageChunk } from "ai";
* stream.
*/
-const TICK_DELAY_MS = 10;
-const BACKLOG_DRAIN_TICKS = 25;
+export const TICK_DELAY_MS = 10;
+export const BACKLOG_DRAIN_TICKS = 25;
type SmoothableChunk = Extract<
UIMessageChunk,
@@ -57,7 +57,7 @@ function makeDelta(pending: PendingText, delta: string): UIMessageChunk {
* A trailing run of non-whitespace is a partial word and gets no cut point —
* it stays buffered until more text or a flush arrives.
*/
-function findWordCutPoints(text: string): number[] {
+export function findWordCutPoints(text: string): number[] {
const wordWithTrailingSpace = /\s*\S+\s+/gy;
const cuts: number[] = [];
while (wordWithTrailingSpace.exec(text)) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts
index 22caad5bf4..c290a2200f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts
@@ -72,60 +72,14 @@ export function createCopilotTransport({
? createUsageCapturingFetch(sessionId)
: undefined,
),
- prepareSendMessagesRequest: async ({ messages }) => {
- const last = messages[messages.length - 1];
- const kickoffExpertId = getKickoffExpertIdFromMetadata(last.metadata);
- // Extract file_ids from FileUIPart entries on the message
- const fileIds = last.parts
- ?.filter((p): p is FileUIPart => p.type === "file")
- .map((p) => {
- // URL is like /api/proxy/api/workspace/files/{id}/download
- const match = p.url.match(/\/workspace\/files\/([^/]+)\//);
- return match?.[1];
- })
- .filter(Boolean) as string[] | undefined;
- // A folder is named for the model to open, never expanded into files,
- // so it travels as its own id list.
- const folderIds = last.parts?.flatMap((p) =>
- isWorkspaceFolderPart(p) ? [p.data.id] : [],
- );
- // ``message_id`` is the client idempotency key. The backend scopes it
- // to the authenticated user + session before using the result as the
- // persisted PK, so retransmits collide atomically without letting one
- // tenant preclaim another tenant's global ChatMessage id.
- //
- // Generated here (rather than in ``useSendMessage``) for two
- // reasons: (1) AI SDK's ``messageId`` arg on ``sendMessage`` is
- // "replace-existing-message" semantics — passing a fresh UUID
- // puts the SDK into edit-mode with no target and breaks
- // optimistic render. (2) ``prepareSendMessagesRequest`` is
- // called once per logical ``sendMessages`` call and the
- // prepared body is reused across SDK-internal retries, so a
- // single per-call UUID is exactly the stability we need.
- return {
- body: {
- message: (
- last.parts?.map((p) => (p.type === "text" ? p.text : "")) ?? []
- ).join(""),
- is_user_message: last.role === "user",
- context: null,
- file_ids: fileIds && fileIds.length > 0 ? fileIds : null,
- folder_ids: folderIds && folderIds.length > 0 ? folderIds : null,
- model: copilotModelRef.current ?? null,
- // Supplying options forces uuid's
- // getRandomValues path. Unlike crypto.randomUUID,
- // getRandomValues is available on plain-HTTP LAN origins used
- // by the local single-container appliance.
- message_id: uuidv4({}),
- // Asks the reply to speak before it starts working. Text turns
- // send false and pay nothing for it.
- voice: isVoiceTurn(),
- expert_kickoff: kickoffExpertId !== null,
- ...optionalAutopilotMode(sessionId),
- },
- headers: await getCopilotAuthHeaders(),
- };
- },
+ prepareSendMessagesRequest: async ({ messages }) => ({
+ body: streamRequestBody(
+ sessionId,
+ messages[messages.length - 1],
+ copilotModelRef.current,
+ ),
+ headers: await getCopilotAuthHeaders(),
+ }),
prepareReconnectToStreamRequest: async () => {
// Always replay from "0-0" (no ?last_chunk_id). AI SDK v5's
// UIMessageStream parser throws UIMessageStreamError on any *-delta /
@@ -144,6 +98,62 @@ export function createCopilotTransport({
});
}
+/** The POST body for a new turn, whichever client sends it. */
+export function streamRequestBody(
+ sessionId: string,
+ last: UIMessage,
+ model: CopilotLlmModel | undefined,
+) {
+ const kickoffExpertId = getKickoffExpertIdFromMetadata(last.metadata);
+ // Extract file_ids from FileUIPart entries on the message
+ const fileIds = last.parts
+ ?.filter((p): p is FileUIPart => p.type === "file")
+ .map((p) => {
+ // URL is like /api/proxy/api/workspace/files/{id}/download
+ const match = p.url.match(/\/workspace\/files\/([^/]+)\//);
+ return match?.[1];
+ })
+ .filter(Boolean) as string[] | undefined;
+ // A folder is named for the model to open, never expanded into files,
+ // so it travels as its own id list.
+ const folderIds = last.parts?.flatMap((p) =>
+ isWorkspaceFolderPart(p) ? [p.data.id] : [],
+ );
+ // ``message_id`` is the client idempotency key. The backend scopes it
+ // to the authenticated user + session before using the result as the
+ // persisted PK, so retransmits collide atomically without letting one
+ // tenant preclaim another tenant's global ChatMessage id.
+ //
+ // Generated here (rather than in ``useSendMessage``) for two
+ // reasons: (1) AI SDK's ``messageId`` arg on ``sendMessage`` is
+ // "replace-existing-message" semantics — passing a fresh UUID
+ // puts the SDK into edit-mode with no target and breaks
+ // optimistic render. (2) ``prepareSendMessagesRequest`` is
+ // called once per logical ``sendMessages`` call and the
+ // prepared body is reused across SDK-internal retries, so a
+ // single per-call UUID is exactly the stability we need.
+ return {
+ message: (
+ last.parts?.map((p) => (p.type === "text" ? p.text : "")) ?? []
+ ).join(""),
+ is_user_message: last.role === "user",
+ context: null,
+ file_ids: fileIds && fileIds.length > 0 ? fileIds : null,
+ folder_ids: folderIds && folderIds.length > 0 ? folderIds : null,
+ model: model ?? null,
+ // Supplying options forces uuid's
+ // getRandomValues path. Unlike crypto.randomUUID,
+ // getRandomValues is available on plain-HTTP LAN origins used
+ // by the local single-container appliance.
+ message_id: uuidv4({}),
+ // Asks the reply to speak before it starts working. Text turns
+ // send false and pay nothing for it.
+ voice: isVoiceTurn(),
+ expert_kickoff: kickoffExpertId !== null,
+ ...optionalAutopilotMode(sessionId),
+ };
+}
+
// Absent unless the user picked a mode, so a chat nobody touched keeps its own.
function optionalAutopilotMode(sessionId: string) {
const mode = getAutopilotModeChoice(sessionId);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.ts
new file mode 100644
index 0000000000..7305f054d5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.ts
@@ -0,0 +1,238 @@
+import { compareEntryIds } from "../turnConverter";
+import type { PersistedRow } from "../turnLog";
+import type { SessionView } from "../turnRuntime";
+import type { RecordedTurn } from "./recordedTurns";
+
+const HEARTBEAT_MS = 10_000;
+// The route's listener checks the meta after each empty read of this length.
+const LISTENER_READ_MS = 5_000;
+const encoder = new TextEncoder();
+
+export interface FakeConnection {
+ method: string;
+ url: URL;
+ /** Entries already sent on this connection, by id. */
+ sent: string[];
+ closed: boolean;
+ /** Closed by the client (an abort), as opposed to by the server. */
+ aborted: boolean;
+ /** End the response cleanly, as a proxy cut or the route's own end does. */
+ cut(): void;
+ /** Fail the response mid-body, as a dropped network does. */
+ fail(): void;
+ /** Stop this connection's heartbeats: it stays open and goes silent. */
+ silence(): void;
+}
+
+type Responder = (request: {
+ method: string;
+ url: URL;
+}) => "stream" | "network-error" | { status: number; body: unknown };
+
+/**
+ * The backend as the runtime sees it, for one recorded turn: the turn's
+ * entries published one by one, every connection reading from its cursor,
+ * heartbeats every 10 s, and a session GET whose rows follow the persists.
+ */
+export function fakeBackend(turn: RecordedTurn) {
+ const frames = turn.sse.map((sse) => ({ id: idOf(sse), sse }));
+ const turnId = turnOf(turn.sse[0]);
+ let published = 0;
+ let running = false;
+ let started = false;
+ let stoppedWithoutFinish = false;
+ const connections: FakeConnection[] = [];
+ // Every request, refused ones included.
+ const requests: { method: string; url: URL }[] = [];
+ const pumps = new Set<() => void>();
+ let responder: Responder = () => "stream";
+
+ function persistedCount() {
+ // A checkpoint names how many of the turn's rows are persisted.
+ let rows = 0;
+ for (const frame of frames.slice(0, published)) {
+ const data = dataOf(frame.sse);
+ if (data?.type === "data-checkpoint") rows = Number(data.data.rows);
+ if (data?.type === "finish") return turn.rows.length;
+ }
+ return 1 + rows;
+ }
+
+ async function fetchImpl(input: RequestInfo | URL, init?: RequestInit) {
+ const url = new URL(String(input));
+ const method = init?.method ?? "GET";
+ requests.push({ method, url });
+ const answer = responder({ method, url });
+ if (answer === "network-error") throw new TypeError("Failed to fetch");
+ if (answer !== "stream") {
+ return new Response(JSON.stringify(answer.body), {
+ status: answer.status,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ if (method === "POST") {
+ started = true;
+ running = true;
+ }
+ const after = url.searchParams.get("after") ?? "0-0";
+ return new Response(open(method, url, after, init?.signal), {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }
+
+ function open(
+ method: string,
+ url: URL,
+ after: string,
+ signal: AbortSignal | null | undefined,
+ ) {
+ let index = frames.findIndex((f) => compareEntryIds(f.id, after) > 0);
+ if (index === -1) index = frames.length;
+ let controller!: ReadableStreamDefaultController<Uint8Array>;
+ let heartbeat: ReturnType<typeof setInterval> | null = null;
+ let done: ReturnType<typeof setTimeout> | null = null;
+ const conn: FakeConnection = {
+ method,
+ url,
+ sent: [],
+ closed: false,
+ aborted: false,
+ cut: () => end(() => controller.close()),
+ fail: () => end(() => controller.error(new TypeError("network lost"))),
+ silence: () => {
+ if (heartbeat) clearInterval(heartbeat);
+ heartbeat = null;
+ },
+ };
+ function end(finish: () => void) {
+ if (conn.closed) return;
+ conn.closed = true;
+ if (heartbeat) clearInterval(heartbeat);
+ if (done) clearTimeout(done);
+ pumps.delete(pump);
+ finish();
+ }
+ function pump() {
+ while (!conn.closed && index < published) {
+ const frame = frames[index++];
+ conn.sent.push(frame.id);
+ controller.enqueue(encoder.encode(frame.sse));
+ if (dataOf(frame.sse)?.type === "finish") {
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
+ end(() => controller.close());
+ }
+ }
+ if (stoppedWithoutFinish && !conn.closed && !done) {
+ done = setTimeout(() => {
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
+ end(() => controller.close());
+ }, LISTENER_READ_MS);
+ }
+ }
+ connections.push(conn);
+ const stream = new ReadableStream<Uint8Array>({
+ start(c) {
+ controller = c;
+ heartbeat = setInterval(() => {
+ if (!conn.closed) c.enqueue(encoder.encode(": heartbeat\n\n"));
+ }, HEARTBEAT_MS);
+ pumps.add(pump);
+ pump();
+ },
+ cancel() {
+ conn.aborted = true;
+ end(() => {});
+ },
+ });
+ signal?.addEventListener("abort", () => {
+ conn.aborted = true;
+ end(() => {});
+ });
+ return stream;
+ }
+
+ return {
+ turnId,
+ connections,
+ requests,
+ fetch: fetchImpl as typeof fetch,
+ /** Publish the next `count` entries (default: all of them). */
+ publish(count = Infinity) {
+ started = true;
+ running = true;
+ published = Math.min(frames.length, published + count);
+ if (published === frames.length) running = false;
+ pumps.forEach((pump) => pump());
+ },
+ /**
+ * The meta stops saying running while the stream holds no finish (a
+ * crash between the status CAS and the finish publish): every read ends
+ * with `[DONE]` once it has nothing left to replay.
+ */
+ stopWithoutFinish() {
+ running = false;
+ stoppedWithoutFinish = true;
+ pumps.forEach((pump) => pump());
+ },
+ /** The turn is already running when the page loads. */
+ beginRunning() {
+ started = true;
+ running = true;
+ },
+ respond(next: Responder) {
+ responder = next;
+ },
+ /** The last checkpoint published, as `active_stream.checkpoint` names it. */
+ lastCheckpoint() {
+ for (let i = published - 1; i >= 0; i--) {
+ const data = dataOf(frames[i].sse);
+ if (data?.type === "data-checkpoint") {
+ return {
+ entry_id: frames[i].id,
+ rows: Number(data.data.rows),
+ sequence: Number(data.data.sequence),
+ };
+ }
+ }
+ return null;
+ },
+ view(rows?: PersistedRow[]): SessionView {
+ const shown = started
+ ? (rows ?? turn.rows.slice(0, persistedCount()))
+ : [];
+ return {
+ messages: shown.map((row, sequence) => ({ ...row, sequence })),
+ has_more_messages: false,
+ active_stream: running
+ ? { turn_id: turnId, checkpoint: this.lastCheckpoint() }
+ : null,
+ };
+ },
+ open() {
+ return connections.filter((c) => !c.closed);
+ },
+ };
+}
+
+export type FakeBackend = ReturnType<typeof fakeBackend>;
+
+function idOf(sse: string) {
+ const line = sse.split("\n").find((l) => l.startsWith("id: ")) ?? "";
+ return line.slice(line.lastIndexOf(":") + 1);
+}
+
+function turnOf(sse: string) {
+ const line = sse.split("\n").find((l) => l.startsWith("id: ")) ?? "";
+ return line.slice("id: ".length, line.lastIndexOf(":"));
+}
+
+function dataOf(sse: string) {
+ const line = sse.split("\n").find((l) => l.startsWith("data: "));
+ return line
+ ? (JSON.parse(line.slice("data: ".length)) as {
+ type: string;
+ data: Record<string, unknown>;
+ })
+ : null;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/textReveal.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/textReveal.test.ts
new file mode 100644
index 0000000000..d834f0b8cf
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/textReveal.test.ts
@@ -0,0 +1,55 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import { TextReveal } from "../textReveal";
+import { emptyTurnLog, type TurnLog } from "../turnLog";
+import { newTurnSegment, type Segment } from "../turnTail";
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+it("re-renders only while the reveal moves", () => {
+ const log = openTextLog("Let me fetch that page for you.");
+ const segment = newTurnSegment("turn-1", log);
+ const onTick = vi.fn();
+ const reveal = new TextReveal(() => [segment], onTick);
+ reveal.track(emptyTurnLog(), log);
+
+ vi.advanceTimersByTime(1_000);
+ const shown = textOf(reveal.display(segment));
+ const revealing = onTick.mock.calls.length;
+ expect(revealing).toBeGreaterThan(0);
+
+ // The block stays open; the last word waits for its end, so nothing moves.
+ vi.advanceTimersByTime(1_000);
+ expect(textOf(reveal.display(segment))).toBe(shown);
+ expect(onTick).toHaveBeenCalledTimes(revealing);
+ reveal.dispose();
+});
+
+function openTextLog(content: string): TurnLog {
+ return {
+ ...emptyTurnLog(),
+ turnId: "turn-1",
+ rows: [
+ {
+ key: "block-1",
+ role: "assistant",
+ content,
+ toolCalls: [],
+ toolCallId: null,
+ sequence: null,
+ metadata: null,
+ },
+ ],
+ blocks: { "block-1": { kind: "text", open: true, row: 0 } },
+ };
+}
+
+function textOf(segment: Segment) {
+ return segment.kind === "turn" ? segment.log.rows[0].content : null;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts
new file mode 100644
index 0000000000..9f9870d2f1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts
@@ -0,0 +1,545 @@
+import type { UIMessage } from "ai";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type Mock,
+} from "vitest";
+
+import { createTailRenderer } from "../renderTail";
+import {
+ ANOMALY_TOAST,
+ LIVENESS_MS,
+ ROTATE_AFTER_MS,
+ TurnRuntime,
+ type RuntimeDeps,
+ type RuntimeSnapshot,
+} from "../turnRuntime";
+import { fakeBackend, type FakeBackend } from "./fakeBackend";
+import { loadRecordedTurn } from "./recordedTurns";
+
+const toolTurn = loadRecordedTurn("baseline-tool-turn");
+const PROMPT = String(toolTurn.rows[0].content);
+// 9-0 ends the first text block, 12-0 opens the tool call, 20-0 is the checkpoint.
+const FIRST_BLOCK_DONE = 9;
+const TOOL_CALL_OPEN = 12;
+const FIRST_TEXT = "Let me fetch that page.";
+const SECOND_TEXT = "It says Example Domain.";
+
+let backend: FakeBackend;
+let runtime: TurnRuntime;
+let toast: Mock<RuntimeDeps["toast"]>;
+let report: Mock<RuntimeDeps["report"]>;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ setVisibility("visible");
+ backend = fakeBackend(toolTurn);
+ toast = vi.fn<RuntimeDeps["toast"]>();
+ report = vi.fn<RuntimeDeps["report"]>();
+ runtime = new TurnRuntime("session-1", {
+ baseUrl: () => "http://backend.test",
+ headers: async () => ({}),
+ fetch: backend.fetch,
+ fetchSession: async () => backend.view(),
+ toast,
+ report,
+ });
+});
+
+afterEach(() => {
+ runtime.dispose();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ setVisibility("visible");
+});
+
+describe("§1.7 — every disconnect cause is expected but one", () => {
+ it("a tab hidden when its stream drops resumes on return, silently", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ setVisibility("hidden");
+ backend.connections[0].fail();
+ await advance(60_000);
+ expect(backend.connections).toHaveLength(1);
+
+ setVisibility("visible");
+ await advance(0);
+ expect(backend.connections).toHaveLength(2);
+ expect(backend.connections[1].url.searchParams.get("after")).toBe("9-0");
+ backend.publish();
+ await advance(1_000);
+
+ expect(snapshot().phase).toBe("finished");
+ expect(textsOf(render())).toEqual([PROMPT, `${FIRST_TEXT}${SECOND_TEXT}`]);
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a tab shown again over a live stream opens nothing", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ setVisibility("hidden");
+ await advance(25_000);
+ setVisibility("visible");
+ await advance(0);
+ expect(backend.connections).toHaveLength(1);
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("the load balancer's cut, landing before the rotation, resumes at once", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.connections[0].cut();
+ await advance(0);
+ expect(backend.connections).toHaveLength(2);
+ expect(backend.connections[1].url.searchParams.get("after")).toBe("9-0");
+ expect(snapshot().notice).toBeNull();
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a trimmed or expired stream is caught up from the rows, without a toast", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.publish();
+ backend.respond(() => ({ status: 410, body: { reason: "expired" } }));
+ backend.connections[0].fail();
+ await advance(1_000);
+ expect(snapshot().phase).toBe("finished");
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("two minutes of model silence with heartbeats is not a disconnect", async () => {
+ await sendAndPublish(TOOL_CALL_OPEN);
+ await advance(120_000);
+ expect(backend.connections).toHaveLength(1);
+ expect(snapshot().phase).toBe("live");
+ expect(snapshot().notice).toBeNull();
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a turn that ended while disconnected ends on its stored finish, and is reconciled", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.respond(() => "network-error");
+ backend.connections[0].fail();
+ backend.publish();
+ backend.respond(() => "stream");
+ await advance(3_000);
+
+ expect(snapshot().phase).toBe("finished");
+ const turn = turnSegment();
+ expect(turn.reconciled).toBe(true);
+ expect(turn.log.rows.map((r) => r.sequence)).toEqual([1, 2, 3]);
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a stream the user stopped is never resumed", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ runtime.stop();
+ await advance(60_000);
+ expect(backend.connections).toHaveLength(1);
+ expect(backend.connections[0].aborted).toBe(true);
+ expect(snapshot().stopped).toBe(true);
+ expect(textsOf(render()).at(-1)).toContain("Operation cancelled");
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a stop before the POST names its turn never attaches to that turn", async () => {
+ void runtime.send({ text: PROMPT }, undefined);
+ await advance(0);
+ runtime.stop();
+ // The server runs the turn on for a moment, and the view says so.
+ backend.publish(FIRST_BLOCK_DONE);
+ runtime.observe(backend.view());
+ await advance(60_000);
+ expect(backend.connections).toHaveLength(1);
+ expect(snapshot().stopped).toBe(true);
+ });
+
+ it("a connection silent for 30 s is replaced without a toast", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.connections[0].silence();
+ await advance(LIVENESS_MS + 5_000);
+ expect(backend.connections[0].aborted).toBe(true);
+ expect(backend.connections).toHaveLength(2);
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("failures while visible and online back off, show an inline notice, and toast once after five", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.respond(() => "network-error");
+ backend.connections[0].fail();
+ await advance(0);
+ expect(snapshot().notice).toBeNull();
+
+ // Attempts after the first drop: 1, 2, 4 and 8 s apart.
+ await advance(1_000);
+ expect(snapshot().notice).toBe("reconnecting");
+ await advance(2_000 + 4_000 + 8_000);
+ expect(toast).toHaveBeenCalledTimes(1);
+ expect(toast).toHaveBeenCalledWith(ANOMALY_TOAST);
+
+ // It keeps trying: every 30 s after the backoff runs out.
+ await advance(16_000 + 30_000 + 30_000);
+ expect(toast).toHaveBeenCalledTimes(1);
+ // The next attempt connects; its first frame clears the notice.
+ backend.respond(() => "stream");
+ await advance(30_000 + 15_000);
+ expect(snapshot().notice).toBeNull();
+ expect(snapshot().phase).toBe("live");
+ });
+
+ it("offline waits for the network, with a notice and no toast", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false);
+ backend.connections[0].fail();
+ await advance(60_000);
+ expect(backend.connections).toHaveLength(1);
+ expect(snapshot().notice).toBe("offline");
+
+ online.mockReturnValue(true);
+ window.dispatchEvent(new Event("online"));
+ await advance(0);
+ expect(backend.connections).toHaveLength(2);
+ expect(snapshot().notice).toBeNull();
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("an executor that died ends the turn inline as interrupted, never with the connection toast", async () => {
+ await sendAndPublish(TOOL_CALL_OPEN);
+ backend.respond(() => ({ status: 410, body: { reason: "expired" } }));
+ backend.connections[0].fail();
+ await advance(1_000);
+
+ expect(snapshot().phase).toBe("finished");
+ const messages = render();
+ expect(textsOf(messages).at(-1)).toContain("Response was interrupted");
+ expect(toolStates(messages)).toEqual(["output-error"]);
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a resume that yields only the end marker while the view shows no active turn ends the turn, inline", async () => {
+ await sendAndPublish(toolTurn.sse.length - 1);
+ backend.stopWithoutFinish();
+ await advance(60_000);
+
+ expect(backend.connections.map((c) => c.method)).toEqual(["POST", "GET"]);
+ expect(snapshot().phase).toBe("finished");
+ expect(turnSegment().reconciled).toBe(true);
+ expect(textsOf(render())).toEqual([PROMPT, `${FIRST_TEXT}${SECOND_TEXT}`]);
+ expect(textsOf(render()).join()).not.toContain("interrupted");
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a resume that yields only the end marker while the view still runs the turn backs off", async () => {
+ await sendAndPublish(toolTurn.sse.length - 1);
+ runtime.bind({}, async () => ({
+ ...backend.view(),
+ active_stream: { turn_id: backend.turnId },
+ }));
+ backend.stopWithoutFinish();
+ await advance(60_000);
+
+ // At once after the POST's close, then 1, 2, 4 and 8 s after each 5 s read.
+ expect(backend.connections.filter((c) => c.method === "GET")).toHaveLength(
+ 5,
+ );
+ expect(snapshot().notice).toBe("reconnecting");
+ });
+});
+
+describe("recovery", () => {
+ it("a resync in flight keeps every other trigger from reconnecting", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.connections[0].fail();
+ backend.publish();
+ const checkpoint = backend.lastCheckpoint();
+ backend.respond(({ url }) =>
+ url.searchParams.get("after") === "9-0"
+ ? { status: 409, body: { reason: "trimmed", checkpoint } }
+ : "stream",
+ );
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => (release = resolve));
+ runtime.bind({}, async () => {
+ await held;
+ return backend.view();
+ });
+ await advance(1_000);
+ const before = backend.requests.length;
+
+ // The tab returns and the network event lands while the view is fetched.
+ window.dispatchEvent(new Event("online"));
+ setVisibility("hidden");
+ setVisibility("visible");
+ await advance(1_000);
+ expect(backend.requests).toHaveLength(before);
+
+ release();
+ await advance(1_000);
+ expect(backend.requests.at(-1)?.url.searchParams.get("after")).toBe("20-0");
+ expect(turnSegment().frozen).toBe(false);
+ expect(snapshot().phase).toBe("finished");
+ });
+
+ it("a send lost while hidden is found on return", async () => {
+ backend.respond(({ method }) =>
+ method === "POST" ? "network-error" : "stream",
+ );
+ setVisibility("hidden");
+ void runtime.send({ text: PROMPT }, undefined);
+ await advance(60_000);
+ expect(snapshot().phase).toBe("idle");
+
+ // The backend started the turn anyway.
+ backend.beginRunning();
+ backend.publish(FIRST_BLOCK_DONE);
+ setVisibility("visible");
+ await advance(1_000);
+ expect(backend.connections.at(-1)?.url.searchParams.get("turn")).toBe(
+ backend.turnId,
+ );
+ expect(textsOf(render())).toEqual([PROMPT, FIRST_TEXT]);
+ });
+
+ it("a lost resend of the same prompt takes no earlier prompt's row", async () => {
+ await sendAndPublish(toolTurn.sse.length);
+ await advance(2_000);
+ backend.respond(({ method }) =>
+ method === "POST" ? "network-error" : "stream",
+ );
+ void runtime.send({ text: PROMPT }, undefined);
+ await advance(10_000);
+
+ expect(textsOf(render())).toEqual([
+ PROMPT,
+ `${FIRST_TEXT}${SECOND_TEXT}`,
+ PROMPT,
+ ]);
+ });
+});
+
+describe("one connection slot", () => {
+ it("W1: two resumes inside the window open one connection and draw one bubble", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ setVisibility("hidden");
+ backend.connections[0].fail();
+ await advance(10_000);
+
+ // The tab returns and the network event lands in the same tick.
+ setVisibility("visible");
+ window.dispatchEvent(new Event("online"));
+ await advance(0);
+ expect(backend.connections).toHaveLength(2);
+
+ backend.publish();
+ await advance(1_000);
+ const assistant = render().filter((m) => m.role === "assistant");
+ expect(assistant).toHaveLength(1);
+ expect(textsOf(assistant)).toEqual([`${FIRST_TEXT}${SECOND_TEXT}`]);
+ });
+});
+
+describe("rotation", () => {
+ it("opens the second connection before closing the first, and applies no entry twice", async () => {
+ // Auth headers take a moment, so the entry published as the rotation
+ // starts reaches the first connection before the second request leaves.
+ runtime.dispose();
+ runtime = new TurnRuntime("session-1", {
+ baseUrl: () => "http://backend.test",
+ headers: () =>
+ new Promise((resolve) => setTimeout(() => resolve({}), 50)),
+ fetch: backend.fetch,
+ fetchSession: async () => backend.view(),
+ toast,
+ report,
+ });
+ void runtime.send({ text: PROMPT }, undefined);
+ await advance(100);
+ backend.publish(6);
+ await advance(100);
+
+ // The rotation tick fires at 25 minutes; its request waits on headers.
+ await advance(ROTATE_AFTER_MS - 200 + 10);
+ expect(runtime.getSnapshot().phase).toBe("live");
+ backend.publish(1);
+ await advance(100);
+ const [first, second] = backend.connections;
+ expect(backend.connections).toHaveLength(2);
+ expect(second.url.searchParams.get("after")).toBe("6-0");
+ // Both carried the entry; the first applied it and then was retired.
+ expect(first.sent.at(-1)).toBe("7-0");
+ expect(second.sent).toEqual(["7-0"]);
+ expect(first.aborted).toBe(true);
+ // Checked here: the end-of-turn reconcile would heal a doubled row.
+ expect(turnSegment().log.rows.map((r) => r.content)).toEqual([
+ "Let me fetch that ",
+ ]);
+
+ backend.publish();
+ await advance(1_000);
+ expect(textsOf(render())).toEqual([PROMPT, `${FIRST_TEXT}${SECOND_TEXT}`]);
+ expect(turnSegment().log.protocolErrors).toEqual([]);
+ expect(report).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("a connection lost past the rotation age resumes at once", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ // Every rotation fails to open, so the first connection lives to the
+ // load balancer's cut.
+ backend.respond(({ method }) =>
+ method === "GET" ? "network-error" : "stream",
+ );
+ await advance(ROTATE_AFTER_MS + 60_000);
+ backend.respond(() => "stream");
+ backend.connections[0].fail();
+ await advance(0);
+ expect(backend.connections).toHaveLength(2);
+ expect(backend.connections[1].url.searchParams.get("after")).toBe("9-0");
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("keeps the first connection open until the second delivers a frame", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ await advance(ROTATE_AFTER_MS + 5_000 - 1);
+ const [first, second] = backend.connections;
+ expect(second.url.searchParams.get("after")).toBe("9-0");
+ expect(first.closed).toBe(false);
+ await advance(10_000);
+ expect(first.aborted).toBe(true);
+ });
+});
+
+describe("resync", () => {
+ it("a trimmed stream seeds from the rows at its checkpoint, then tails from it", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ // The turn completes while the client is away, and its stream is
+ // trimmed to the last checkpoint.
+ backend.connections[0].fail();
+ backend.publish();
+ const checkpoint = backend.lastCheckpoint();
+ expect(checkpoint?.entry_id).toBe("20-0");
+ backend.respond(({ url }) =>
+ url.searchParams.get("after") === "9-0"
+ ? { status: 409, body: { reason: "trimmed", checkpoint } }
+ : "stream",
+ );
+ await advance(2_000);
+
+ const tail = backend.connections.at(-1)!;
+ expect(tail.url.searchParams.get("after")).toBe("20-0");
+ expect(snapshot().phase).toBe("finished");
+ expect(turnSegment().log.rows.map((r) => r.content)).toEqual(
+ toolTurn.rows.slice(1).map((r) => r.content),
+ );
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("an expired stream takes the persisted rows as the whole truth", async () => {
+ await sendAndPublish(FIRST_BLOCK_DONE);
+ backend.publish();
+ backend.respond(() => ({ status: 410, body: { reason: "expired" } }));
+ backend.connections[0].fail();
+ await advance(1_000);
+
+ expect(turnSegment().ended).toBe(true);
+ expect(textsOf(render())).toEqual([PROMPT, `${FIRST_TEXT}${SECOND_TEXT}`]);
+ expect(textsOf(render()).join()).not.toContain("interrupted");
+ });
+
+ it("a fresh mount seeds the running turn from its checkpoint and tails from there", async () => {
+ backend.beginRunning();
+ backend.publish(20);
+ runtime.observe(backend.view());
+ await advance(0);
+ expect(backend.connections[0].url.searchParams.get("after")).toBe("20-0");
+ expect(snapshot().ownedFrom).toBe(1);
+ backend.publish();
+ await advance(1_000);
+ expect(textsOf(render())).toEqual([`${FIRST_TEXT}${SECOND_TEXT}`]);
+ });
+});
+
+describe("the end-of-turn reconcile", () => {
+ it("adopts the rows' sequences and keeps every message object", async () => {
+ await sendAndPublish(toolTurn.sse.length - 1);
+ const before = render();
+ backend.publish();
+ await advance(1_000);
+
+ const turn = turnSegment();
+ expect(turn.reconciled).toBe(true);
+ expect(turn.log.rows.map((r) => r.sequence)).toEqual([1, 2, 3]);
+ const after = render();
+ expect(after.map((m) => m.id)).toEqual(before.map((m) => m.id));
+ expect(report).not.toHaveBeenCalled();
+ });
+
+ it("replaces a row that differs under its own key, and reports it", async () => {
+ await sendAndPublish(toolTurn.sse.length - 1);
+ const before = render();
+ const rows = toolTurn.rows.map((row) =>
+ row.content === SECOND_TEXT ? { ...row, content: "It says Other." } : row,
+ );
+ backend.publish();
+ vi.spyOn(backend, "view").mockImplementation(() => ({
+ messages: rows.map((row, sequence) => ({ ...row, sequence })),
+ has_more_messages: false,
+ active_stream: null,
+ }));
+ await advance(1_000);
+
+ expect(render().map((m) => m.id)).toEqual(before.map((m) => m.id));
+ expect(textsOf(render())).toEqual([PROMPT, `${FIRST_TEXT}It says Other.`]);
+ expect(report).toHaveBeenCalledWith(
+ "finish",
+ expect.objectContaining({ diffs: [{ index: 2, fields: ["content"] }] }),
+ );
+ });
+});
+
+async function sendAndPublish(count: number) {
+ void runtime.send({ text: PROMPT }, undefined);
+ await advance(0);
+ backend.publish(count);
+ await advance(100);
+}
+
+async function advance(ms: number) {
+ await vi.advanceTimersByTimeAsync(ms);
+}
+
+function snapshot(): RuntimeSnapshot {
+ return runtime.getSnapshot();
+}
+
+function turnSegment() {
+ const turn = snapshot().segments.find((s) => s.kind === "turn");
+ if (turn?.kind !== "turn") throw new Error("no turn");
+ return turn;
+}
+
+const renderTail = createTailRenderer("session-1");
+function render() {
+ return renderTail(snapshot()).messages;
+}
+
+function textsOf(messages: UIMessage[]) {
+ return messages.map((m) =>
+ m.parts.map((p) => (p.type === "text" ? p.text : "")).join(""),
+ );
+}
+
+function toolStates(messages: UIMessage[]) {
+ return messages
+ .flatMap((m) => m.parts)
+ .filter((p) => p.type.startsWith("tool-"))
+ .map((p) => (p as { state: string }).state);
+}
+
+function setVisibility(state: "hidden" | "visible") {
+ Object.defineProperty(document, "visibilityState", {
+ value: state,
+ configurable: true,
+ });
+ document.dispatchEvent(new Event("visibilitychange"));
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnTail.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnTail.test.ts
new file mode 100644
index 0000000000..78f1a6b636
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnTail.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from "vitest";
+
+import { emptyTurnLog, type LogRow, type PersistedRow } from "../turnLog";
+import {
+ mergeRows,
+ newTurnSegment,
+ turnRows,
+ userSegment,
+ type Segment,
+} from "../turnTail";
+
+describe("turnRows", () => {
+ it("stops a stopped turn's rows at the next prompt, before that prompt has a sequence", () => {
+ // A send right after a stop: the next prompt is still local when the
+ // stopped turn reconciles, and its row is already persisted.
+ const stopped = {
+ ...newTurnSegment("turn-1", emptyTurnLog()),
+ stopped: true,
+ };
+ const segments: Segment[] = [
+ { ...userSegment(prompt("first"), "sent"), sequence: 0 },
+ stopped,
+ userSegment(prompt("second"), "sent"),
+ ];
+ const rows: PersistedRow[] = [
+ { role: "user", content: "first", sequence: 0 },
+ { role: "assistant", content: "Partial", sequence: 1 },
+ {
+ role: "assistant",
+ content: "[__COPILOT_ERROR_f7a1__] Operation cancelled",
+ sequence: 2,
+ },
+ { role: "user", content: "second", sequence: 3 },
+ { role: "assistant", content: "Next reply", sequence: 4 },
+ ];
+
+ const persisted = turnRows(segments, 0, stopped, rows);
+
+ expect(persisted?.start).toBe(1);
+ expect(persisted?.rows.map((r) => r.content)).toEqual([
+ "Partial",
+ "[__COPILOT_ERROR_f7a1__] Operation cancelled",
+ ]);
+ });
+});
+
+describe("turnRows", () => {
+ it("finds a repeated prompt's row after the rows the tail already holds", () => {
+ const answered = newTurnSegment("turn-1", {
+ ...emptyTurnLog(),
+ rows: [row("block-1", "Hello", 1)],
+ });
+ // Stopped before its first checkpoint, so its start is found by its prompt.
+ const stopped = {
+ ...newTurnSegment("turn-2", emptyTurnLog()),
+ stopped: true,
+ };
+ const segments: Segment[] = [
+ { ...userSegment(prompt("hi"), "sent"), sequence: 0 },
+ answered,
+ userSegment(prompt("hi"), "sent"),
+ stopped,
+ ];
+ const rows: PersistedRow[] = [
+ { role: "user", content: "hi", sequence: 0 },
+ { role: "assistant", content: "Hello", sequence: 1 },
+ { role: "user", content: "hi", sequence: 2 },
+ { role: "assistant", content: "Partial", sequence: 3 },
+ ];
+
+ const persisted = turnRows(segments, 0, stopped, rows);
+
+ expect(persisted?.start).toBe(3);
+ expect(persisted?.rows.map((r) => r.content)).toEqual(["Partial"]);
+ });
+});
+
+describe("mergeRows", () => {
+ it("keeps every on-screen key, and an equal row's object", () => {
+ const live = [row("block-1", "Hello", 1), row("block-2", "Bye", null)];
+ const persisted = [row("seq:1", "Hello", 1), row("seq:2", "Goodbye", 2)];
+
+ const merged = mergeRows(live, persisted);
+
+ expect(merged.map((r) => r.key)).toEqual(["block-1", "block-2"]);
+ expect(merged[0]).toBe(live[0]);
+ expect(merged[1]).toMatchObject({ content: "Goodbye", sequence: 2 });
+ });
+
+ it("drops streamed rows past the DB's end once an earlier row is out of place", () => {
+ // The fold holds one row the DB does not, so every later index is shifted.
+ const live = [
+ row("block-0", "Thinking", null),
+ row("block-1", "Hello", null),
+ row("block-2", "Bye", null),
+ ];
+ const persisted = [row("seq:1", "Hello", 1), row("seq:2", "Bye", 2)];
+
+ expect(mergeRows(live, persisted).map((r) => r.content)).toEqual([
+ "Hello",
+ "Bye",
+ ]);
+ });
+});
+
+function row(key: string, content: string, sequence: number | null): LogRow {
+ return {
+ key,
+ role: "assistant",
+ content,
+ toolCalls: [],
+ toolCallId: null,
+ sequence,
+ metadata: null,
+ };
+}
+
+function prompt(text: string) {
+ return {
+ id: `local:${text}`,
+ role: "user" as const,
+ parts: [{ type: "text" as const, text }],
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/renderTail.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/renderTail.ts
new file mode 100644
index 0000000000..02873f9d85
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/renderTail.ts
@@ -0,0 +1,134 @@
+import type { UIDataTypes, UIMessage, UITools } from "ai";
+
+import {
+ convertChatSessionMessagesToUiMessages,
+ createTurnLogRenderer,
+ type TurnStatsMap,
+} from "../helpers/convertChatSessionToUiMessages";
+import type { RuntimeSnapshot } from "./turnRuntime";
+import type { RowsSegment } from "./turnTail";
+
+type UiMessage = UIMessage<unknown, UIDataTypes, UITools>;
+
+/**
+ * Render the runtime's tail with one renderer per turn, so a turn's bubbles
+ * keep their objects, and so their keys, for the life of the mount.
+ */
+export function createTailRenderer(sessionId: string) {
+ const turnRenderers = new Map<
+ string,
+ ReturnType<typeof createTurnLogRenderer>
+ >();
+ const rowsMessages = new WeakMap<RowsSegment, UiMessage[]>();
+
+ return function renderTail(snapshot: RuntimeSnapshot) {
+ const messages: UiMessage[] = [];
+ const stats: TurnStatsMap = new Map();
+ const drained = drainedTexts(snapshot);
+ for (const seg of snapshot.segments) {
+ if (seg.kind === "user") {
+ // A drained row in the turn stands in for its promoted chip.
+ if (seg.origin === "chip" && takeOne(drained, textOf(seg.message))) {
+ continue;
+ }
+ messages.push(seg.message as UiMessage);
+ if (seg.rawId || seg.createdAt) {
+ stats.set(seg.key, {
+ ...(seg.rawId ? { rawMessageId: seg.rawId } : {}),
+ ...(seg.createdAt ? { createdAt: seg.createdAt } : {}),
+ });
+ }
+ } else if (seg.kind === "rows") {
+ let converted = rowsMessages.get(seg);
+ if (!converted) {
+ converted = convertChatSessionMessagesToUiMessages(
+ sessionId,
+ [...seg.rows],
+ { isComplete: true },
+ ).messages;
+ rowsMessages.set(seg, converted);
+ }
+ messages.push(...converted);
+ } else {
+ let render = turnRenderers.get(seg.key);
+ if (!render) {
+ render = createTurnLogRenderer();
+ turnRenderers.set(seg.key, render);
+ }
+ const rendered = render(seg.log);
+ messages.push(...rendered);
+ for (const message of rendered) {
+ const at = seg.rowCreatedAt[message.id];
+ if (message.role === "user" && at)
+ stats.set(message.id, { createdAt: at });
+ }
+ const last = rendered.findLast((m) => m.role === "assistant");
+ if (last && (seg.durationMs !== null || seg.createdAt)) {
+ stats.set(last.id, {
+ ...(seg.durationMs !== null ? { durationMs: seg.durationMs } : {}),
+ ...(seg.createdAt ? { createdAt: seg.createdAt } : {}),
+ });
+ }
+ }
+ }
+ return { messages, stats };
+ };
+}
+
+/**
+ * Join consecutive assistant messages as a reload does (two turns with no user
+ * row between them are one bubble), keeping the first one's key. A join is
+ * cached on its two inputs, so an unchanged pair stays the same object.
+ */
+export function createAssistantRunJoiner() {
+ const joins = new WeakMap<UiMessage, WeakMap<UiMessage, UiMessage>>();
+ return function joinAssistantRuns(messages: UiMessage[]) {
+ const joined: UiMessage[] = [];
+ for (const message of messages) {
+ const last = joined[joined.length - 1];
+ if (
+ last?.role !== "assistant" ||
+ message.role !== "assistant" ||
+ last.metadata ||
+ message.metadata
+ ) {
+ joined.push(message);
+ continue;
+ }
+ let byNext = joins.get(last);
+ if (!byNext) joins.set(last, (byNext = new WeakMap()));
+ let pair = byNext.get(message);
+ if (!pair) {
+ pair = { ...last, parts: [...last.parts, ...message.parts] };
+ byNext.set(message, pair);
+ }
+ joined[joined.length - 1] = pair;
+ }
+ return joined;
+ };
+}
+
+function drainedTexts(snapshot: RuntimeSnapshot) {
+ const texts = new Map<string, number>();
+ for (const seg of snapshot.segments) {
+ if (seg.kind !== "turn") continue;
+ for (const row of seg.log.rows) {
+ if (row.role !== "user") continue;
+ texts.set(row.content, (texts.get(row.content) ?? 0) + 1);
+ }
+ }
+ return texts;
+}
+
+function takeOne(texts: Map<string, number>, text: string) {
+ const count = texts.get(text) ?? 0;
+ if (count === 0) return false;
+ texts.set(text, count - 1);
+ return true;
+}
+
+function textOf(message: UIMessage) {
+ return message.parts
+ .map((part) => (part.type === "text" ? part.text : ""))
+ .join("");
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/sseClient.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/sseClient.ts
index dc45bdbd05..30d4604480 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/sseClient.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/sseClient.ts
@@ -23,11 +23,12 @@ export async function fetchSse(
url: string,
init: RequestInit,
onFrame: (frame: SseFrame) => void,
+ fetchImpl: typeof fetch = fetch,
): Promise<SseResult> {
- const response = await fetch(url, init);
+ const response = await fetchImpl(url, init);
if (!response.ok || !response.body) {
- const body = await response.json().catch(() => null);
- return { ok: false, status: response.status, body };
+ const text = await response.text().catch(() => "");
+ return { ok: false, status: response.status, body: parseBody(text) };
}
await readSseFrames(response.body, onFrame, init.signal ?? undefined);
return { ok: true };
@@ -85,3 +86,13 @@ function toFrame(id: string | undefined, data: string): SseFrame | null {
if (!parsed) return { kind: "synthetic", chunk };
return { kind: "entry", entry: { ...parsed, chunk } };
}
+
+// A refusal is JSON from the API, or plain text from a proxy in front of it.
+function parseBody(text: string): unknown {
+ if (!text) return null;
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ return text;
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/textReveal.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/textReveal.ts
new file mode 100644
index 0000000000..89fe66a256
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/textReveal.ts
@@ -0,0 +1,108 @@
+import {
+ BACKLOG_DRAIN_TICKS,
+ findWordCutPoints,
+ TICK_DELAY_MS,
+} from "../copilotStreamSmoothing";
+import type { LogRow, TurnLog } from "./turnLog";
+import type { Segment } from "./turnTail";
+
+const REVEAL_TICK_MS = 30;
+
+/**
+ * Paces the text the live POST stream writes, as the smoothing transform does
+ * on the AI SDK path: what is shown lags what is applied, so the cursor and
+ * the turn log stay exact.
+ */
+export class TextReveal {
+ // Characters shown so far of each row a live block is writing.
+ private shown = new Map<string, number>();
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private displayRows = new WeakMap<LogRow, { shown: number; row: LogRow }>();
+
+ constructor(
+ private readonly segments: () => readonly Segment[],
+ private readonly onTick: () => void,
+ ) {}
+
+ /** Rows a live block writes into show from where they stood before this entry. */
+ track(prev: TurnLog, next: TurnLog) {
+ for (const block of Object.values(next.blocks)) {
+ if (!block.open || block.row === null) continue;
+ const row = next.rows[block.row];
+ if (!this.shown.has(row.key)) {
+ this.shown.set(row.key, prev.rows[block.row]?.content.length ?? 0);
+ }
+ }
+ if (this.shown.size > 0 && !this.timer) {
+ this.timer = setInterval(() => this.tick(), REVEAL_TICK_MS);
+ }
+ }
+
+ /** Show everything: a resumed stream or a stop does not pace. */
+ clear() {
+ this.shown.clear();
+ }
+
+ /** The segment as shown: rows still revealing are cut where the reveal stands. */
+ display(seg: Segment): Segment {
+ if (seg.kind !== "turn" || this.shown.size === 0) return seg;
+ let changed = false;
+ const rows = seg.log.rows.map((row) => {
+ const shown = this.shown.get(row.key);
+ if (shown === undefined || shown >= row.content.length) return row;
+ changed = true;
+ const cached = this.displayRows.get(row);
+ if (cached?.shown === shown) return cached.row;
+ const display = { ...row, content: row.content.slice(0, shown) };
+ this.displayRows.set(row, { shown, row: display });
+ return display;
+ });
+ return changed ? { ...seg, log: { ...seg.log, rows } } : seg;
+ }
+
+ dispose() {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+
+ // Each tick shows what the transform would have emitted over it: a share of
+ // the backlog per 10 ms, a whole word at least.
+ private tick() {
+ const open = openRows(this.segments());
+ let moved = false;
+ for (const [key, shown] of this.shown) {
+ const row = open.get(key);
+ if (!row) {
+ this.shown.delete(key);
+ moved = true;
+ continue;
+ }
+ let next = shown;
+ for (let t = 0; t < REVEAL_TICK_MS / TICK_DELAY_MS; t++) {
+ const cuts = findWordCutPoints(row.content.slice(next));
+ if (cuts.length === 0) break;
+ const words = Math.max(1, Math.ceil(cuts.length / BACKLOG_DRAIN_TICKS));
+ next += cuts[Math.min(words, cuts.length) - 1];
+ }
+ if (next !== shown) {
+ this.shown.set(key, next);
+ moved = true;
+ }
+ }
+ if (this.shown.size === 0) this.dispose();
+ if (moved) this.onTick();
+ }
+}
+
+function openRows(segments: readonly Segment[]) {
+ const rows = new Map<string, LogRow>();
+ for (const seg of segments) {
+ if (seg.kind !== "turn") continue;
+ for (const block of Object.values(seg.log.blocks)) {
+ if (!block.open || block.row === null) continue;
+ const row = seg.log.rows[block.row];
+ if (row) rows.set(row.key, row);
+ }
+ }
+ return rows;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts
new file mode 100644
index 0000000000..980a0194cf
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts
@@ -0,0 +1,1248 @@
+import { getV2GetSession } from "@/app/api/__generated__/endpoints/chat/chat";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import { environment } from "@/services/environment";
+import * as Sentry from "@sentry/nextjs";
+import type { FileUIPart, UIMessage } from "ai";
+import { v4 as uuidv4 } from "uuid";
+
+import { streamRequestBody } from "../copilotStreamTransport";
+import { getCopilotAuthHeaders, isEngineSwitchPart } from "../helpers";
+import type { CopilotLlmModel } from "../store";
+import { isTokenDevtoolEnabled } from "../tokenDevtool/gate";
+import { createUsageCapturingFetch } from "../tokenDevtool/usageTap";
+import { fetchSse, type SseFrame } from "./sseClient";
+import { TextReveal } from "./textReveal";
+import { applyEntry, type StreamEntry, type WireChunk } from "./turnConverter";
+import { seedTurnLog } from "./turnLog";
+import { diffRows, sha256Hex } from "./turnShadow";
+import {
+ checkpointOf,
+ closeBlocks,
+ FROZEN_NOTE,
+ gapSegment,
+ hasOpenParts,
+ INTERRUPTED_MARKER,
+ keepIdentity,
+ lastCheckpoint,
+ locatePrompt,
+ mergeRows,
+ newTurnSegment,
+ persistedRows,
+ promptFloor,
+ reconcileTurn,
+ tailEndSequence,
+ turnRows,
+ userSegment,
+ withMarker,
+ withPromptRow,
+ withStopMarker,
+ type Segment,
+ type TurnCheckpoint,
+ type TurnSegment,
+} from "./turnTail";
+
+/** No byte for this long means the connection is dead: the route and the
+ * listener heartbeat every 10 s and the SDK engine every 10 s of silence. */
+export const LIVENESS_MS = 30_000;
+/** The load balancer cuts an SSE at 30 minutes; rotate before it does. */
+export const ROTATE_AFTER_MS = 25 * 60_000;
+const BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 16_000];
+const ANOMALY_RETRY_MS = 30_000;
+const INDICATOR_AFTER_FAILURES = 2;
+const CATCHING_UP_AFTER_MS = 2_000;
+const TICK_MS = 5_000;
+const EMIT_THROTTLE_MS = 30;
+const FROZEN_POLL_MS = 10_000;
+const FINISH_PROBE_MS = 500;
+// A server-started continuation (engine switch, approval wake) is dispatched
+// after the turn ends; its meta can lag the finish by a few seconds.
+const CONTINUATION_PROBES = 8;
+const SETTLE_PROBES = 3;
+const MAX_RESYNCS_PER_TURN = 1;
+// Resyncing on an orphan tool output, which the backend does persist, would
+// loop; only a fold that lost track of a block or a call is rebuilt.
+const RESYNC_REASONS = new Set([
+ "unknown block",
+ "closed block",
+ "input changed",
+]);
+
+export const ANOMALY_TOAST = {
+ title: "Connection lost",
+ description: "We keep trying; your expert may still be working.",
+};
+
+export type RuntimePhase =
+ | "idle"
+ | "connecting"
+ | "live"
+ | "resuming"
+ | "finished"
+ | "failed";
+
+/** A passive, inline state; never a toast. */
+export type RuntimeNotice = "catching-up" | "reconnecting" | "offline" | null;
+
+export interface RuntimeSnapshot {
+ /** The tail this runtime owns, in order; history before it is the DB view's. */
+ segments: readonly Segment[];
+ /** First DB sequence the tail owns; null while it owns nothing. */
+ ownedFrom: number | null;
+ phase: RuntimePhase;
+ notice: RuntimeNotice;
+ error: Error | null;
+ stopped: boolean;
+}
+
+export interface SessionView {
+ messages?: readonly unknown[] | null;
+ has_more_messages?: boolean;
+ active_stream?: {
+ turn_id: string;
+ checkpoint?: TurnCheckpoint | null;
+ } | null;
+}
+
+export interface RuntimeDeps {
+ baseUrl: () => string;
+ headers: () => Promise<Record<string, string>>;
+ fetch: typeof fetch;
+ fetchSession: () => Promise<SessionView | null>;
+ toast: (options: { title: string; description: string }) => void;
+ report: (kind: string, extra: Record<string, unknown>) => void;
+}
+
+export interface RuntimeHandlers {
+ /** A turn's error entry or a refused send, with the provider failure sent before it. */
+ onError?: (error: Error, providerFailure: unknown) => void;
+ onTurnEnd?: () => void;
+}
+
+export type SendInput =
+ | { text: string; files?: FileUIPart[]; metadata?: unknown }
+ | { parts: UIMessage["parts"]; metadata?: unknown };
+
+interface Connection {
+ kind: "post" | "resume";
+ controller: AbortController;
+ openedAt: number;
+ lastFrameAt: number;
+ frames: number;
+ entries: number;
+ turnId: string | null;
+ closedByClient: boolean;
+ syntheticError: string | null;
+}
+
+/** What the classification needs to know about a connection that is gone. */
+type Lost = Pick<Connection, "turnId" | "openedAt" | "syntheticError">;
+
+type ConnectionEnd =
+ | { kind: "closed" }
+ | { kind: "refused"; status: number; body: unknown }
+ | { kind: "failed"; error: unknown };
+
+interface TurnBookkeeping {
+ verified: number;
+ reportedErrors: number;
+ resyncs: number;
+ sawModeChange: boolean;
+}
+
+/**
+ * The chat's connection to a session's running turn: one connection slot,
+ * one cursor per turn, and a tail of segments rendered from the rows the
+ * backend persists. Survives unmounts in a module-level map, as the chat
+ * runtime it replaces did, so switching sessions does not drop a stream.
+ */
+export class TurnRuntime {
+ private segments: Segment[] = [];
+ private ownedFrom: number | null = null;
+ private slot: Connection | null = null;
+ private rotating: Connection | null = null;
+ private failures = 0;
+ private anomalyShown = false;
+ private notice: RuntimeNotice = null;
+ private error: Error | null = null;
+ private stopped = false;
+ // A stopped turn keeps running on the server for a moment; never re-attach to it.
+ private suppressAttach = false;
+ private followPending = false;
+ // A resync or an expiry is rebuilding the turn; it reconnects when done.
+ private recovering = false;
+ // A send whose stream ended before naming its turn, while hidden or offline.
+ private unresolvedPost: { lost: Lost; end: ConnectionEnd } | null = null;
+ private providerFailure: unknown = null;
+ private lastViewMaxSequence: number | null = null;
+ private turns = new Map<string, TurnBookkeeping>();
+ private retryTimer: ReturnType<typeof setTimeout> | null = null;
+ private tickTimer: ReturnType<typeof setInterval> | null = null;
+ private frozenTimer: ReturnType<typeof setInterval> | null = null;
+ private emitTimer: ReturnType<typeof setTimeout> | null = null;
+ private reveal = new TextReveal(
+ () => this.segments,
+ () => this.emitNow(),
+ );
+ private listeners = new Set<() => void>();
+ private snapshot: RuntimeSnapshot;
+ private handlers: RuntimeHandlers = {};
+ private boundFetchSession: (() => Promise<SessionView | null>) | null = null;
+ private disposed = false;
+
+ constructor(
+ readonly sessionId: string,
+ private readonly deps: RuntimeDeps,
+ ) {
+ this.snapshot = this.buildSnapshot();
+ if (typeof window !== "undefined") {
+ document.addEventListener("visibilitychange", this.onVisible);
+ window.addEventListener("pageshow", this.onVisible);
+ document.addEventListener("resume", this.onVisible);
+ window.addEventListener("online", this.onOnline);
+ window.addEventListener("offline", this.onOffline);
+ }
+ }
+
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ };
+
+ getSnapshot = () => this.snapshot;
+
+ /** The mounted chat's callbacks and session fetch; an unmounted runtime falls back. */
+ bind(
+ handlers: RuntimeHandlers,
+ fetchSession: (() => Promise<SessionView | null>) | null,
+ ) {
+ this.handlers = handlers;
+ this.boundFetchSession = fetchSession;
+ return () => {
+ if (this.handlers === handlers) this.handlers = {};
+ if (this.boundFetchSession === fetchSession)
+ this.boundFetchSession = null;
+ };
+ }
+
+ /** Whether `observe(view)` would attach to the view's running turn. */
+ wouldAttach(view: SessionView) {
+ const active = view.active_stream;
+ return (
+ !!active &&
+ !this.turnFor(active.turn_id) &&
+ !this.suppressAttach &&
+ !this.isPostPending() &&
+ !this.runningTurn()
+ );
+ }
+
+ // ── The five named operations ─────────────────────────────────────────
+
+ /** POST a new turn: the prompt shows at once, and the turn follows it. */
+ async send(input: SendInput, model: CopilotLlmModel | undefined) {
+ if (this.isPostPending()) return;
+ this.stopped = false;
+ this.suppressAttach = false;
+ this.error = null;
+ this.providerFailure = null;
+ const message = userMessage(`local:${uuidv4({})}`, input);
+ this.claimTail(this.nextSequence());
+ this.segments.push(userSegment(message, "sent"));
+ this.emitNow();
+ const body = streamRequestBody(this.sessionId, message, model);
+ await this.open("post", null, this.streamUrl(), {
+ method: "POST",
+ body: JSON.stringify(body),
+ extraHeaders: { "Content-Type": "application/json" },
+ });
+ }
+
+ /** Stop following the turn: abort, mark it stopped, and let the persisted marker reconcile into it. */
+ stop() {
+ const running = this.runningTurn();
+ this.abortConnections();
+ this.clearRetry();
+ this.stopped = true;
+ this.suppressAttach = true;
+ this.notice = null;
+ this.reveal.clear();
+ if (running) {
+ this.updateTurn(running.key, (seg) => ({
+ ...seg,
+ stopped: true,
+ log: withStopMarker(seg.log),
+ }));
+ }
+ this.emitNow();
+ }
+
+ /** Promoted follow-ups; a drained row in the turn with the same text stands in for one. */
+ appendLocalUserRows(entries: readonly { id: string; text: string }[]) {
+ if (entries.length === 0) return;
+ this.claimTail(this.nextSequence());
+ for (const entry of entries) {
+ const key = `pending-chip-${entry.id}`;
+ if (this.segments.some((s) => s.key === key)) continue;
+ this.segments.push(
+ userSegment(userMessage(key, { text: entry.text }), "chip"),
+ );
+ }
+ this.emit();
+ }
+
+ /** The backend refused the send before persisting it (a 429). */
+ dropUnsentUserRow() {
+ const last = this.segments[this.segments.length - 1];
+ if (last?.kind !== "user" || last.origin !== "sent") return;
+ this.segments.pop();
+ if (this.segments.length === 0) this.ownedFrom = null;
+ this.emitNow();
+ }
+
+ /**
+ * Every fresh session view: reconcile the turns it has finished, attach
+ * to a turn it runs that this runtime does not follow, and fetch the rest
+ * of a running turn the server no longer runs.
+ */
+ observe(view: SessionView) {
+ const rows = persistedRows(view.messages);
+ const last = rows[rows.length - 1]?.sequence;
+ if (typeof last === "number") this.lastViewMaxSequence = last;
+ const active = view.active_stream ?? null;
+ if (!active) {
+ this.suppressAttach = false;
+ this.stopped = false;
+ }
+ for (const seg of this.segments) {
+ if (seg.kind !== "turn" || seg.reconciled) continue;
+ if (active?.turn_id === seg.log.turnId) continue;
+ if (seg.ended || seg.stopped || seg.frozen) this.reconcile(seg, view);
+ }
+ if (active && this.wouldAttach(view)) this.attach(active, view);
+ const running = this.runningTurn();
+ if (running && active?.turn_id !== running.log.turnId && !running.frozen) {
+ this.ensureConnected();
+ }
+ if (!running && !this.isPostPending() && !active) this.settleTail(view);
+ this.emitNow();
+ }
+
+ // ── Connection ─────────────────────────────────────────────────────────
+
+ /**
+ * Open a connection at the cursor unless one is open and delivered a frame
+ * within the liveness window. One slot, so a second call inside the window
+ * does nothing: two resumes never read one turn at once.
+ */
+ ensureConnected() {
+ const running = this.runningTurn();
+ if (!running?.log.turnId || running.frozen || this.recovering) return;
+ if (this.slot && Date.now() - this.slot.lastFrameAt < LIVENESS_MS) return;
+ this.clearRetry();
+ this.resume(running);
+ }
+
+ /** An answered approval starts the chat's next turn on the server; attach to it. */
+ followBackendTurn() {
+ if (this.runningTurn() || this.isPostPending()) {
+ this.followPending = true;
+ return;
+ }
+ void this.probe(null, CONTINUATION_PROBES, true);
+ }
+
+ dispose() {
+ this.disposed = true;
+ this.abortConnections();
+ this.clearRetry();
+ this.reveal.dispose();
+ for (const timer of [this.tickTimer, this.frozenTimer]) {
+ if (timer) clearInterval(timer);
+ }
+ if (this.emitTimer) clearTimeout(this.emitTimer);
+ if (typeof window !== "undefined") {
+ document.removeEventListener("visibilitychange", this.onVisible);
+ window.removeEventListener("pageshow", this.onVisible);
+ document.removeEventListener("resume", this.onVisible);
+ window.removeEventListener("online", this.onOnline);
+ window.removeEventListener("offline", this.onOffline);
+ }
+ }
+
+ isIdle() {
+ return !this.slot && !this.runningTurn() && !this.isPostPending();
+ }
+
+ private resume(seg: TurnSegment) {
+ const turnId = seg.log.turnId;
+ if (!turnId) return;
+ this.abortSlot();
+ void this.open("resume", turnId, this.resumeUrl(turnId, seg.log.cursor));
+ }
+
+ // Rotation opens the second connection first and retires the first on the
+ // second's first frame; entries both deliver are dropped by the cursor.
+ private rotate() {
+ const running = this.runningTurn();
+ const turnId = running?.log.turnId;
+ if (!running || !turnId || this.rotating) return;
+ void this.open(
+ "resume",
+ turnId,
+ this.resumeUrl(turnId, running.log.cursor),
+ {},
+ true,
+ );
+ }
+
+ private async open(
+ kind: Connection["kind"],
+ turnId: string | null,
+ url: string,
+ init: { method?: string; body?: string; extraHeaders?: object } = {},
+ asRotation = false,
+ ) {
+ const now = Date.now();
+ const conn: Connection = {
+ kind,
+ controller: new AbortController(),
+ openedAt: now,
+ lastFrameAt: now,
+ frames: 0,
+ entries: 0,
+ turnId,
+ closedByClient: false,
+ syntheticError: null,
+ };
+ if (asRotation) this.rotating = conn;
+ else {
+ this.abortSlot();
+ this.slot = conn;
+ }
+ this.ensureTicking();
+ this.emit();
+ let end: ConnectionEnd;
+ try {
+ const headers = await this.deps.headers();
+ const result = await fetchSse(
+ url,
+ {
+ method: init.method ?? "GET",
+ body: init.body,
+ headers: { ...headers, ...init.extraHeaders },
+ signal: conn.controller.signal,
+ },
+ (frame) => this.onFrame(conn, frame),
+ this.deps.fetch,
+ );
+ end = result.ok
+ ? { kind: "closed" }
+ : { kind: "refused", status: result.status, body: result.body };
+ } catch (error) {
+ end = { kind: "failed", error };
+ }
+ this.onEnd(conn, end);
+ }
+
+ private onFrame(conn: Connection, frame: SseFrame) {
+ if (conn !== this.slot && conn !== this.rotating) return;
+ conn.lastFrameAt = Date.now();
+ conn.frames += 1;
+ if (conn === this.rotating && conn.frames === 1) {
+ const retired = this.slot;
+ this.slot = conn;
+ this.rotating = null;
+ retired?.controller.abort();
+ if (retired) retired.closedByClient = true;
+ }
+ // Every response ends with [DONE]; only an entry or a heartbeat shows the
+ // route is following a running turn.
+ if (frame.kind === "entry" || frame.kind === "comment")
+ this.resetFailures();
+ if (frame.kind === "entry") {
+ conn.entries += 1;
+ this.applyFrom(conn, frame.entry);
+ } else if (frame.kind === "synthetic" && frame.chunk.type === "error") {
+ conn.syntheticError = str(frame.chunk.errorText);
+ }
+ this.emit();
+ }
+
+ private applyFrom(conn: Connection, entry: StreamEntry) {
+ let seg = this.turnFor(entry.turn);
+ if (!seg) {
+ if (conn.kind !== "post" || conn.turnId !== null) return;
+ seg = newTurnSegment(
+ entry.turn,
+ seedTurnLog({ turnId: entry.turn, rows: [], checkpoint: null }),
+ );
+ this.segments.push(seg);
+ }
+ conn.turnId = entry.turn;
+ if (seg.ended || seg.stopped || seg.frozen) return;
+ const next = applyEntry(seg.log, entry);
+ if (next === seg.log) return;
+ if (conn.kind === "post") this.reveal.track(seg.log, next);
+ else this.reveal.clear();
+ const key = seg.key;
+ this.updateTurn(key, (s) => ({ ...s, log: next }));
+ this.onChunk(key, entry.chunk);
+ this.checkProtocol(key);
+ void this.verifyCheckpoints(key);
+ // The turn is over at an id-bearing finish, and failed at an id-bearing error.
+ if (entry.chunk.type === "finish" || entry.chunk.type === "error") {
+ this.endTurn(key);
+ }
+ }
+
+ private onChunk(key: string, chunk: WireChunk) {
+ if (chunk.type === "data-provider-failure")
+ this.providerFailure = chunk.data;
+ if (isEngineSwitchPart(chunk)) this.bookkeeping(key).sawModeChange = true;
+ if (chunk.type === "error") {
+ const failure = this.providerFailure;
+ this.providerFailure = null;
+ this.handlers.onError?.(new Error(str(chunk.errorText)), failure);
+ }
+ }
+
+ private onEnd(conn: Connection, end: ConnectionEnd) {
+ if (conn === this.rotating) {
+ this.rotating = null;
+ return;
+ }
+ if (conn !== this.slot || this.disposed) return;
+ this.slot = null;
+ this.emit();
+ if (conn.closedByClient) return;
+ const seg = conn.turnId ? this.turnFor(conn.turnId) : null;
+ if (seg && (seg.ended || seg.stopped || seg.frozen)) return;
+ if (end.kind === "refused" && conn.kind === "post") {
+ this.refusedSend(end);
+ return;
+ }
+ if (!seg) {
+ this.findLostTurn(conn, end);
+ return;
+ }
+ if (end.kind === "refused") {
+ if (end.status === 409) void this.resync(seg.key, checkpointOf(end.body));
+ else if (end.status === 410 || end.status === 204)
+ void this.expire(seg.key);
+ else this.retry(conn);
+ return;
+ }
+ // A clean close after entries but without the turn's finish is an expected
+ // cut (a proxy restart, the route's own error frame): resume at once.
+ if (end.kind === "closed" && conn.entries > 0) this.resume(seg);
+ else if (end.kind === "closed") void this.closedEmpty(seg.key, conn);
+ else this.retry(conn);
+ }
+
+ // A read that yields no entry may be of a turn the server stopped running
+ // without storing its finish; resuming it again would loop.
+ private async closedEmpty(key: string, lost: Lost) {
+ const view = await this.recover(() => this.fetchView());
+ const seg = this.segmentByKey(key);
+ if (seg?.kind !== "turn" || seg.ended || seg.stopped || seg.frozen) return;
+ if (view && view.active_stream?.turn_id !== seg.log.turnId)
+ void this.expire(key, view);
+ else this.retry(lost);
+ }
+
+ /**
+ * The disconnect classification (design §1.7). Hidden, offline and
+ * rotation-age cuts resume silently; only a run of failures while the tab
+ * is visible and online reaches the one alarming toast.
+ */
+ private retry(lost: Lost) {
+ const running = this.runningTurn();
+ if (!running && lost.turnId !== null) return;
+ const offline =
+ typeof navigator !== "undefined" && navigator.onLine === false;
+ if (
+ lost.turnId === null &&
+ (offline || document.visibilityState === "hidden")
+ ) {
+ this.unresolvedPost = { lost, end: { kind: "closed" } };
+ }
+ if (document.visibilityState === "hidden") return;
+ if (offline) {
+ this.notice = "offline";
+ this.emitNow();
+ return;
+ }
+ if (Date.now() - lost.openedAt >= ROTATE_AFTER_MS && running) {
+ this.resume(running);
+ return;
+ }
+ this.failures += 1;
+ if (this.failures >= INDICATOR_AFTER_FAILURES) this.notice = "reconnecting";
+ if (this.failures >= BACKOFF_MS.length && !this.anomalyShown) {
+ this.anomalyShown = true;
+ this.deps.toast(ANOMALY_TOAST);
+ }
+ const delay = BACKOFF_MS[this.failures - 1] ?? ANOMALY_RETRY_MS;
+ this.clearRetry();
+ this.retryTimer = setTimeout(() => {
+ this.retryTimer = null;
+ if (this.runningTurn()) this.ensureConnected();
+ else void this.recoverUnknownTurn(lost, { kind: "closed" });
+ }, delay);
+ this.emitNow();
+ }
+
+ private refusedSend(end: Extract<ConnectionEnd, { kind: "refused" }>) {
+ const text =
+ typeof end.body === "string" ? end.body : JSON.stringify(end.body);
+ this.error = new Error(text || `Request failed with status ${end.status}`);
+ this.emitNow();
+ this.handlers.onError?.(this.error, null);
+ }
+
+ // A send whose stream ended before naming its turn: the session view says
+ // whether the turn runs, once the tab can ask.
+ private findLostTurn(lost: Lost, end: ConnectionEnd) {
+ const offline =
+ typeof navigator !== "undefined" && navigator.onLine === false;
+ if (document.visibilityState === "hidden" || offline)
+ this.unresolvedPost = { lost, end };
+ else void this.recoverUnknownTurn(lost, end);
+ }
+
+ // The turn registers a beat after the POST answers, so the view is asked a
+ // few times before the send is reported as failed.
+ private async recoverUnknownTurn(lost: Lost, end: ConnectionEnd) {
+ for (let i = 0; i < CONTINUATION_PROBES; i++) {
+ const view = await this.fetchView();
+ if (!view) {
+ this.retry(lost);
+ return;
+ }
+ const attaching = this.wouldAttach(view);
+ this.observe(view);
+ if (attaching) {
+ this.resetFailures();
+ return;
+ }
+ if (this.disposed || this.stopped) return;
+ await sleep(FINISH_PROBE_MS);
+ }
+ if (end.kind === "failed" || lost.syntheticError) {
+ this.error =
+ end.kind === "failed" && end.error instanceof Error
+ ? end.error
+ : new Error(lost.syntheticError ?? "The connection closed early.");
+ this.emitNow();
+ }
+ }
+
+ // ── The turn's lifecycle ───────────────────────────────────────────────
+
+ private attach(
+ active: NonNullable<SessionView["active_stream"]>,
+ view: SessionView,
+ ) {
+ const rows = persistedRows(view.messages);
+ const checkpoint = active.checkpoint ?? null;
+ const start = checkpoint
+ ? checkpoint.sequence
+ : (this.lastViewMaxSequence ?? -1) + 1;
+ // Rows another tab (or the server) persisted between the tail and this turn.
+ const gap =
+ this.ownedFrom === null ? null : gapSegment(this.segments, start, rows);
+ if (gap) this.segments.push(gap);
+ this.claimTail(start);
+ const seg = newTurnSegment(
+ active.turn_id,
+ seedTurnLog({ turnId: active.turn_id, rows, checkpoint }),
+ start,
+ );
+ this.segments.push(seg);
+ this.resume(seg);
+ }
+
+ private endTurn(key: string) {
+ this.updateTurn(key, (seg) => ({ ...seg, ended: true }));
+ this.resetFailures();
+ this.emitNow();
+ this.handlers.onTurnEnd?.();
+ const seg = this.segmentByKey(key);
+ if (seg?.kind !== "turn") return;
+ const continuation =
+ this.bookkeeping(key).sawModeChange || this.followPending;
+ this.followPending = false;
+ void this.probe(
+ seg.log.turnId,
+ continuation ? CONTINUATION_PROBES : SETTLE_PROBES,
+ continuation,
+ );
+ }
+
+ /**
+ * Fetch the session view until it no longer runs `turnId`: the end-of-turn
+ * reconcile, and the attach to a continuation it starts.
+ */
+ private async probe(
+ turnId: string | null,
+ attempts: number,
+ awaitContinuation: boolean,
+ ) {
+ for (let i = 0; i < attempts; i++) {
+ await sleep(FINISH_PROBE_MS);
+ if (this.disposed || this.stopped) return;
+ const view = await this.fetchView();
+ if (!view) continue;
+ this.observe(view);
+ const active = view.active_stream?.turn_id ?? null;
+ if (active && active !== turnId) return;
+ if (!active && !awaitContinuation) return;
+ }
+ }
+
+ /**
+ * Rebuild the turn from the DB rows at a checkpoint and tail the stream
+ * from there: a trimmed stream, a protocol error, a digest mismatch. A
+ * second one on the same turn freezes it instead, so a real bug cannot
+ * become a reconnect storm.
+ */
+ private async resync(key: string, checkpoint: TurnCheckpoint | null) {
+ const book = this.bookkeeping(key);
+ if (book.resyncs >= MAX_RESYNCS_PER_TURN) {
+ void this.freeze(key);
+ return;
+ }
+ book.resyncs += 1;
+ this.abortSlot();
+ const view = await this.recover(() => this.fetchView());
+ const seg = this.segmentByKey(key);
+ if (seg?.kind !== "turn" || !seg.log.turnId) return;
+ if (!view) {
+ book.resyncs -= 1;
+ this.retry({
+ turnId: seg.log.turnId,
+ openedAt: Date.now(),
+ syntheticError: null,
+ });
+ return;
+ }
+ const active = view.active_stream;
+ const at =
+ checkpoint ??
+ (active?.turn_id === seg.log.turnId ? active.checkpoint : null) ??
+ lastCheckpoint(seg.log);
+ const seeded = seedTurnLog({
+ turnId: seg.log.turnId,
+ rows: persistedRows(view.messages),
+ checkpoint: at,
+ });
+ book.verified = 0;
+ book.reportedErrors = 0;
+ this.updateTurn(key, (s) => ({
+ ...s,
+ log: { ...seeded, rows: keepIdentity(s.log.rows, seeded.rows) },
+ }));
+ const next = this.segmentByKey(key);
+ if (next?.kind === "turn") this.resume(next);
+ }
+
+ // The stream is gone: the DB view is the whole truth, and a turn that
+ // stopped mid-part renders as interrupted.
+ private async expire(key: string, known: SessionView | null = null) {
+ const view = known ?? (await this.recover(() => this.fetchView()));
+ const seg = this.segmentByKey(key);
+ if (seg?.kind !== "turn") return;
+ if (!view) {
+ this.retry({
+ turnId: seg.log.turnId,
+ openedAt: Date.now(),
+ syntheticError: null,
+ });
+ return;
+ }
+ const persisted = turnRows(
+ this.segments,
+ this.ownedFrom,
+ seg,
+ persistedRows(view.messages),
+ );
+ const interrupted = hasOpenParts(seg.log);
+ this.updateTurn(key, (s) => {
+ const rows = persisted
+ ? mergeRows(s.log.rows, persisted.rows)
+ : s.log.rows;
+ return {
+ ...s,
+ ended: true,
+ reconciled: persisted !== null,
+ log: {
+ ...closeBlocks(s.log),
+ status: "finished",
+ rows: interrupted
+ ? withMarker(
+ rows,
+ `interrupted:${s.log.turnId}`,
+ INTERRUPTED_MARKER,
+ )
+ : rows,
+ },
+ };
+ });
+ this.resetFailures();
+ this.emitNow();
+ this.handlers.onTurnEnd?.();
+ this.observe(view);
+ }
+
+ // Show the persisted rows with a note, and poll until the turn is over.
+ private async freeze(key: string) {
+ this.abortSlot();
+ this.clearRetry();
+ const view = await this.fetchView();
+ this.updateTurn(key, (seg) => {
+ const persisted = view
+ ? turnRows(
+ this.segments,
+ this.ownedFrom,
+ seg,
+ persistedRows(view.messages),
+ )
+ : null;
+ return {
+ ...seg,
+ frozen: true,
+ log: {
+ ...closeBlocks(seg.log),
+ rows: withMarker(
+ persisted?.rows ?? seg.log.rows,
+ `frozen:${seg.log.turnId}`,
+ FROZEN_NOTE,
+ ),
+ },
+ };
+ });
+ this.deps.report("frozen", { turnId: key });
+ this.notice = null;
+ this.emitNow();
+ if (this.frozenTimer) clearInterval(this.frozenTimer);
+ this.frozenTimer = setInterval(async () => {
+ const next = await this.fetchView();
+ if (next) this.observe(next);
+ const seg = this.segmentByKey(key);
+ if (seg?.kind === "turn" && seg.reconciled && this.frozenTimer) {
+ clearInterval(this.frozenTimer);
+ this.frozenTimer = null;
+ }
+ }, FROZEN_POLL_MS);
+ }
+
+ private reconcile(seg: TurnSegment, view: SessionView) {
+ const rows = persistedRows(view.messages);
+ const persisted = turnRows(this.segments, this.ownedFrom, seg, rows);
+ if (!persisted) return;
+ // The session GET returns a window; a turn starting before it waits.
+ const windowStart = rows[0]?.sequence ?? Infinity;
+ if (view.has_more_messages !== false && windowStart > persisted.start)
+ return;
+ const drift = diffRows(seg.log.rows, persisted.rows);
+ if (drift.length > 0 && !seg.stopped && !seg.frozen) {
+ this.deps.report("finish", {
+ turnId: seg.log.turnId,
+ cursor: seg.log.cursor,
+ diffs: drift,
+ });
+ }
+ this.updateTurn(seg.key, (s) => reconcileTurn(s, persisted));
+ const index = this.segments.findIndex((s) => s.key === seg.key);
+ const prompt = this.segments[index - 1];
+ const row = rows.find((r) => r.sequence === persisted.start - 1);
+ if (
+ prompt?.kind === "user" &&
+ prompt.sequence === null &&
+ row?.role === "user"
+ ) {
+ this.segments[index - 1] = withPromptRow(prompt, row);
+ }
+ }
+
+ // With nothing running, a prompt whose turn never reached this client (a
+ // stop before its first entry, a lost send) takes its row, and rows after
+ // the tail's end are shown as persisted.
+ private settleTail(view: SessionView) {
+ const rows = persistedRows(view.messages);
+ const last = this.segments[this.segments.length - 1];
+ if (
+ last?.kind === "user" &&
+ last.origin === "sent" &&
+ last.sequence === null
+ ) {
+ const floor = promptFloor(
+ this.segments,
+ this.segments.length - 1,
+ this.ownedFrom,
+ );
+ const row = locatePrompt(last, rows, floor);
+ if (!row) return;
+ this.segments[this.segments.length - 1] = withPromptRow(last, row);
+ }
+ const gap =
+ this.ownedFrom === null
+ ? null
+ : gapSegment(this.segments, Infinity, rows);
+ if (gap) this.segments.push(gap);
+ }
+
+ private claimTail(from: number) {
+ if (this.ownedFrom === null || from < this.ownedFrom) this.ownedFrom = from;
+ }
+
+ private nextSequence() {
+ return this.ownedFrom !== null && this.segments.length > 0
+ ? (tailEndSequence(this.segments) ?? this.ownedFrom) + 1
+ : (this.lastViewMaxSequence ?? -1) + 1;
+ }
+
+ private checkProtocol(key: string) {
+ const seg = this.segmentByKey(key);
+ if (seg?.kind !== "turn") return;
+ const book = this.bookkeeping(key);
+ const fresh = seg.log.protocolErrors.slice(book.reportedErrors);
+ book.reportedErrors = seg.log.protocolErrors.length;
+ for (const error of fresh) {
+ this.deps.report("protocol_error", {
+ turnId: seg.log.turnId,
+ cursor: seg.log.cursor,
+ ...error,
+ });
+ }
+ if (fresh.some((e) => RESYNC_REASONS.has(e.reason))) {
+ void this.resync(key, null);
+ }
+ }
+
+ private async verifyCheckpoints(key: string) {
+ const book = this.bookkeeping(key);
+ let seg = this.segmentByKey(key);
+ while (seg?.kind === "turn" && book.verified < seg.log.checkpoints.length) {
+ const checkpoint = seg.log.checkpoints[book.verified++];
+ const digest = await sha256Hex(checkpoint.canonical);
+ seg = this.segmentByKey(key);
+ if (digest === null || digest === checkpoint.digest) continue;
+ if (seg?.kind !== "turn") return;
+ this.deps.report("checkpoint", {
+ turnId: seg.log.turnId,
+ entryId: checkpoint.entryId,
+ rows: checkpoint.rows,
+ serverDigest: checkpoint.digest,
+ clientDigest: digest,
+ });
+ void this.resync(key, {
+ entry_id: checkpoint.entryId,
+ rows: checkpoint.rows,
+ sequence: checkpoint.sequence,
+ });
+ return;
+ }
+ }
+
+ // ── Plumbing ───────────────────────────────────────────────────────────
+
+ private onVisible = () => {
+ if (document.visibilityState === "visible") this.wake();
+ };
+
+ private onOnline = () => {
+ if (this.notice === "offline") this.notice = null;
+ this.resetFailures();
+ this.wake();
+ this.emitNow();
+ };
+
+ private onOffline = () => {
+ if (this.runningTurn() && !this.isLive()) {
+ this.notice = "offline";
+ this.emitNow();
+ }
+ };
+
+ private wake() {
+ const unresolved = this.unresolvedPost;
+ this.unresolvedPost = null;
+ if (unresolved && !this.runningTurn())
+ void this.recoverUnknownTurn(unresolved.lost, unresolved.end);
+ else this.ensureConnected();
+ }
+
+ private ensureTicking() {
+ if (this.tickTimer) return;
+ this.tickTimer = setInterval(() => this.tick(), TICK_MS);
+ }
+
+ // Liveness and rotation; a hidden tab's timers are not to be trusted.
+ private tick() {
+ const slot = this.slot;
+ if (!slot && !this.runningTurn()) {
+ if (this.tickTimer) clearInterval(this.tickTimer);
+ this.tickTimer = null;
+ return;
+ }
+ if (!slot || document.visibilityState === "hidden") return;
+ const now = Date.now();
+ if (now - slot.lastFrameAt >= LIVENESS_MS) {
+ slot.closedByClient = true;
+ slot.controller.abort();
+ this.slot = null;
+ if (slot.turnId === null) this.findLostTurn(slot, { kind: "closed" });
+ else this.retry(slot);
+ return;
+ }
+ if (!this.rotating && now - slot.openedAt >= ROTATE_AFTER_MS) this.rotate();
+ }
+
+ // Rebuilding from the DB view: no other trigger reconnects meanwhile, and
+ // a rebuild past 2 s shows an inline "catching up".
+ private async recover<T>(work: () => Promise<T>) {
+ this.recovering = true;
+ const timer = setTimeout(() => {
+ this.notice = "catching-up";
+ this.emitNow();
+ }, CATCHING_UP_AFTER_MS);
+ try {
+ return await work();
+ } finally {
+ this.recovering = false;
+ clearTimeout(timer);
+ if (this.notice === "catching-up") this.notice = null;
+ this.emit();
+ }
+ }
+
+ private async fetchView() {
+ try {
+ return await (this.boundFetchSession ?? this.deps.fetchSession)();
+ } catch {
+ return null;
+ }
+ }
+
+ private runningTurn(): TurnSegment | null {
+ for (let i = this.segments.length - 1; i >= 0; i--) {
+ const seg = this.segments[i];
+ if (seg.kind !== "turn") continue;
+ return seg.ended || seg.stopped ? null : seg;
+ }
+ return null;
+ }
+
+ private isPostPending() {
+ return this.slot?.kind === "post" && this.slot.turnId === null;
+ }
+
+ private isLive() {
+ return (
+ !!this.slot &&
+ this.slot.frames > 0 &&
+ Date.now() - this.slot.lastFrameAt < LIVENESS_MS
+ );
+ }
+
+ private turnFor(turnId: string): TurnSegment | null {
+ const seg = this.segments.find(
+ (s): s is TurnSegment => s.kind === "turn" && s.log.turnId === turnId,
+ );
+ return seg ?? null;
+ }
+
+ private segmentByKey(key: string) {
+ return this.segments.find((s) => s.key === key) ?? null;
+ }
+
+ private updateTurn(key: string, patch: (seg: TurnSegment) => TurnSegment) {
+ const index = this.segments.findIndex((s) => s.key === key);
+ const seg = this.segments[index];
+ if (seg?.kind === "turn") this.segments[index] = patch(seg);
+ }
+
+ private bookkeeping(key: string) {
+ let book = this.turns.get(key);
+ if (!book) {
+ book = {
+ verified: 0,
+ reportedErrors: 0,
+ resyncs: 0,
+ sawModeChange: false,
+ };
+ this.turns.set(key, book);
+ }
+ return book;
+ }
+
+ private resetFailures() {
+ this.failures = 0;
+ this.anomalyShown = false;
+ if (this.notice === "reconnecting" || this.notice === "offline") {
+ this.notice = null;
+ }
+ }
+
+ private abortSlot() {
+ const slot = this.slot;
+ this.slot = null;
+ if (!slot) return;
+ slot.closedByClient = true;
+ slot.controller.abort();
+ }
+
+ private abortConnections() {
+ this.abortSlot();
+ const rotating = this.rotating;
+ this.rotating = null;
+ if (rotating) {
+ rotating.closedByClient = true;
+ rotating.controller.abort();
+ }
+ }
+
+ private clearRetry() {
+ if (this.retryTimer) clearTimeout(this.retryTimer);
+ this.retryTimer = null;
+ }
+
+ private streamUrl() {
+ return `${this.deps.baseUrl()}/api/chat/sessions/${this.sessionId}/stream`;
+ }
+
+ private resumeUrl(turnId: string, cursor: string | null) {
+ const params = new URLSearchParams({
+ turn: turnId,
+ after: cursor ?? "0-0",
+ });
+ return `${this.streamUrl()}?${params}`;
+ }
+
+ private emit() {
+ if (this.emitTimer) return;
+ this.emitTimer = setTimeout(() => {
+ this.emitTimer = null;
+ this.emitNow();
+ }, EMIT_THROTTLE_MS);
+ }
+
+ private emitNow() {
+ if (this.emitTimer) clearTimeout(this.emitTimer);
+ this.emitTimer = null;
+ this.snapshot = this.buildSnapshot();
+ for (const listener of this.listeners) listener();
+ }
+
+ private buildSnapshot(): RuntimeSnapshot {
+ return {
+ segments: this.segments.map((seg) => this.reveal.display(seg)),
+ ownedFrom: this.ownedFrom,
+ phase: this.phase(),
+ notice: this.notice,
+ error: this.error,
+ stopped: this.stopped,
+ };
+ }
+
+ private phase(): RuntimePhase {
+ if (this.isPostPending()) return "connecting";
+ const running = this.runningTurn();
+ if (running) return this.isLive() ? "live" : "resuming";
+ if (this.error) return "failed";
+ const last = this.segments.findLast(
+ (s): s is TurnSegment => s.kind === "turn",
+ );
+ if (!last || last.stopped) return "idle";
+ return last.log.status === "failed" ? "failed" : "finished";
+ }
+}
+
+const runtimes = new Map<string, TurnRuntime>();
+// A runtime holds its turns' rows; idle ones beyond this are dropped.
+const MAX_RUNTIMES = 5;
+
+export function getTurnRuntime(
+ sessionId: string,
+ deps: Partial<RuntimeDeps> = {},
+) {
+ const existing = runtimes.get(sessionId);
+ if (existing) {
+ runtimes.delete(sessionId);
+ runtimes.set(sessionId, existing);
+ return existing;
+ }
+ const runtime = new TurnRuntime(sessionId, {
+ ...defaultDeps(sessionId),
+ ...deps,
+ });
+ runtimes.set(sessionId, runtime);
+ for (const [id, other] of runtimes) {
+ if (runtimes.size <= MAX_RUNTIMES) break;
+ if (id !== sessionId && other.isIdle()) {
+ other.dispose();
+ runtimes.delete(id);
+ }
+ }
+ return runtime;
+}
+
+export function resetTurnRuntimes() {
+ for (const runtime of runtimes.values()) runtime.dispose();
+ runtimes.clear();
+}
+
+function defaultDeps(sessionId: string): RuntimeDeps {
+ return {
+ baseUrl: () => environment.getAGPTServerBaseUrl(),
+ headers: getCopilotAuthHeaders,
+ // The token devtool reads the `: usage` comments off the same response.
+ fetch: isTokenDevtoolEnabled()
+ ? createUsageCapturingFetch(sessionId)
+ : (input, init) => fetch(input, init),
+ fetchSession: async () => {
+ const response = await getV2GetSession(sessionId);
+ return response.status === 200 ? (response.data as SessionView) : null;
+ },
+ toast: (options) => toast(options),
+ report: (kind, extra) =>
+ Sentry.captureMessage(`copilot stream drift: ${kind}`, {
+ level: "warning",
+ tags: { stream_drift: kind },
+ extra: { sessionId, ...extra },
+ }),
+ };
+}
+
+function userMessage(id: string, input: SendInput): UIMessage {
+ const parts =
+ "parts" in input
+ ? input.parts
+ : [
+ ...(input.files ?? []),
+ ...(input.text
+ ? [
+ {
+ type: "text" as const,
+ text: input.text,
+ state: "done" as const,
+ },
+ ]
+ : []),
+ ];
+ return {
+ id,
+ role: "user",
+ parts,
+ ...(input.metadata ? { metadata: input.metadata } : {}),
+ };
+}
+
+function str(value: unknown): string {
+ return typeof value === "string" ? value : "";
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnShadow.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnShadow.ts
index 166836caa3..4566c054ff 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnShadow.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnShadow.ts
@@ -297,7 +297,7 @@ function reportDrift(
}
// `crypto.subtle` exists only in secure contexts; a plain-HTTP LAN origin skips the check.
-async function sha256Hex(text: string): Promise<string | null> {
+export async function sha256Hex(text: string): Promise<string | null> {
const subtle = globalThis.crypto?.subtle;
if (!subtle) return null;
const hash = await subtle.digest("SHA-256", new TextEncoder().encode(text));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnTail.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnTail.ts
new file mode 100644
index 0000000000..063549033f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnTail.ts
@@ -0,0 +1,409 @@
+import type { UIMessage } from "ai";
+
+import { CANCELLED_MARKER } from "../useCopilotStop";
+import {
+ COPILOT_RETRYABLE_ERROR_PREFIX,
+ isMarker,
+ logRowFromPersisted,
+ type LogRow,
+ type PersistedRow,
+ type TurnLog,
+} from "./turnLog";
+import { diffRows } from "./turnShadow";
+
+/**
+ * The runtime's tail: the prompts, turns and persisted rows it renders after
+ * the session's history, and which of the session's persisted rows belong to
+ * each. Everything here is pure; the runtime holds the state.
+ */
+
+export interface UserSegment {
+ kind: "user";
+ key: string;
+ message: UIMessage;
+ sequence: number | null;
+ /** `sent` is the turn's own prompt; `chip` a promoted follow-up. */
+ origin: "sent" | "chip";
+ rawId: string | null;
+ createdAt: string | null;
+}
+
+export interface TurnSegment {
+ kind: "turn";
+ key: string;
+ log: TurnLog;
+ ended: boolean;
+ stopped: boolean;
+ /** Two drift events on one turn: the persisted view is shown instead. */
+ frozen: boolean;
+ reconciled: boolean;
+ /** Fields that never stream, adopted at the reconcile. */
+ durationMs: number | null;
+ createdAt: string | null;
+ /** When each persisted row was written, by row key. */
+ rowCreatedAt: Readonly<Record<string, string>>;
+ /** Where an attached turn's rows begin before it names a checkpoint. */
+ startHint: number | null;
+}
+
+/** Persisted rows the tail holds but no turn of this mount produced. */
+export interface RowsSegment {
+ kind: "rows";
+ key: string;
+ rows: readonly PersistedRow[];
+}
+
+export type Segment = UserSegment | TurnSegment | RowsSegment;
+
+export interface TurnCheckpoint {
+ entry_id: string;
+ rows: number;
+ sequence: number;
+}
+
+export const INTERRUPTED_MARKER = `${COPILOT_RETRYABLE_ERROR_PREFIX} Response was interrupted. Resend to try again.`;
+export const FROZEN_NOTE =
+ "[__COPILOT_SYSTEM_e3b0__] This reply is shown as saved; it will update when the turn ends.";
+
+export function newTurnSegment(
+ turnId: string,
+ log: TurnLog,
+ startHint: number | null = null,
+): TurnSegment {
+ return {
+ kind: "turn",
+ key: `turn:${turnId}`,
+ log,
+ ended: false,
+ stopped: false,
+ frozen: false,
+ reconciled: false,
+ durationMs: null,
+ createdAt: null,
+ rowCreatedAt: {},
+ startHint,
+ };
+}
+
+export function userSegment(
+ message: UIMessage,
+ origin: UserSegment["origin"],
+): UserSegment {
+ return {
+ kind: "user",
+ key: message.id,
+ message,
+ sequence: null,
+ origin,
+ rawId: null,
+ createdAt: null,
+ };
+}
+
+/** Where a turn's rows start: its first checkpoint, its seed, or the row after its prompt. */
+export function turnStart(
+ segments: readonly Segment[],
+ ownedFrom: number | null,
+ seg: TurnSegment,
+ rows: readonly PersistedRow[],
+) {
+ const known = segmentStart(seg);
+ if (known !== null) return known;
+ const index = segments.indexOf(seg);
+ const before = segments[index - 1];
+ if (before?.kind === "user") {
+ const prompt =
+ before.sequence ??
+ locatePrompt(before, rows, promptFloor(segments, index - 1, ownedFrom))
+ ?.sequence;
+ return typeof prompt === "number" ? prompt + 1 : null;
+ }
+ return index === 0 ? ownedFrom : null;
+}
+
+/**
+ * A turn's persisted rows: from its start up to the next segment, whose
+ * prompt is found by its text while it has no sequence of its own yet (a
+ * send right after a stop).
+ */
+export function turnRows(
+ segments: readonly Segment[],
+ ownedFrom: number | null,
+ seg: TurnSegment,
+ rows: readonly PersistedRow[],
+) {
+ const start = turnStart(segments, ownedFrom, seg, rows);
+ if (start === null) return null;
+ const end =
+ segments
+ .slice(segments.indexOf(seg) + 1)
+ .map((later) => {
+ const known = segmentStart(later);
+ if (known !== null || later.kind !== "user" || later.origin !== "sent")
+ return known;
+ return locatePrompt(later, rows, start + 1)?.sequence ?? null;
+ })
+ .find((n): n is number => typeof n === "number") ?? Infinity;
+ const raw = rows.filter(
+ (r) =>
+ typeof r.sequence === "number" && r.sequence >= start && r.sequence < end,
+ );
+ return { start, raw, rows: raw.map(logRowFromPersisted) };
+}
+
+/**
+ * The end-of-turn reconcile, row by row: an equal row adopts its sequence and
+ * keeps its object, a differing one takes the persisted content under its own
+ * key, and a streamed row the DB lacks stays on screen.
+ */
+export function reconcileTurn(
+ seg: TurnSegment,
+ persisted: { raw: readonly PersistedRow[]; rows: readonly LogRow[] },
+): TurnSegment {
+ const rows = seg.frozen
+ ? [...persisted.rows]
+ : mergeRows(seg.log.rows, persisted.rows);
+ const rowCreatedAt: Record<string, string> = {};
+ rows.forEach((row, i) => {
+ const at = createdAtOf(persisted.raw[i]);
+ if (at) rowCreatedAt[row.key] = at;
+ });
+ const durations = persisted.raw
+ .map((r) => (r as { duration_ms?: unknown }).duration_ms)
+ .filter((d): d is number => typeof d === "number");
+ return {
+ ...seg,
+ reconciled: true,
+ ended: true,
+ log: { ...closeBlocks(seg.log), rows },
+ durationMs: durations.length ? Math.max(...durations) : seg.durationMs,
+ createdAt:
+ createdAtOf(persisted.raw[persisted.raw.length - 1]) ?? seg.createdAt,
+ rowCreatedAt,
+ };
+}
+
+/** A local prompt takes its persisted row's place: sequence, id and timestamp. */
+export function withPromptRow(
+ seg: UserSegment,
+ row: PersistedRow,
+): UserSegment {
+ const rawId = (row as { id?: unknown }).id;
+ return {
+ ...seg,
+ sequence: row.sequence ?? null,
+ rawId: typeof rawId === "string" ? rawId : null,
+ createdAt: createdAtOf(row),
+ };
+}
+
+/** Rows persisted after the tail's end and before `start` that no segment holds. */
+export function gapSegment(
+ segments: readonly Segment[],
+ start: number,
+ rows: readonly PersistedRow[],
+): RowsSegment | null {
+ const tailEnd = tailEndSequence(segments);
+ if (tailEnd === null) return null;
+ const gap = rows.filter(
+ (r) => (r.sequence ?? -1) > tailEnd && (r.sequence ?? -1) < start,
+ );
+ return gap.length
+ ? { kind: "rows", key: `rows:${gap[0].sequence}`, rows: gap }
+ : null;
+}
+
+export function tailEndSequence(segments: readonly Segment[]) {
+ const last = segments[segments.length - 1];
+ if (!last) return null;
+ if (last.kind === "rows")
+ return last.rows[last.rows.length - 1]?.sequence ?? null;
+ if (last.kind === "user") return last.sequence;
+ return last.log.rows[last.log.rows.length - 1]?.sequence ?? null;
+}
+
+/** Rows equal to the ones on screen keep their object and key; others take the persisted content under the on-screen key. */
+export function mergeRows(
+ live: readonly LogRow[],
+ persisted: readonly LogRow[],
+): LogRow[] {
+ const differing = new Set(diffRows(live, persisted).map((d) => d.index));
+ // A streamed row past the DB's end is one it lacks only if every row before
+ // it matched; after a mismatch it is a persisted row at another index.
+ const aligned = [...differing].every((i) => i >= persisted.length);
+ const length = aligned ? live.length : 0;
+ const merged: LogRow[] = [];
+ for (let i = 0; i < Math.max(length, persisted.length); i++) {
+ const a = live[i];
+ const b = persisted[i];
+ if (!b) merged.push(a);
+ else if (!a) merged.push(b);
+ else if (differing.has(i)) merged.push({ ...b, key: a.key });
+ else merged.push(adoptPersisted(a, b));
+ }
+ return merged;
+}
+
+/** A resync's seed keeps the rows already on screen where they are equal. */
+export function keepIdentity(
+ live: readonly LogRow[],
+ seeded: readonly LogRow[],
+) {
+ const differing = new Set(
+ diffRows(live.slice(0, seeded.length), seeded).map((d) => d.index),
+ );
+ return seeded.map((row, i) => {
+ const current = live[i];
+ if (!current) return row;
+ return differing.has(i)
+ ? { ...row, key: current.key }
+ : adoptPersisted(current, row);
+ });
+}
+
+export function withStopMarker(log: TurnLog): TurnLog {
+ const last = log.rows[log.rows.length - 1];
+ const rows =
+ last && isMarker(last)
+ ? log.rows
+ : [...log.rows, markerRow(`stop:${log.turnId}`, CANCELLED_MARKER)];
+ return { ...closeBlocks(log), status: "finished", rows };
+}
+
+/** Rows that end in a marker row of their own, unless one is there already. */
+export function withMarker(
+ rows: readonly LogRow[],
+ key: string,
+ content: string,
+) {
+ const last = rows[rows.length - 1];
+ return last && isMarker(last)
+ ? [...rows]
+ : [...rows, markerRow(key, content)];
+}
+
+export function closeBlocks(log: TurnLog): TurnLog {
+ const open = Object.entries(log.blocks).filter(([, b]) => b.open);
+ if (open.length === 0) return log;
+ const blocks = { ...log.blocks };
+ for (const [id, block] of open) blocks[id] = { ...block, open: false };
+ return { ...log, blocks };
+}
+
+/** A block still writing or a tool call still waiting on its output. */
+export function hasOpenParts(log: TurnLog) {
+ return (
+ Object.values(log.blocks).some((b) => b.open) ||
+ Object.values(log.tools).some((t) => t.phase !== "output-available")
+ );
+}
+
+export function persistedRows(
+ messages: readonly unknown[] | null | undefined,
+): PersistedRow[] {
+ return (messages ?? [])
+ .map((row) => row as PersistedRow)
+ .filter((row) => typeof row.sequence === "number")
+ .sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
+}
+
+/**
+ * The prompt's row: the first user row in the tail whose text it carries
+ * (the backend appends an attached-files block after it).
+ */
+export function locatePrompt(
+ seg: UserSegment,
+ rows: readonly PersistedRow[],
+ from: number | null,
+) {
+ const text = seg.message.parts
+ .map((p) => (p.type === "text" ? p.text : ""))
+ .join("");
+ const row = rows.find(
+ (r) =>
+ r.role === "user" &&
+ (r.sequence ?? -1) >= (from ?? 0) &&
+ typeof r.content === "string" &&
+ r.content.startsWith(text),
+ );
+ return row ?? null;
+}
+
+/** A prompt's row comes after every row the segments before it already hold. */
+export function promptFloor(
+ segments: readonly Segment[],
+ index: number,
+ ownedFrom: number | null,
+) {
+ const placed = segments.slice(0, index).flatMap((seg) => {
+ if (seg.kind === "user") return [seg.sequence];
+ return (seg.kind === "rows" ? seg.rows : seg.log.rows).map(
+ (r) => r.sequence,
+ );
+ });
+ return Math.max(
+ ownedFrom ?? 0,
+ ...placed
+ .filter((s): s is number => typeof s === "number")
+ .map((s) => s + 1),
+ );
+}
+
+export function lastCheckpoint(log: TurnLog): TurnCheckpoint | null {
+ const last = log.checkpoints[log.checkpoints.length - 1];
+ return last
+ ? { entry_id: last.entryId, rows: last.rows, sequence: last.sequence }
+ : null;
+}
+
+/** The checkpoint a 409 names, as the route writes it. */
+export function checkpointOf(body: unknown): TurnCheckpoint | null {
+ const checkpoint = (body as { checkpoint?: unknown } | null)?.checkpoint;
+ if (!checkpoint || typeof checkpoint !== "object") return null;
+ const { entry_id, rows, sequence } = checkpoint as Record<string, unknown>;
+ return typeof entry_id === "string" &&
+ typeof rows === "number" &&
+ typeof sequence === "number"
+ ? { entry_id, rows, sequence }
+ : null;
+}
+
+function adoptPersisted(live: LogRow, persisted: LogRow): LogRow {
+ const sameMetadata =
+ JSON.stringify(live.metadata ?? null) ===
+ JSON.stringify(persisted.metadata ?? live.metadata ?? null);
+ if (live.sequence === persisted.sequence && sameMetadata) return live;
+ return {
+ ...live,
+ sequence: persisted.sequence,
+ metadata: persisted.metadata ?? live.metadata,
+ };
+}
+
+function markerRow(key: string, content: string): LogRow {
+ return {
+ key,
+ role: "assistant",
+ content,
+ toolCalls: [],
+ toolCallId: null,
+ sequence: null,
+ metadata: null,
+ };
+}
+
+function segmentStart(seg: Segment): number | null {
+ if (seg.kind === "user") return seg.sequence;
+ if (seg.kind === "rows") return seg.rows[0]?.sequence ?? null;
+ return (
+ seg.log.checkpoints[0]?.sequence ??
+ seg.log.rows[0]?.sequence ??
+ seg.startHint
+ );
+}
+
+function createdAtOf(row: PersistedRow | undefined): string | null {
+ const value = (row as { created_at?: unknown } | undefined)?.created_at;
+ if (typeof value === "string") return value;
+ return value instanceof Date ? value.toISOString() : null;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index 13ac13ff0c..4ca046c23a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -426,6 +426,8 @@ export function useChatSession({
return {
sessionId,
setSessionId,
+ /** The session GET as last fetched; null while a fetch is in flight. */
+ sessionView: freshSessionData,
sessionLlmAuthProvider,
sessionLlmCredentialId,
sessionExpertId,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
index 56d6ca4d2f..8167f533fc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -28,6 +28,7 @@ import {
} from "./expertKickoff";
import { useExpertKickoff } from "./useExpertKickoff";
import { useCopilotNotifications } from "./useCopilotNotifications";
+import { useCopilotRuntimeStream } from "./useCopilotRuntimeStream";
import { useCopilotStream } from "./useCopilotStream";
import { resolveExpertIdentity, useExpertMap } from "./useExpertMap";
import { useLoadMoreMessages } from "./useLoadMoreMessages";
@@ -67,7 +68,9 @@ function getLatestKickoffAttemptToken(messages: UIMessage[]) {
return null;
}
-export function useCopilotPage() {
+export function useCopilotPage({
+ isStreamRuntime = false,
+}: { isStreamRuntime?: boolean } = {}) {
const { user, isUserLoading, isLoggedIn } = useAuth();
const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);
const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);
@@ -128,6 +131,7 @@ export function useCopilotPage() {
const {
sessionId,
setSessionId,
+ sessionView,
sessionLlmAuthProvider,
sessionLlmCredentialId,
sessionExpertId,
@@ -174,10 +178,32 @@ export function useCopilotPage() {
const isExpertSendLocked =
isResolvingExpertIdentity || Boolean(expertIdentity?.isArchived);
+ const streamArgs = {
+ userId: user?.id ?? null,
+ sessionId,
+ sessionView,
+ hydratedMessages,
+ rawSessionMessages,
+ sessionAuthProvider: sessionLlmAuthProvider,
+ sessionCredentialId: sessionLlmCredentialId,
+ activeTurnStartMessageId,
+ hasActiveStream,
+ refetchSession,
+ // Sent whenever the picker can set it. The tier control is not behind
+ // CHAT_MODE_OPTION -- it renders from the server's connection offer --
+ // so gating the value on that flag silently ran the turn on the tier the
+ // user had not chosen. Entitlement is the server's call, not the flag's.
+ copilotModel: copilotLlmModel,
+ };
+ // The host keys its mount by the flag, so this never changes within one.
+ const useStream = isStreamRuntime
+ ? useCopilotRuntimeStream
+ : useCopilotStream;
+ const stream = useStream(streamArgs);
+ const runtimeStream = "appendLocalUserRows" in stream ? stream : null;
const {
followBackendTurn,
messages: currentMessages,
- setMessages,
sendMessage,
stop,
status,
@@ -192,39 +218,29 @@ export function useCopilotPage() {
dismissRateLimit,
providerLimit,
dismissProviderLimit,
- } = useCopilotStream({
- userId: user?.id ?? null,
- sessionId,
- hydratedMessages,
- rawSessionMessages,
- sessionAuthProvider: sessionLlmAuthProvider,
- sessionCredentialId: sessionLlmCredentialId,
- activeTurnStartMessageId,
- hasActiveStream,
- refetchSession,
- // Sent whenever the picker can set it. The tier control is not behind
- // CHAT_MODE_OPTION -- it renders from the server's connection offer --
- // so gating the value on that flag silently ran the turn on the tier the
- // user had not chosen. Entitlement is the server's call, not the flag's.
- copilotModel: copilotLlmModel,
- });
+ } = stream;
const kickoffAttemptToken = getLatestKickoffAttemptToken(currentMessages);
const { pagedMessages, pagedTurnStats, hasMore, isLoadingMore, loadMore } =
useLoadMoreMessages({
sessionId,
- initialOldestSequence: oldestSequence,
+ initialOldestSequence: runtimeStream
+ ? runtimeStream.oldestSequence
+ : oldestSequence,
initialHasMore: hasMoreMessages,
initialPageRawMessages: rawSessionMessages,
});
// Merge the older-pages and current-page stat maps; current-page (historical)
// wins on overlap since it was persisted more recently.
+ const currentTurnStats = runtimeStream
+ ? runtimeStream.turnStats
+ : historicalTurnStats;
const turnStats = useMemo(() => {
const merged = new Map(pagedTurnStats);
- historicalTurnStats?.forEach((v, k) => merged.set(k, v));
+ currentTurnStats?.forEach((v, k) => merged.set(k, v));
return merged;
- }, [pagedTurnStats, historicalTurnStats]);
+ }, [pagedTurnStats, currentTurnStats]);
// Ref that mirrors whether a stream turn is currently in-flight.
// Updated synchronously on every render so it always reflects the latest
@@ -322,18 +338,22 @@ export function useCopilotPage() {
() => stripReplayPrefix(cachedRawMessages),
[cachedRawMessages],
);
- const restoreStatusMessage = useMemo(
+ const latestStatusMessage = useMemo(
() =>
isRestoringActiveSession
? getLatestAssistantStatusMessage(messages)
: null,
[isRestoringActiveSession, messages],
);
+ // The runtime's restore state is a passive notice; it never trims the list.
+ const restoreStatusMessage = runtimeStream
+ ? runtimeStream.restoreStatusMessage
+ : latestStatusMessage;
const displayMessages = useMemo(() => {
- if (!isRestoringActiveSession) return messages;
+ if (!isRestoringActiveSession || runtimeStream) return messages;
if (hasAssistantTail(cachedMessages)) return cachedMessages;
return trimVisibleMessagesForActiveRestore(messages);
- }, [isRestoringActiveSession, messages, cachedMessages]);
+ }, [isRestoringActiveSession, runtimeStream, messages, cachedMessages]);
// Chip state machine (peek sync + auto-continue promotion + mid-turn poll)
// lives in a dedicated hook so this component is just glue.
@@ -341,7 +361,12 @@ export function useCopilotPage() {
sessionId,
status,
messages,
- setMessages,
+ ...("setMessages" in stream
+ ? { setMessages: stream.setMessages }
+ : {
+ appendLocalUserRows: stream.appendLocalUserRows,
+ drainedCount: stream.drainedCount,
+ }),
});
useCopilotNotifications(sessionId);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts
index 33c7194a47..f96dd6973f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts
@@ -24,11 +24,17 @@ interface Args {
sessionId: string | null;
status: ChatStatus;
messages: UIMessage[];
- setMessages: (
+ setMessages?: (
updater: UIMessage[] | ((prev: UIMessage[]) => UIMessage[]),
) => void;
+ /** The stream runtime's promotion; its turn's drained rows stand in for the bubbles. */
+ appendLocalUserRows?: (entries: readonly QueuedMessage[]) => void;
+ /** Drained follow-ups the runtime has rendered; replaces counting drain hints. */
+ drainedCount?: number;
}
+type Promote = (drained: QueuedMessage[], flavour?: PromotionFlavour) => void;
+
/**
* Owns the chip lifecycle: keep the local chip list in sync with Redis,
* promote chips to user-bubbles when the backend drains (auto-continue or
@@ -58,7 +64,14 @@ export function useCopilotPendingChips({
status,
messages,
setMessages,
+ appendLocalUserRows,
+ drainedCount,
}: Args) {
+ const promote: Promote = (drained, flavour) => {
+ if (appendLocalUserRows) appendLocalUserRows(drained);
+ else if (setMessages)
+ promoteChipsToTrailingBubbles(setMessages, drained, flavour);
+ };
const [queue, setQueue] = useState<QueuedMessage[]>([]);
// Stable string view for consumers that only need the texts. Memoised so
// downstream components don't re-render on identity churn alone.
@@ -73,23 +86,23 @@ export function useCopilotPendingChips({
queueRef.current = queue;
}, [queue]);
- usePeekOnBoundary({ sessionId, status, queueRef, setMessages, setQueue });
+ usePeekOnBoundary({ sessionId, status, queueRef, promote, setQueue });
useAutoContinuePromotion({
sessionId,
status,
messages,
queue,
- setMessages,
+ promote,
setQueue,
});
useMidTurnDrainPromotion({
sessionId,
status,
- messages,
+ drainHintCount: drainedCount ?? countPendingDrainedHints(messages),
queue,
- setMessages,
+ promote,
setQueue,
});
@@ -113,15 +126,17 @@ function usePeekOnBoundary({
sessionId,
status,
queueRef,
- setMessages,
+ promote,
setQueue,
}: {
sessionId: string | null;
status: ChatStatus;
queueRef: { current: QueuedMessage[] };
- setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void;
+ promote: Promote;
setQueue: (updater: QueueUpdater) => void;
}) {
+ const promoteRef = useRef(promote);
+ promoteRef.current = promote;
const prevSessionIdRef = useRef<string | null>(sessionId);
const prevStatusRef = useRef<ChatStatus>(status);
// Peeks overlap: Strict Mode mounts this effect twice, and two idle edges
@@ -192,9 +207,7 @@ function usePeekOnBoundary({
const drained = current.filter((entry) =>
inFlightIds.has(entry.id),
);
- if (drained.length > 0) {
- promoteChipsToTrailingBubbles(setMessages, drained);
- }
+ if (drained.length > 0) promoteRef.current(drained);
return current.filter((entry) => !inFlightIds.has(entry.id));
});
return;
@@ -258,16 +271,18 @@ function useAutoContinuePromotion({
status,
messages,
queue,
- setMessages,
+ promote,
setQueue,
}: {
sessionId: string | null;
status: ChatStatus;
messages: UIMessage[];
queue: QueuedMessage[];
- setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void;
+ promote: Promote;
setQueue: (updater: QueueUpdater) => void;
}) {
+ const promoteRef = useRef(promote);
+ promoteRef.current = promote;
const prevStatusRef = useRef(status);
// The opener is the first assistant id observed after a turn starts.
// Any LATER assistant id in the same chain is the auto-continue.
@@ -319,12 +334,11 @@ function useAutoContinuePromotion({
void pollBackendAndPromote(
sessionId,
queue,
- setMessages,
+ (drained) => promoteRef.current(drained, "auto-continue"),
setQueue,
isCurrentSession,
- "auto-continue",
);
- }, [messages, status, sessionId, queue, setMessages, setQueue]);
+ }, [messages, status, sessionId, queue, setQueue]);
}
type PromotionFlavour = Parameters<typeof makePromotedUserBubble>[1];
@@ -405,18 +419,20 @@ function isPromotedBubbleFor(
function useMidTurnDrainPromotion({
sessionId,
status,
- messages,
+ drainHintCount,
queue,
- setMessages,
+ promote,
setQueue,
}: {
sessionId: string | null;
status: ChatStatus;
- messages: UIMessage[];
+ drainHintCount: number;
queue: QueuedMessage[];
- setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void;
+ promote: Promote;
setQueue: (updater: QueueUpdater) => void;
}) {
+ const promoteRef = useRef(promote);
+ promoteRef.current = promote;
// Live ref tracks the latest sessionId so a poll captured at request
// time can detect a session switch on resolve. A cancellation flag
// would also fire on enqueue (this effect re-runs on every queue
@@ -432,7 +448,6 @@ function useMidTurnDrainPromotion({
// increasing — replays (AI SDK resume re-emits the parts) leave the
// count unchanged on a stable render, and the GET re-read keeps a
// replayed hint idempotent regardless.
- const drainHintCount = countPendingDrainedHints(messages);
// Baseline is tracked per session: on a session switch the old session's
// chips can still be in `queue` for the current commit, so a higher hint
// count in the new session must not promote stale chips into the new chat.
@@ -458,11 +473,11 @@ function useMidTurnDrainPromotion({
void pollBackendAndPromote(
sessionId,
queue,
- setMessages,
+ (drained) => promoteRef.current(drained),
setQueue,
isCurrentSession,
);
- }, [drainHintCount, sessionId, status, queue, setMessages, setQueue]);
+ }, [drainHintCount, sessionId, status, queue, setQueue]);
// Backstop: a slow poll that catches a dropped hint.
useEffect(() => {
@@ -477,13 +492,13 @@ function useMidTurnDrainPromotion({
void pollBackendAndPromote(
sessionId,
queue,
- setMessages,
+ (drained) => promoteRef.current(drained),
setQueue,
isCurrentSession,
);
}, MID_TURN_BACKSTOP_POLL_MS);
return () => clearInterval(interval);
- }, [sessionId, status, queue, setMessages, setQueue]);
+ }, [sessionId, status, queue, setQueue]);
}
// Count ``data-pending-drained`` hint parts the backend emits at each
@@ -502,10 +517,9 @@ function countPendingDrainedHints(messages: UIMessage[]): number {
async function pollBackendAndPromote(
sessionId: string,
snapshotQueue: QueuedMessage[],
- setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void,
+ promote: (drained: QueuedMessage[]) => void,
setQueue: (updater: QueueUpdater) => void,
isCurrentSession: () => boolean,
- flavour: PromotionFlavour = "midturn",
): Promise<void> {
let backendCount: number;
try {
@@ -542,7 +556,7 @@ async function pollBackendAndPromote(
// keeps the stream flowing, at the cost of showing a count-only follow-up
// above the work that preceded it until ``useHydrateOnStreamEnd`` snaps
// the list to the DB order at the end of the turn.
- promoteChipsToTrailingBubbles(setMessages, drained, flavour);
+ promote(drained);
// Drop only the drained entries by id; entries appended after the
// snapshot survive the in-flight poll race.
setQueue((current) => current.filter((entry) => !drainedIds.has(entry.id)));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts
new file mode 100644
index 0000000000..f17395d419
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts
@@ -0,0 +1,421 @@
+import { getGetV2GetCopilotUsageQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";
+import { useQueryClient } from "@tanstack/react-query";
+import type { UIMessage } from "ai";
+import {
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
+
+import { handleStreamError } from "./copilotStreamErrorHandlers";
+import { useCopilotStreamStore } from "./copilotStreamStore";
+import {
+ clearKickoffPending,
+ getKickoffAttemptTokenFromMetadata,
+ getKickoffExpertId,
+ getKickoffExpertIdFromMetadata,
+ withKickoffLock,
+} from "./expertKickoff";
+import {
+ convertChatSessionMessagesToUiMessages,
+ type TurnStatsMap,
+} from "./helpers/convertChatSessionToUiMessages";
+import {
+ latestProviderFailure,
+ parseProviderFailure,
+ providerFailureFingerprint,
+ type ProviderFailure,
+} from "./providerFailure";
+import { useCopilotUIStore, type CopilotLlmModel } from "./store";
+import {
+ createAssistantRunJoiner,
+ createTailRenderer,
+} from "./stream/renderTail";
+import {
+ getTurnRuntime,
+ type RuntimePhase,
+ type RuntimeSnapshot,
+ type SendInput,
+ type SessionView,
+ type TurnRuntime,
+} from "./stream/turnRuntime";
+import type { PersistedRow } from "./stream/turnLog";
+import { useCopilotStop } from "./useCopilotStop";
+
+const NOTICE_TEXT = {
+ "catching-up": "Catching up…",
+ reconnecting: "Reconnecting…",
+ offline: "Offline — waiting for the network…",
+} as const;
+
+const EMPTY_SNAPSHOT: RuntimeSnapshot = {
+ segments: [],
+ ownedFrom: null,
+ phase: "idle",
+ notice: null,
+ error: null,
+ stopped: false,
+};
+
+interface Args {
+ userId?: string | null;
+ sessionId: string | null;
+ /** The fresh session GET: its rows are the history above the runtime's tail. */
+ sessionView: SessionView | null;
+ hydratedMessages: UIMessage[] | undefined;
+ rawSessionMessages?: unknown[];
+ sessionAuthProvider?: string | null;
+ sessionCredentialId?: string | null;
+ refetchSession: () => Promise<{ data?: unknown }>;
+ copilotModel: CopilotLlmModel | undefined;
+}
+
+/**
+ * The chat stream on our own runtime: one connection per session, resumed
+ * at a cursor, rendered from the rows the backend persists. Returns the same
+ * shape as `useCopilotStream` so the page can take either.
+ */
+export function useCopilotRuntimeStream({
+ userId = null,
+ sessionId,
+ sessionView,
+ hydratedMessages,
+ rawSessionMessages,
+ sessionAuthProvider = null,
+ sessionCredentialId = null,
+ refetchSession,
+ copilotModel,
+}: Args) {
+ const queryClient = useQueryClient();
+ const setInitialPrompt = useCopilotUIStore((s) => s.setInitialPrompt);
+ const [rateLimitMessage, setRateLimitMessage] = useState<string | null>(null);
+ const [platformLimitFailure, setPlatformLimitFailure] =
+ useState<ProviderFailure | null>(null);
+ const [providerLimit, setProviderLimit] = useState<ProviderFailure | null>(
+ null,
+ );
+ const dismissedProviderFailureRef = useRef<{
+ sessionId: string;
+ fingerprint: string;
+ } | null>(null);
+
+ const runtime = useMemo(
+ () => (sessionId ? getTurnRuntime(sessionId) : null),
+ [sessionId],
+ );
+ const snapshot = useSyncExternalStore(
+ runtime?.subscribe ?? subscribeNothing,
+ runtime?.getSnapshot ?? emptySnapshot,
+ runtime?.getSnapshot ?? emptySnapshot,
+ );
+ const isUserStoppingRef = useRef(false);
+ isUserStoppingRef.current = snapshot.stopped;
+
+ useEffect(() => {
+ if (!runtime) return;
+ return runtime.bind(
+ {
+ onError: handleError,
+ onTurnEnd: () =>
+ queryClient.invalidateQueries({
+ queryKey: getGetV2GetCopilotUsageQueryKey(),
+ }),
+ },
+ async () => viewOf((await refetchSession()).data),
+ );
+ });
+
+ // Before paint, so a running turn's seeded rows replace its history rows
+ // in the same frame.
+ useLayoutEffect(() => {
+ if (runtime && sessionView) runtime.observe(sessionView);
+ }, [runtime, sessionView]);
+
+ const cut = snapshot.ownedFrom ?? prospectiveCut(runtime, sessionView);
+ const history = useSessionHistory(sessionId, sessionView, cut);
+ const renderTail = useMemo(
+ () => createTailRenderer(sessionId ?? ""),
+ [sessionId],
+ );
+ const tail = useMemo(() => renderTail(snapshot), [renderTail, snapshot]);
+ const joinAssistantRuns = useMemo(() => createAssistantRunJoiner(), []);
+ const messages = useMemo(
+ () =>
+ sessionId
+ ? joinAssistantRuns([...history.messages, ...tail.messages])
+ : [],
+ [sessionId, joinAssistantRuns, history.messages, tail.messages],
+ );
+ const turnStats = useMemo(
+ () => withLatestUser(messages, history.stats, tail.stats),
+ [messages, history.stats, tail.stats],
+ );
+
+ function handleError(error: Error, rawFailure: unknown) {
+ if (!sessionId) return;
+ const coord = useCopilotStreamStore.getState().getCoord(sessionId);
+ const kickoffExpertId = coord.lastSubmittedKickoffExpertId;
+ const kickoffAttemptToken = coord.lastSubmittedKickoffAttemptToken;
+ const clearRecovery = () =>
+ useCopilotStreamStore.getState().updateCoord(sessionId, {
+ lastSubmittedMessageText: null,
+ lastSubmittedKickoffExpertId: null,
+ lastSubmittedKickoffAttemptToken: null,
+ });
+ handleStreamError({
+ error,
+ providerFailure: parseProviderFailure(rawFailure),
+ onRateLimit: (message, limitFailure, origin) => {
+ // The backend refuses a turn over our cap before persisting its
+ // prompt: put the text back in an empty composer and drop the bubble.
+ if (coord.lastSubmittedMessageText) {
+ if (kickoffExpertId) clearRecovery();
+ else if (isComposerEmpty()) {
+ setInitialPrompt(coord.lastSubmittedMessageText);
+ clearRecovery();
+ }
+ runtime?.dropUnsentUserRow();
+ }
+ if (limitFailure && origin === "provider") {
+ dismissedProviderFailureRef.current = null;
+ setProviderLimit(limitFailure);
+ } else {
+ setPlatformLimitFailure(limitFailure ?? null);
+ setRateLimitMessage(limitFailure?.message || message);
+ }
+ },
+ onReconnect: () => runtime?.ensureConnected(),
+ isUserStoppingRef,
+ });
+ if (!kickoffExpertId) return;
+ if (userId && kickoffAttemptToken) {
+ void withKickoffLock(userId, kickoffExpertId, async () => {
+ clearKickoffPending(userId, kickoffExpertId, kickoffAttemptToken);
+ }).catch(() => undefined);
+ }
+ clearRecovery();
+ runtime?.dropUnsentUserRow();
+ }
+
+ async function sendMessage(input: SendInput) {
+ if (!runtime || !sessionId) return;
+ const metadata = input.metadata;
+ useCopilotStreamStore.getState().updateCoord(sessionId, {
+ lastSubmittedMessageText: "text" in input ? input.text : textOf(input),
+ lastSubmittedKickoffExpertId: getKickoffExpertIdFromMetadata(metadata),
+ lastSubmittedKickoffAttemptToken:
+ getKickoffAttemptTokenFromMetadata(metadata),
+ });
+ await runtime.send(input, copilotModel);
+ }
+
+ const stop = useCopilotStop({
+ sessionId,
+ stopStream: () => runtime?.stop(),
+ isUserStoppingRef,
+ setIsUserStopping: () => {},
+ });
+
+ // A failure the chat is still sitting on survives a reload: the backend
+ // persisted its envelope onto the marker row.
+ useEffect(() => {
+ setProviderLimit(null);
+ dismissedProviderFailureRef.current = null;
+ }, [sessionId]);
+
+ useEffect(() => {
+ if (!sessionId || !rawSessionMessages?.length) return;
+ const historical = latestProviderFailure(
+ rawSessionMessages,
+ sessionAuthProvider
+ ? {
+ authProvider: sessionAuthProvider,
+ credentialId: sessionCredentialId,
+ }
+ : null,
+ );
+ const dismissed = dismissedProviderFailureRef.current;
+ if (
+ historical &&
+ dismissed?.sessionId === sessionId &&
+ dismissed.fingerprint === providerFailureFingerprint(historical)
+ ) {
+ return;
+ }
+ setProviderLimit((current) => current ?? historical);
+ }, [rawSessionMessages, sessionAuthProvider, sessionCredentialId, sessionId]);
+
+ useEffect(() => {
+ if (!sessionId || !hydratedMessages) return;
+ const kickoffExpertId = useCopilotStreamStore
+ .getState()
+ .getCoord(sessionId).lastSubmittedKickoffExpertId;
+ if (!kickoffExpertId) return;
+ if (
+ !hydratedMessages.some((m) => getKickoffExpertId(m) === kickoffExpertId)
+ )
+ return;
+ useCopilotStreamStore.getState().updateCoord(sessionId, {
+ lastSubmittedMessageText: null,
+ lastSubmittedKickoffExpertId: null,
+ lastSubmittedKickoffAttemptToken: null,
+ });
+ }, [hydratedMessages, sessionId]);
+
+ const notice = snapshot.notice;
+ return {
+ followBackendTurn: () => runtime?.followBackendTurn(),
+ messages,
+ appendLocalUserRows: (entries: readonly { id: string; text: string }[]) =>
+ runtime?.appendLocalUserRows(entries),
+ /** Follow-ups drained into the running turns, for the chip strip. */
+ drainedCount: drainedRowCount(snapshot),
+ sendMessage,
+ stop,
+ status: chatStatus(snapshot.phase),
+ error: snapshot.error ?? undefined,
+ // The runtime never locks the composer: a send while it resumes is queued.
+ isReconnecting: false,
+ isFinishProbing: false,
+ isRestoringActiveSession: notice !== null,
+ restoreStatusMessage: notice ? NOTICE_TEXT[notice] : null,
+ isSyncing: false,
+ isUserStoppingRef,
+ isUserStopping: snapshot.stopped,
+ turnStats,
+ oldestSequence: history.oldestSequence,
+ rateLimitMessage,
+ platformLimitFailure,
+ providerLimit,
+ dismissProviderLimit: () => {
+ if (sessionId && providerLimit) {
+ dismissedProviderFailureRef.current = {
+ sessionId,
+ fingerprint: providerFailureFingerprint(providerLimit),
+ };
+ }
+ setProviderLimit(null);
+ },
+ dismissRateLimit: () => {
+ setRateLimitMessage(null);
+ setPlatformLimitFailure(null);
+ },
+ };
+}
+
+/**
+ * The rows above the runtime's tail, from every view this mount has seen:
+ * the session GET returns a sliding window, and a long turn slides it past
+ * rows the user already has on screen.
+ */
+function useSessionHistory(
+ sessionId: string | null,
+ view: SessionView | null,
+ cut: number | null,
+) {
+ const retained = useRef(new Map<number, PersistedRow>());
+ return useMemo(() => {
+ for (const raw of view?.messages ?? []) {
+ const row = raw as PersistedRow;
+ if (typeof row.sequence === "number")
+ retained.current.set(row.sequence, row);
+ }
+ const rows = [...retained.current.values()]
+ .filter((row) => cut === null || (row.sequence ?? 0) < cut)
+ .sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
+ const converted = sessionId
+ ? convertChatSessionMessagesToUiMessages(sessionId, rows, {
+ isComplete: !view?.active_stream,
+ })
+ : { messages: [], stats: new Map() as TurnStatsMap };
+ return {
+ messages: converted.messages,
+ stats: converted.stats,
+ oldestSequence: rows[0]?.sequence ?? null,
+ };
+ }, [sessionId, view, cut]);
+}
+
+// Before the runtime attaches to a running turn, its persisted rows are
+// already the tail's; cutting them here keeps them from flashing as history.
+function prospectiveCut(runtime: TurnRuntime | null, view: SessionView | null) {
+ const active = view?.active_stream;
+ if (!runtime || !view || !active || !runtime.wouldAttach(view)) return null;
+ if (active.checkpoint) return active.checkpoint.sequence;
+ const sequences = (view.messages ?? [])
+ .map((row) => (row as PersistedRow).sequence)
+ .filter((s): s is number => typeof s === "number");
+ return sequences.length ? Math.max(...sequences) + 1 : 0;
+}
+
+function withLatestUser(
+ messages: UIMessage[],
+ historyStats: TurnStatsMap,
+ tailStats: TurnStatsMap,
+) {
+ const stats: TurnStatsMap = new Map(historyStats);
+ tailStats.forEach((value, key) => stats.set(key, value));
+ const latestUser = messages.findLast((m) => m.role === "user");
+ stats.forEach((value, key) => {
+ if (value.isLatestUserMessage && key !== latestUser?.id) {
+ stats.set(key, { ...value, isLatestUserMessage: false });
+ }
+ });
+ if (latestUser) {
+ stats.set(latestUser.id, {
+ ...stats.get(latestUser.id),
+ isLatestUserMessage: true,
+ });
+ }
+ return stats;
+}
+
+function chatStatus(phase: RuntimePhase) {
+ switch (phase) {
+ case "connecting":
+ return "submitted" as const;
+ case "live":
+ case "resuming":
+ return "streaming" as const;
+ case "failed":
+ return "error" as const;
+ default:
+ return "ready" as const;
+ }
+}
+
+function drainedRowCount(snapshot: RuntimeSnapshot) {
+ let count = 0;
+ for (const seg of snapshot.segments) {
+ if (seg.kind !== "turn") continue;
+ count += seg.log.rows.filter((row) => row.role === "user").length;
+ }
+ return count;
+}
+
+function viewOf(data: unknown): SessionView | null {
+ const response = data as { status?: number; data?: SessionView } | undefined;
+ return response?.status === 200 && response.data ? response.data : null;
+}
+
+function textOf(input: { parts: UIMessage["parts"] }) {
+ return input.parts.map((p) => (p.type === "text" ? p.text : "")).join("");
+}
+
+function isComposerEmpty() {
+ const composer = document.getElementById(
+ "chat-input",
+ ) as HTMLTextAreaElement | null;
+ return !composer || composer.value.length === 0;
+}
+
+function subscribeNothing() {
+ return () => {};
+}
+
+function emptySnapshot() {
+ return EMPTY_SNAPSHOT;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.ts
index a54f5b4a14..6f70e0bec3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.ts
@@ -1,6 +1,5 @@
import { postV2CancelSessionTask } from "@/app/api/__generated__/endpoints/chat/chat";
import { toast } from "@/components/molecules/Toast/use-toast";
-import type { UseChatHelpers } from "@ai-sdk/react";
import type { UIMessage } from "ai";
import { resolveInProgressTools } from "./helpers";
@@ -15,8 +14,9 @@ export const CANCELLED_MARKER = "[__COPILOT_ERROR_f7a1__] Operation cancelled";
interface UseCopilotStopArgs {
sessionId: string | null;
- sdkStop: () => void;
- setMessages: UseChatHelpers<UIMessage>["setMessages"];
+ /** Aborts the stream and marks the turn stopped on screen, synchronously,
+ * so the UI reflects the click before the cancel POST returns. */
+ stopStream: () => void;
/** Flipped to `true` so the stream's onError/onFinish callbacks don't
* misinterpret the resulting AbortError as a disconnect + reconnect. */
isUserStoppingRef: React.MutableRefObject<boolean>;
@@ -27,49 +27,23 @@ interface UseCopilotStopArgs {
}
/**
- * Build the `stop` handler for `useCopilotStream`.
- *
- * Wraps AI-SDK's `stop()` to:
+ * Build the `stop` handler for the chat stream:
* 1. flag the stop as user-initiated (so onError/onFinish don't reconnect)
- * 2. abort the SSE fetch synchronously for instant UI feedback
- * 3. inject a cancellation marker into the visible assistant message
- * 4. asynchronously tell the backend executor to actually stop the task,
+ * 2. abort the stream and mark the turn stopped, for instant UI feedback
+ * 3. asynchronously tell the backend executor to actually stop the task,
* surfacing a toast when the cancel was published but not yet
* confirmed (the task should stop shortly) or failed outright.
*/
export function useCopilotStop({
sessionId,
- sdkStop,
- setMessages,
+ stopStream,
isUserStoppingRef,
setIsUserStopping,
}: UseCopilotStopArgs) {
async function stop() {
isUserStoppingRef.current = true;
setIsUserStopping(true);
- try {
- sdkStop();
- } catch {
- // sdkStop throws if no fetch is in flight — the user-stop flag
- // already flipped, so the UI reflects the intent either way.
- }
- setMessages((prev) => {
- const resolved = resolveInProgressTools(prev, "cancelled");
- const last = resolved[resolved.length - 1];
- if (last?.role === "assistant") {
- return [
- ...resolved.slice(0, -1),
- {
- ...last,
- parts: [
- ...last.parts,
- { type: "text" as const, text: CANCELLED_MARKER },
- ],
- },
- ];
- }
- return resolved;
- });
+ stopStream();
if (!sessionId) return;
try {
@@ -96,3 +70,35 @@ export function useCopilotStop({
return stop;
}
+
+/**
+ * The AI SDK path's `stopStream`: abort the SDK's fetch, cancel open tools
+ * and append the marker to the last assistant message.
+ */
+export function sdkStopStream(
+ sdkStop: () => void,
+ setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void,
+) {
+ return () => {
+ try {
+ sdkStop();
+ } catch {
+ // sdkStop throws if no fetch is in flight — the user-stop flag
+ // already flipped, so the UI reflects the intent either way.
+ }
+ setMessages(markMessagesStopped);
+ };
+}
+
+function markMessagesStopped(prev: UIMessage[]): UIMessage[] {
+ const resolved = resolveInProgressTools(prev, "cancelled");
+ const last = resolved[resolved.length - 1];
+ if (last?.role !== "assistant") return resolved;
+ return [
+ ...resolved.slice(0, -1),
+ {
+ ...last,
+ parts: [...last.parts, { type: "text" as const, text: CANCELLED_MARKER }],
+ },
+ ];
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
index 6cf88b713c..aa81c3941d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
@@ -44,7 +44,7 @@ import {
import { useCopilotUIStore } from "./store";
import type { CopilotLlmModel } from "./store";
import { useCopilotReconnect } from "./useCopilotReconnect";
-import { useCopilotStop } from "./useCopilotStop";
+import { sdkStopStream, useCopilotStop } from "./useCopilotStop";
import { useHydrateOnStreamEnd } from "./useHydrateOnStreamEnd";
import { RESTORE_STALL_TIMEOUT_MS } from "./restoreConstants";
import { useStreamActivityWatchdog } from "./useStreamActivityWatchdog";
@@ -635,8 +635,7 @@ export function useCopilotStream({
const stop = useCopilotStop({
sessionId,
- sdkStop,
- setMessages,
+ stopStream: sdkStopStream(sdkStop, setMessages),
isUserStoppingRef,
setIsUserStopping,
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
index 1c3b9c3554..113cb0062d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts
@@ -1,6 +1,5 @@
import { toast } from "@/components/molecules/Toast/use-toast";
import { uploadFileDirect } from "@/lib/direct-upload";
-import type { UseChatHelpers } from "@ai-sdk/react";
import type { FileUIPart, UIMessage } from "ai";
import { useEffect, useRef } from "react";
import {
@@ -20,6 +19,7 @@ import {
type WorkspaceAttachment,
} from "./helpers/workspaceAttachments";
import { useCopilotUIStore } from "./store";
+import type { SendInput } from "./stream/turnRuntime";
const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;
@@ -29,7 +29,7 @@ interface UploadedFile {
mime_type: string;
}
-type SendMessageFn = UseChatHelpers<UIMessage>["sendMessage"];
+type SendMessageFn = (message: SendInput) => Promise<void>;
interface Args {
sessionId: string | null;
diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
index 489676ebe8..aa8f769e1d 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
@@ -64,6 +64,9 @@ export enum Flag {
// The share of chat sessions whose stream the converter shadows and checks
// against the server, 0 to 1 (a PostHog payload). 0 is off.
COPILOT_STREAM_SHADOW = "copilot-stream-shadow",
+ // The chat's own stream runtime in place of the AI SDK's: resume at a
+ // cursor, render from the persisted rows. Frontend only; fail-closed.
+ COPILOT_STREAM_RUNTIME = "copilot-stream-runtime",
}
const isPwMockEnabled = process.env.NEXT_PUBLIC_PW_TEST === "true";
@@ -99,6 +102,7 @@ const defaultFlags = {
[Flag.COPILOT_VOICE_MODE]: false,
[Flag.COPILOT_AUTO_MODE]: false,
[Flag.COPILOT_STREAM_SHADOW]: 0,
+ [Flag.COPILOT_STREAM_RUNTIME]: false,
};
type FlagValues = typeof defaultFlags;
@@ -166,6 +170,8 @@ function readEnvOverride(flag: Flag): string | undefined {
return process.env.NEXT_PUBLIC_FORCE_FLAG_COPILOT_VOICE_MODE;
case Flag.COPILOT_AUTO_MODE:
return process.env.NEXT_PUBLIC_FORCE_FLAG_COPILOT_AUTO_MODE;
+ case Flag.COPILOT_STREAM_RUNTIME:
+ return process.env.NEXT_PUBLIC_FORCE_FLAG_COPILOT_STREAM_RUNTIME;
case Flag.COPILOT_BOT_PLATFORMS:
case Flag.COPILOT_STREAM_SHADOW:
return undefined;
diff --git a/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts b/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts
index 5475c59a1f..ae202acdb8 100644
--- a/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts
+++ b/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts
@@ -24,15 +24,23 @@ interface StreamChunksOptions {
* ReadableStream is not always invoked on abort in test environments).
*/
abortSignal?: AbortSignal;
+ /** The turn whose entries these are: every frame carries `id: <turn>:<n>-0`,
+ * as the route writes it. A fresh turn per response by default. */
+ turnId?: string;
+ /** Serve only the entries after this cursor, as a resume at a cursor does. */
+ after?: string | null;
}
+let turnCounter = 0;
+
export function streamSseResponse(
chunks: UIMessageChunk[],
options: StreamChunksOptions = {},
) {
const { delayMsBetweenChunks = 0, perChunkDelaysMs, abortSignal } = options;
+ const turnId = options.turnId ?? `sse-turn-${++turnCounter}`;
const encoder = new TextEncoder();
- let nextIndex = 0;
+ let nextIndex = options.after ? Number(options.after.split("-")[0]) : 0;
let cancelled = false;
let pendingTimer: ReturnType<typeof setTimeout> | undefined;
let pendingResolve: (() => void) | undefined;
@@ -94,7 +102,11 @@ export function streamSseResponse(
return;
}
const chunk = chunks[nextIndex++];
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
+ controller.enqueue(
+ encoder.encode(
+ `id: ${turnId}:${nextIndex}-0\ndata: ${JSON.stringify(chunk)}\n\n`,
+ ),
+ );
},
cancel() {
abortNow();
@@ -144,18 +156,22 @@ export function copilotStreamHandler({
);
}
+/** A resume names its turn and cursor; one without them replays the whole turn. */
export function copilotResumeHandler({
baseUrl,
sessionId,
chunks,
...streamOptions
}: CopilotStreamHandlerOptions): HttpHandler {
- return http.get(streamUrl(baseUrl, sessionId), ({ request }) =>
- streamSseResponse(chunks, {
+ return http.get(streamUrl(baseUrl, sessionId), ({ request }) => {
+ const params = new URL(request.url).searchParams;
+ return streamSseResponse(chunks, {
+ turnId: params.get("turn") ?? undefined,
+ after: params.get("after"),
...streamOptions,
abortSignal: request.signal,
- }),
- );
+ });
+ });
}
interface CopilotErrorHandlerOptions {