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.

test(frontend/copilot): add SSE streaming integration test infrastructure (#13098)

Ubbe3073d443af3f
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
new file mode 100644
index 0000000000..3e7278c5f6
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx
@@ -0,0 +1,301 @@
+import { server } from "@/mocks/mock-server";
+import {
+ assistantTextChunks,
+ copilotStreamHandler,
+} 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,
+ TEST_BACKEND_BASE_URL,
+ TEST_SESSION_ID,
+ typeAndSend,
+} from "./sse-helpers";
+
+// Pin the backend host so the CoPilot transport's absolute URL is
+// deterministic — the transport bypasses the Next proxy on purpose
+// (Vercel function-timeout dodge), so MSW has to match an absolute URL.
+vi.mock("@/services/environment", async (importActual) => {
+ const actual = await importActual<typeof import("@/services/environment")>();
+ return {
+ ...actual,
+ environment: {
+ ...actual.environment,
+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,
+ },
+ };
+});
+
+// Replace the Supabase token fetch with a static header so we don't need
+// real auth in tests.
+vi.mock("../helpers", async (importActual) => {
+ const actual = await importActual<typeof import("../helpers")>();
+ return {
+ ...actual,
+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),
+ };
+});
+
+// useChatSession depends on useSupabase via useCopilotPage's auth gate.
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),
+}));
+
+// Keep mode/model toggles and artifacts off so the chat input renders a
+// single, predictable Submit button.
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ ARTIFACTS: "ARTIFACTS",
+ CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
+ ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ },
+ useGetFlag: () => false,
+}));
+
+beforeEach(() => {
+ resetCopilotChatRegistry();
+});
+
+afterEach(() => {
+ resetCopilotChatRegistry();
+});
+
+describe("AutoPilot 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();
+ });
+
+ 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("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("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");
+
+ // 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
new file mode 100644
index 0000000000..20647b17ec
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
@@ -0,0 +1,177 @@
+import { server } from "@/mocks/mock-server";
+import {
+ copilotStreamErrorHandler,
+ 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,
+ TEST_BACKEND_BASE_URL,
+ TEST_SESSION_ID,
+ typeAndSend,
+} from "./sse-helpers";
+
+vi.mock("@/services/environment", async (importActual) => {
+ const actual = await importActual<typeof import("@/services/environment")>();
+ return {
+ ...actual,
+ environment: {
+ ...actual.environment,
+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,
+ },
+ };
+});
+
+vi.mock("../helpers", async (importActual) => {
+ const actual = await importActual<typeof import("../helpers")>();
+ return {
+ ...actual,
+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),
+ };
+});
+
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ ARTIFACTS: "ARTIFACTS",
+ CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
+ ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ },
+ useGetFlag: () => false,
+}));
+
+beforeEach(() => {
+ resetCopilotChatRegistry();
+});
+
+afterEach(() => {
+ resetCopilotChatRegistry();
+});
+
+describe("AutoPilot streaming — error paths", () => {
+ 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();
+ });
+
+ 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 autopilot limit reached/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ });
+
+ 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");
+
+ expect(
+ await screen.findByText(/kaboom/i, undefined, { timeout: 5000 }),
+ ).toBeDefined();
+ });
+
+ 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." },
+ ],
+ }),
+ );
+
+ 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();
+ });
+
+ 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();
+ });
+});
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
new file mode 100644
index 0000000000..28e34c623e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-lifecycle.test.tsx
@@ -0,0 +1,150 @@
+import { server } from "@/mocks/mock-server";
+import {
+ assistantTextChunks,
+ copilotResumeHandler,
+ copilotStreamHandler,
+} 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,
+ TEST_BACKEND_BASE_URL,
+ TEST_SESSION_ID,
+ typeAndSend,
+} from "./sse-helpers";
+
+vi.mock("@/services/environment", async (importActual) => {
+ const actual = await importActual<typeof import("@/services/environment")>();
+ return {
+ ...actual,
+ environment: {
+ ...actual.environment,
+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,
+ },
+ };
+});
+
+vi.mock("../helpers", async (importActual) => {
+ const actual = await importActual<typeof import("../helpers")>();
+ return {
+ ...actual,
+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),
+ };
+});
+
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ ARTIFACTS: "ARTIFACTS",
+ CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
+ ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ },
+ useGetFlag: () => false,
+}));
+
+beforeEach(() => {
+ resetCopilotChatRegistry();
+});
+
+afterEach(() => {
+ resetCopilotChatRegistry();
+});
+
+describe("AutoPilot 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(/you manually stopped this chat/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeDefined();
+ // Post-stop chunks never reach the bubble.
+ expect(screen.queryByText(/should be cut off/i)).toBeNull();
+ });
+});
+
+describe("AutoPilot 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();
+ });
+});
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
new file mode 100644
index 0000000000..cce9a1dc4c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx
@@ -0,0 +1,175 @@
+import {
+ getGetV2GetCopilotUsageMockHandler200,
+ getGetV2GetPendingMessagesMockHandler200,
+ getGetV2GetSessionMockHandler200,
+ getPostV2CancelSessionTaskMockHandler200,
+} from "@/app/api/__generated__/endpoints/chat/chat.msw";
+import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";
+import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";
+import { server } from "@/mocks/mock-server";
+import OnboardingProvider from "@/providers/onboarding/onboarding-provider";
+import { streamSseResponse } from "@/tests/integrations/copilot-sse";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { UIMessageChunk } from "ai";
+import { http, type HttpHandler } from "msw";
+import { NuqsTestingAdapter } from "nuqs/adapters/testing";
+import { ReactNode, useState } from "react";
+import { expect } from "vitest";
+import { CopilotChatHost } from "../CopilotChatHost";
+
+export const TEST_BACKEND_BASE_URL = "http://localhost:18006";
+export const TEST_SESSION_ID = "test-session-stream-1";
+
+export interface SessionOverride {
+ active_stream?: SessionDetailResponse["active_stream"];
+ messages?: SessionDetailResponse["messages"];
+ has_more_messages?: boolean;
+ chat_status?: string;
+}
+
+/**
+ * Override the default Orval session-GET handler with a clean, fully-controlled
+ * session — empty messages, no active stream — so each test starts from a
+ * deterministic baseline. Random faker fields are replaced with stable values.
+ */
+export function sessionHandler(opts: SessionOverride = {}) {
+ return getGetV2GetSessionMockHandler200({
+ id: TEST_SESSION_ID,
+ created_at: "2026-05-13T00:00:00Z",
+ updated_at: "2026-05-13T00:00:00Z",
+ user_id: "test-user",
+ chat_status: opts.chat_status ?? "idle",
+ messages: opts.messages ?? [],
+ has_more_messages: opts.has_more_messages ?? false,
+ oldest_sequence: null,
+ active_stream: opts.active_stream ?? null,
+ metadata: { dry_run: false, builder_graph_id: null },
+ });
+}
+
+/**
+ * Multi-call POST handler for the CoPilot stream URL. Each request consumes
+ * the next entry in `chunksPerTurn`; after the array is exhausted the last
+ * entry is replayed for every subsequent request. Lets a single test exercise
+ * back-to-back turns in the same session.
+ */
+export function copilotStreamSequenceHandler({
+ baseUrl,
+ sessionId,
+ chunksPerTurn,
+}: {
+ baseUrl: string;
+ sessionId: string;
+ chunksPerTurn: UIMessageChunk[][];
+}): HttpHandler {
+ let turn = 0;
+ return http.post(
+ `${baseUrl}/api/chat/sessions/${sessionId}/stream`,
+ ({ request }) => {
+ const chunks =
+ chunksPerTurn[turn] ?? chunksPerTurn[chunksPerTurn.length - 1];
+ turn += 1;
+ return streamSseResponse(chunks, { abortSignal: request.signal });
+ },
+ );
+}
+
+function Wrapper({
+ children,
+ searchParams,
+}: {
+ children: ReactNode;
+ searchParams: string;
+}) {
+ const [queryClient] = useState(
+ () => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ );
+ return (
+ <QueryClientProvider client={queryClient}>
+ <NuqsTestingAdapter searchParams={searchParams}>
+ <BackendAPIProvider>
+ <OnboardingProvider>
+ <TooltipProvider>{children}</TooltipProvider>
+ </OnboardingProvider>
+ </BackendAPIProvider>
+ </NuqsTestingAdapter>
+ </QueryClientProvider>
+ );
+}
+
+/**
+ * Render `<CopilotChatHost />` with a pre-set `sessionId` in URL state and
+ * neutral overrides for the chat-adjacent endpoints (session, usage, pending
+ * messages). The default Orval mocks return random faker data that flips the
+ * input into "limit reached" or injects ghost queued chips, so we pin them.
+ */
+export function renderHost(opts: { sessionOverride?: SessionOverride } = {}) {
+ server.use(
+ sessionHandler(opts.sessionOverride),
+ getGetV2GetCopilotUsageMockHandler200({
+ daily: {
+ percent_used: 0,
+ resets_at: new Date("2026-05-14T00:00:00Z"),
+ },
+ weekly: {
+ percent_used: 0,
+ resets_at: new Date("2026-05-20T00:00:00Z"),
+ },
+ tier: "PRO",
+ reset_cost: 0,
+ }),
+ getGetV2GetPendingMessagesMockHandler200({
+ count: 0,
+ messages: [],
+ }),
+ // useCopilotStop POSTs here when the user clicks Stop. The default
+ // Orval handler returns random faker fields; pin to a deterministic
+ // success so the stop path neither triggers the destructive "Could
+ // not stop the task" toast nor the "Stop may take a moment" toast
+ // (which would render extra DOM and risk flaky assertions).
+ getPostV2CancelSessionTaskMockHandler200({
+ cancelled: true,
+ reason: null,
+ }),
+ );
+ return render(
+ <CopilotChatHost droppedFiles={[]} onDroppedFilesConsumed={() => {}} />,
+ {
+ wrapper: ({ children }) => (
+ <Wrapper searchParams={`?sessionId=${TEST_SESSION_ID}`}>
+ {children}
+ </Wrapper>
+ ),
+ },
+ );
+}
+
+/**
+ * The textarea is disabled while the session GET is loading. Block until it's
+ * enabled before driving userEvent — otherwise keystrokes are silently
+ * swallowed and the test times out on findByText with no useful trace.
+ */
+export async function waitForInputReady() {
+ await waitFor(() => {
+ const input = screen.getByLabelText(
+ /chat message input/i,
+ ) as HTMLTextAreaElement;
+ expect(input.disabled).toBe(false);
+ });
+}
+
+export async function typeAndSend(text: string) {
+ await waitForInputReady();
+ const user = userEvent.setup();
+ const input = screen.getByLabelText(/chat message input/i);
+ await user.type(input, text);
+ await user.click(screen.getByRole("button", { name: /submit/i }));
+}
+
+export async function clickStop() {
+ const user = userEvent.setup();
+ await user.click(await screen.findByRole("button", { name: /stop/i }));
+}
diff --git a/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts b/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts
new file mode 100644
index 0000000000..5475c59a1f
--- /dev/null
+++ b/autogpt_platform/frontend/src/tests/integrations/copilot-sse.ts
@@ -0,0 +1,183 @@
+import type { UIMessageChunk } from "ai";
+import { http, HttpResponse, type HttpHandler } from "msw";
+
+const SSE_HEADERS = {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ "x-vercel-ai-ui-message-stream": "v1",
+ "x-accel-buffering": "no",
+};
+
+interface StreamChunksOptions {
+ /** Uniform delay applied before every chunk except the first. */
+ delayMsBetweenChunks?: number;
+ /**
+ * Per-chunk delays applied before producing each chunk. Length must match
+ * `chunks`. When set, overrides `delayMsBetweenChunks`.
+ */
+ perChunkDelaysMs?: number[];
+ /**
+ * Aborts in-progress chunk production. Wire this from the MSW handler's
+ * `request.signal` so a consumer-side fetch abort can stop the stream and
+ * unblock any pending inter-chunk delay (cancel() on the underlying
+ * ReadableStream is not always invoked on abort in test environments).
+ */
+ abortSignal?: AbortSignal;
+}
+
+export function streamSseResponse(
+ chunks: UIMessageChunk[],
+ options: StreamChunksOptions = {},
+) {
+ const { delayMsBetweenChunks = 0, perChunkDelaysMs, abortSignal } = options;
+ const encoder = new TextEncoder();
+ let nextIndex = 0;
+ let cancelled = false;
+ let pendingTimer: ReturnType<typeof setTimeout> | undefined;
+ let pendingResolve: (() => void) | undefined;
+
+ function abortNow() {
+ cancelled = true;
+ if (pendingTimer) {
+ clearTimeout(pendingTimer);
+ pendingTimer = undefined;
+ }
+ if (pendingResolve) {
+ const r = pendingResolve;
+ pendingResolve = undefined;
+ r();
+ }
+ }
+ if (abortSignal) {
+ if (abortSignal.aborted) cancelled = true;
+ else abortSignal.addEventListener("abort", abortNow, { once: true });
+ }
+
+ function delayForIndex(i: number): number {
+ if (perChunkDelaysMs) return perChunkDelaysMs[i] ?? 0;
+ return i > 0 ? delayMsBetweenChunks : 0;
+ }
+
+ const stream = new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ if (cancelled) {
+ try {
+ controller.close();
+ } catch {
+ // already closed
+ }
+ return;
+ }
+ const delayMs = delayForIndex(nextIndex);
+ if (delayMs > 0) {
+ await new Promise<void>((resolve) => {
+ pendingResolve = resolve;
+ pendingTimer = setTimeout(() => {
+ pendingTimer = undefined;
+ pendingResolve = undefined;
+ resolve();
+ }, delayMs);
+ });
+ if (cancelled) {
+ try {
+ controller.close();
+ } catch {
+ // already closed
+ }
+ return;
+ }
+ }
+ if (nextIndex >= chunks.length) {
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
+ controller.close();
+ return;
+ }
+ const chunk = chunks[nextIndex++];
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
+ },
+ cancel() {
+ abortNow();
+ },
+ });
+
+ return new HttpResponse(stream, { status: 200, headers: SSE_HEADERS });
+}
+
+export function assistantTextChunks(
+ text: string,
+ options: { messageId?: string; textPartId?: string } = {},
+): UIMessageChunk[] {
+ const { messageId = "test-message-1", textPartId = "test-text-1" } = options;
+ return [
+ { type: "start", messageId },
+ { type: "start-step" },
+ { type: "text-start", id: textPartId },
+ { type: "text-delta", id: textPartId, delta: text },
+ { type: "text-end", id: textPartId },
+ { type: "finish-step" },
+ { type: "finish" },
+ ];
+}
+
+function streamUrl(baseUrl: string, sessionId: string) {
+ return `${baseUrl}/api/chat/sessions/${sessionId}/stream`;
+}
+
+interface CopilotStreamHandlerOptions extends StreamChunksOptions {
+ baseUrl: string;
+ sessionId: string;
+ chunks: UIMessageChunk[];
+}
+
+export function copilotStreamHandler({
+ baseUrl,
+ sessionId,
+ chunks,
+ ...streamOptions
+}: CopilotStreamHandlerOptions): HttpHandler {
+ return http.post(streamUrl(baseUrl, sessionId), ({ request }) =>
+ streamSseResponse(chunks, {
+ ...streamOptions,
+ abortSignal: request.signal,
+ }),
+ );
+}
+
+export function copilotResumeHandler({
+ baseUrl,
+ sessionId,
+ chunks,
+ ...streamOptions
+}: CopilotStreamHandlerOptions): HttpHandler {
+ return http.get(streamUrl(baseUrl, sessionId), ({ request }) =>
+ streamSseResponse(chunks, {
+ ...streamOptions,
+ abortSignal: request.signal,
+ }),
+ );
+}
+
+interface CopilotErrorHandlerOptions {
+ baseUrl: string;
+ sessionId: string;
+ status: number;
+ body: string | object;
+}
+
+export function copilotStreamErrorHandler({
+ baseUrl,
+ sessionId,
+ status,
+ body,
+}: CopilotErrorHandlerOptions): HttpHandler {
+ return http.post(streamUrl(baseUrl, sessionId), () => {
+ if (typeof body === "string") {
+ return new HttpResponse(body, {
+ status,
+ headers: { "content-type": "text/plain" },
+ });
+ }
+ return HttpResponse.json(body, { status });
+ });
+}