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.
dx(frontend): migrate direct hook tests to component-level tests (#12960)
Ubbe22ff12c6f0c7
diff --git a/autogpt_platform/frontend/src/middleware.test.ts b/autogpt_platform/frontend/src/__tests__/middleware.test.tssimilarity index 97%rename from autogpt_platform/frontend/src/middleware.test.tsrename to autogpt_platform/frontend/src/__tests__/middleware.test.tsindex 0dd69aff0c..2c7e9af980 100644--- a/autogpt_platform/frontend/src/middleware.test.ts+++ b/autogpt_platform/frontend/src/__tests__/middleware.test.ts@@ -7,7 +7,7 @@ vi.mock("@/lib/supabase/middleware", () => ({updateSession: (...args: unknown[]) => updateSessionMock(...args),}));-import { middleware } from "./middleware";+import { middleware } from "../middleware";describe("middleware www→non-www redirect", () => {it("redirects www host to non-www with 308", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/DiagnosticsContent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/DiagnosticsContent.test.tsxindex b4b0b843af..52f189e42b 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/DiagnosticsContent.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/DiagnosticsContent.test.tsx@@ -506,6 +506,60 @@ describe("DiagnosticsContent", () => {expect(screen.getByText(/from 4 schedules/)).toBeDefined();});+ it("shows error state when only the agent query errors (coalesces error)", () => {+ const err = { status: 500, message: "agent boom" };+ mockExecQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: false,+ error: null,+ refetch: vi.fn(),+ });+ mockAgentQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: true,+ error: err,+ refetch: vi.fn(),+ });+ mockScheduleQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: false,+ error: null,+ refetch: vi.fn(),+ });+ render(<DiagnosticsContent />);+ expect(screen.getByText("Try Again")).toBeDefined();+ });++ it("shows error state when only the schedule query errors (coalesces error)", () => {+ const err = { status: 503, message: "schedule boom" };+ mockExecQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: false,+ error: null,+ refetch: vi.fn(),+ });+ mockAgentQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: false,+ error: null,+ refetch: vi.fn(),+ });+ mockScheduleQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: true,+ error: err,+ refetch: vi.fn(),+ });+ render(<DiagnosticsContent />);+ expect(screen.getByText("Try Again")).toBeDefined();+ });+it("clicking Refresh button calls all refetch functions", () => {const refetchExec = vi.fn();const refetchAgent = vi.fn();diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/components/__tests__/useDiagnosticsContent.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/components/__tests__/useDiagnosticsContent.test.tsdeleted file mode 100644index 7ec8e58830..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/components/__tests__/useDiagnosticsContent.test.ts+++ /dev/null@@ -1,86 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { renderHook } from "@testing-library/react";--// Mock the three generated API hooks this hook composes. The hook under-// test is intentionally thin — it forwards loading/error from the three-// children and coalesces them. Stubbing at the module boundary lets us-// exercise the combine-logic without spinning up MSW.-const mockExecutions = vi.fn();-const mockAgents = vi.fn();-const mockSchedules = vi.fn();--vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({- useGetV2GetExecutionDiagnostics: (...args: unknown[]) =>- mockExecutions(...args),- useGetV2GetAgentDiagnostics: (...args: unknown[]) => mockAgents(...args),- useGetV2GetScheduleDiagnostics: (...args: unknown[]) =>- mockSchedules(...args),-}));--import { useDiagnosticsContent } from "../useDiagnosticsContent";--function stub(overrides: Record<string, unknown> = {}) {- return {- data: undefined,- isLoading: false,- isError: false,- error: null,- refetch: vi.fn(),- ...overrides,- };-}--describe("useDiagnosticsContent", () => {- it("is loading when any of the child queries is loading", () => {- mockExecutions.mockReturnValue(stub({ isLoading: true }));- mockAgents.mockReturnValue(stub());- mockSchedules.mockReturnValue(stub());-- const { result } = renderHook(() => useDiagnosticsContent());- expect(result.current.isLoading).toBe(true);- expect(result.current.isError).toBe(false);- });-- it("is in error state when any of the child queries errored", () => {- const err = new Error("schedule boom");- mockExecutions.mockReturnValue(stub());- mockAgents.mockReturnValue(stub());- mockSchedules.mockReturnValue(stub({ isError: true, error: err }));-- const { result } = renderHook(() => useDiagnosticsContent());- expect(result.current.isError).toBe(true);- expect(result.current.error).toBe(err);- });-- it("unwraps each response's data field into a dedicated return key", () => {- mockExecutions.mockReturnValue(- stub({ data: { data: { running_executions: 7 } } }),- );- mockAgents.mockReturnValue(stub({ data: { data: { total_agents: 3 } } }));- mockSchedules.mockReturnValue(- stub({ data: { data: { user_schedules: 9 } } }),- );-- const { result } = renderHook(() => useDiagnosticsContent());- expect(result.current.executionData).toEqual({ running_executions: 7 });- expect(result.current.agentData).toEqual({ total_agents: 3 });- expect(result.current.scheduleData).toEqual({ user_schedules: 9 });- });-- it("refresh() invokes refetch on all three child queries", () => {- const refetchEx = vi.fn();- const refetchAg = vi.fn();- const refetchSc = vi.fn();- mockExecutions.mockReturnValue(stub({ refetch: refetchEx }));- mockAgents.mockReturnValue(stub({ refetch: refetchAg }));- mockSchedules.mockReturnValue(stub({ refetch: refetchSc }));-- const { result } = renderHook(() => useDiagnosticsContent());- result.current.refresh();-- expect(refetchEx).toHaveBeenCalledTimes(1);- expect(refetchAg).toHaveBeenCalledTimes(1);- expect(refetchSc).toHaveBeenCalledTimes(1);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsxindex 423030177b..7834a104f1 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/RateLimitManager.test.tsx@@ -2,19 +2,27 @@ import {render,screen,fireEvent,+ waitFor,cleanup,} from "@/tests/integrations/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { server } from "@/mocks/mock-server";+import {+ getGetV2GetUserRateLimitMockHandler,+ getGetV2GetUserRateLimitMockHandler200,+ getGetV2SearchUsersByNameOrEmailMockHandler200,+ getPostV2ResetUserRateLimitUsageMockHandler200,+ getPostV2SetUserRateLimitTierMockHandler200,+} from "@/app/api/__generated__/endpoints/admin/admin.msw";+import { http, HttpResponse } from "msw";import { RateLimitManager } from "../RateLimitManager";import type { UserRateLimitResponse } from "@/app/api/__generated__/models/userRateLimitResponse";-const mockHandleSearch = vi.fn();-const mockHandleSelectUser = vi.fn();-const mockHandleReset = vi.fn();-const mockHandleTierChange = vi.fn();+const toastSpy = vi.hoisted(() => vi.fn());-vi.mock("../useRateLimitManager", () => ({- useRateLimitManager: () => mockHookReturn,+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast: toastSpy }),+ toast: toastSpy,}));vi.mock("../../../components/AdminUserSearch", () => ({@@ -47,44 +55,71 @@ vi.mock("../RateLimitDisplay", () => ({onTierChange,}: {data: UserRateLimitResponse;- onReset: (rw: boolean) => void;- onTierChange: (t: string) => void;+ onReset: (rw: boolean) => Promise<void>;+ onTierChange: (t: string) => Promise<void>;}) => (<div data-testid="rate-limit-display"><span>{data.user_email ?? data.user_id}</span>- <button onClick={() => onReset(false)}>mock-reset</button>- <button onClick={() => onTierChange("PRO")}>mock-tier</button>+ <span data-testid="display-tier">{data.tier}</span>+ <span data-testid="display-daily-used">+ {data.daily_cost_used_microdollars}+ </span>+ <button+ onClick={() => {+ onReset(false).catch(() => {});+ }}+ >+ mock-reset+ </button>+ <button+ onClick={() => {+ onTierChange("PRO").catch(() => {});+ }}+ >+ mock-tier+ </button></div>),}));-let mockHookReturn = buildHookReturn();+const RATE_LIMIT_URL =+ "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit";+const SEARCH_URL =+ "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit/search_users";+const RESET_URL =+ "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit/reset";+const TIER_URL =+ "http://localhost:3000/api/proxy/api/copilot/admin/rate_limit/tier";-function buildHookReturn(overrides: Record<string, unknown> = {}) {+function makeRateLimit(+ overrides: Partial<UserRateLimitResponse> = {},+): UserRateLimitResponse {return {- isSearching: false,- isLoadingRateLimit: false,- searchResults: [] as Array<{ user_id: string; user_email: string }>,- selectedUser: null as { user_id: string; user_email: string } | null,- rateLimitData: null as UserRateLimitResponse | null,- handleSearch: mockHandleSearch,- handleSelectUser: mockHandleSelectUser,- handleReset: mockHandleReset,- handleTierChange: mockHandleTierChange,+ user_id: "user-123",+ user_email: "[email protected]",+ daily_cost_limit_microdollars: 10_000_000,+ weekly_cost_limit_microdollars: 50_000_000,+ daily_cost_used_microdollars: 2_500_000,+ weekly_cost_used_microdollars: 10_000_000,+ tier: "BASIC",...overrides,};}+function typeAndSearch(query: string) {+ const input = screen.getByTestId("search-input") as HTMLInputElement;+ fireEvent.keyDown(input, { key: "Enter", target: { value: query } });+}++beforeEach(() => {+ toastSpy.mockClear();+});+afterEach(() => {cleanup();- mockHandleSearch.mockClear();- mockHandleSelectUser.mockClear();- mockHandleReset.mockClear();- mockHandleTierChange.mockClear();- mockHookReturn = buildHookReturn();});-describe("RateLimitManager", () => {+describe("RateLimitManager - rendering", () => {it("renders the search section", () => {render(<RateLimitManager />);expect(screen.getByText("Search User")).toBeDefined();@@ -98,119 +133,305 @@ describe("RateLimitManager", () => {).toBeDefined();});- it("does not show user list when searchResults is empty", () => {+ it("does not show user list initially", () => {render(<RateLimitManager />);expect(screen.queryByText(/Select a user/)).toBeNull();});- it("shows user selection list when results exist and no user selected", () => {- mockHookReturn = buildHookReturn({- searchResults: [+ it("does not render RateLimitDisplay initially", () => {+ render(<RateLimitManager />);+ expect(screen.queryByTestId("rate-limit-display")).toBeNull();+ });+});++describe("RateLimitManager - search behavior", () => {+ it("performs a direct lookup for an email and shows the rate limit display", async () => {+ const data = makeRateLimit();+ server.use(getGetV2GetUserRateLimitMockHandler200(data));++ render(<RateLimitManager />);+ typeAndSearch("[email protected]");++ expect(await screen.findByTestId("rate-limit-display")).toBeDefined();+ expect(screen.getByText("[email protected]")).toBeDefined();+ });++ it("performs a direct lookup for a UUID and shows the rate limit display", async () => {+ const uuid = "550e8400-e29b-41d4-a716-446655440000";+ const data = makeRateLimit({ user_id: uuid });+ server.use(getGetV2GetUserRateLimitMockHandler200(data));++ render(<RateLimitManager />);+ typeAndSearch(uuid);++ expect(await screen.findByTestId("rate-limit-display")).toBeDefined();+ });++ it("shows error toast on direct lookup failure", async () => {+ server.use(+ http.get(RATE_LIMIT_URL, () =>+ HttpResponse.json({ detail: "not found" }, { status: 404 }),+ ),+ );++ render(<RateLimitManager />);+ typeAndSearch("[email protected]");++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Error",+ variant: "destructive",+ }),+ );+ });+ expect(screen.queryByTestId("rate-limit-display")).toBeNull();+ });++ it("does fuzzy search for partial text and renders the result list", async () => {+ server.use(+ getGetV2SearchUsersByNameOrEmailMockHandler200([{ user_id: "u1", user_email: "[email protected]" },{ user_id: "u2", user_email: "[email protected]" },- ],- });+ ]),+ );render(<RateLimitManager />);+ typeAndSearch("alice");- expect(screen.getByText("Select a user (2 results)")).toBeDefined();+ expect(await screen.findByText("Select a user (2 results)")).toBeDefined();expect(screen.getByText("[email protected]")).toBeDefined();expect(screen.getByText("[email protected]")).toBeDefined();});- it("shows singular 'result' text for single result", () => {- mockHookReturn = buildHookReturn({- searchResults: [{ user_id: "u1", user_email: "[email protected]" }],+ it("shows toast when fuzzy search returns no results", async () => {+ server.use(getGetV2SearchUsersByNameOrEmailMockHandler200([]));++ render(<RateLimitManager />);+ typeAndSearch("nonexistent");++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({ title: "No results" }),+ );+ });+ });++ it("shows error toast on fuzzy search failure", async () => {+ server.use(+ http.get(SEARCH_URL, () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );++ render(<RateLimitManager />);+ typeAndSearch("alice");++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Error",+ variant: "destructive",+ }),+ );});+ });+});++describe("RateLimitManager - user selection list", () => {+ it("shows singular 'result' text for single result", async () => {+ server.use(+ getGetV2SearchUsersByNameOrEmailMockHandler200([+ { user_id: "u1", user_email: "[email protected]" },+ ]),+ );render(<RateLimitManager />);- expect(screen.getByText("Select a user (1 result)")).toBeDefined();+ typeAndSearch("alice");++ expect(await screen.findByText("Select a user (1 result)")).toBeDefined();});- it("calls handleSelectUser when a user in the list is clicked", () => {+ it("loads rate limit display when a user in the list is clicked", async () => {const users = [{ user_id: "u1", user_email: "[email protected]" },{ user_id: "u2", user_email: "[email protected]" },];- mockHookReturn = buildHookReturn({ searchResults: users });+ server.use(+ getGetV2SearchUsersByNameOrEmailMockHandler200(users),+ getGetV2GetUserRateLimitMockHandler200(+ makeRateLimit({ user_id: "u2", user_email: "[email protected]" }),+ ),+ );render(<RateLimitManager />);+ typeAndSearch("user");- fireEvent.click(screen.getByText("[email protected]"));- expect(mockHandleSelectUser).toHaveBeenCalledWith(users[1]);+ fireEvent.click(await screen.findByText("[email protected]"));++ expect(await screen.findByTestId("rate-limit-display")).toBeDefined();+ expect(screen.getByText("Selected:")).toBeDefined();});- it("hides selection list when a user is selected", () => {- const users = [{ user_id: "u1", user_email: "[email protected]" }];- mockHookReturn = buildHookReturn({- searchResults: users,- selectedUser: users[0],- });+ it("shows error toast when fetching rate limit for selected user fails", async () => {+ server.use(+ getGetV2SearchUsersByNameOrEmailMockHandler200([+ { user_id: "u1", user_email: "[email protected]" },+ ]),+ http.get(RATE_LIMIT_URL, () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );render(<RateLimitManager />);- expect(screen.queryByText(/Select a user/)).toBeNull();+ typeAndSearch("alice");++ fireEvent.click(await screen.findByText("[email protected]"));++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Error",+ variant: "destructive",+ }),+ );+ });+ expect(screen.queryByTestId("rate-limit-display")).toBeNull();});+});++describe("RateLimitManager - reset and tier change", () => {+ it("calls reset endpoint, updates rate limit data, and shows success toast", async () => {+ const initial = makeRateLimit({ daily_cost_used_microdollars: 5_000_000 });+ const after = makeRateLimit({ daily_cost_used_microdollars: 0 });++ server.use(+ getGetV2GetUserRateLimitMockHandler200(initial),+ getPostV2ResetUserRateLimitUsageMockHandler200(after),+ );++ render(<RateLimitManager />);+ typeAndSearch("[email protected]");++ await screen.findByTestId("rate-limit-display");+ fireEvent.click(screen.getByText("mock-reset"));- it("shows selected user indicator", () => {- const users = [{ user_id: "u1", user_email: "[email protected]" }];- mockHookReturn = buildHookReturn({- searchResults: users,- selectedUser: users[0],+ await waitFor(() => {+ expect(screen.getByTestId("display-daily-used").textContent).toBe("0");});+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Success" }),+ );+ });++ it("shows error toast when reset endpoint fails", async () => {+ server.use(+ getGetV2GetUserRateLimitMockHandler200(makeRateLimit()),+ http.post(RESET_URL, () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );render(<RateLimitManager />);- expect(screen.getByText("Selected:")).toBeDefined();+ typeAndSearch("[email protected]");++ await screen.findByTestId("rate-limit-display");+ fireEvent.click(screen.getByText("mock-reset"));++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Error",+ description: "Failed to reset rate limit usage.",+ variant: "destructive",+ }),+ );+ });});- it("shows loading message when isLoadingRateLimit is true", () => {- mockHookReturn = buildHookReturn({ isLoadingRateLimit: true });+ it("changes tier and re-fetches the rate limit data", async () => {+ let callCount = 0;+ server.use(+ http.get(RATE_LIMIT_URL, () => {+ callCount += 1;+ const tier = callCount === 1 ? "BASIC" : "PRO";+ return HttpResponse.json(makeRateLimit({ tier }), { status: 200 });+ }),+ getPostV2SetUserRateLimitTierMockHandler200(),+ );render(<RateLimitManager />);- expect(screen.getByText("Loading rate limits...")).toBeDefined();+ typeAndSearch("[email protected]");++ await waitFor(() =>+ expect(screen.getByTestId("display-tier").textContent).toBe("BASIC"),+ );++ fireEvent.click(screen.getByText("mock-tier"));++ await waitFor(() =>+ expect(screen.getByTestId("display-tier").textContent).toBe("PRO"),+ );});- it("renders RateLimitDisplay when rateLimitData is present", () => {- mockHookReturn = buildHookReturn({- rateLimitData: {- user_id: "user-123",- user_email: "[email protected]",- daily_cost_limit_microdollars: 10_000_000,- weekly_cost_limit_microdollars: 50_000_000,- daily_cost_used_microdollars: 2_500_000,- weekly_cost_used_microdollars: 10_000_000,- tier: "BASIC",- },- });+ it("does not update tier when the set-tier endpoint fails", async () => {+ let getCount = 0;+ server.use(+ http.get(RATE_LIMIT_URL, () => {+ getCount += 1;+ return HttpResponse.json(makeRateLimit({ tier: "BASIC" }), {+ status: 200,+ });+ }),+ http.post(TIER_URL, () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );render(<RateLimitManager />);- expect(screen.getByTestId("rate-limit-display")).toBeDefined();- expect(screen.getByText("[email protected]")).toBeDefined();+ typeAndSearch("[email protected]");++ await screen.findByTestId("rate-limit-display");+ expect(getCount).toBe(1);++ fireEvent.click(screen.getByText("mock-tier"));++ // The hook throws on non-200, so it never re-fetches. The displayed tier+ // should remain BASIC and no second GET should fire.+ await waitFor(() => {+ expect(screen.getByTestId("display-tier").textContent).toBe("BASIC");+ });+ expect(getCount).toBe(1);});- it("does not render RateLimitDisplay when rateLimitData is null", () => {+ it("does not render RateLimitDisplay when search returns no rate limit data", () => {+ // Default initial render: ensure the display is gated on rateLimitData.render(<RateLimitManager />);expect(screen.queryByTestId("rate-limit-display")).toBeNull();});+});- it("passes handleReset and handleTierChange to RateLimitDisplay", () => {- mockHookReturn = buildHookReturn({- rateLimitData: {- user_id: "user-123",- user_email: "[email protected]",- daily_cost_limit_microdollars: 10_000_000,- weekly_cost_limit_microdollars: 50_000_000,- daily_cost_used_microdollars: 2_500_000,- weekly_cost_used_microdollars: 10_000_000,- tier: "BASIC",- },- });+describe("RateLimitManager - loading states", () => {+ it("shows loading message while fetching rate limit after selecting user", async () => {+ server.use(+ getGetV2SearchUsersByNameOrEmailMockHandler200([+ { user_id: "u1", user_email: "[email protected]" },+ ]),+ // Delayed handler so we can observe the loading state+ getGetV2GetUserRateLimitMockHandler(+ async () =>+ new Promise<UserRateLimitResponse>((resolve) =>+ setTimeout(() => resolve(makeRateLimit()), 50),+ ),+ ),+ );render(<RateLimitManager />);+ typeAndSearch("alice");- fireEvent.click(screen.getByText("mock-reset"));- expect(mockHandleReset).toHaveBeenCalledWith(false);+ fireEvent.click(await screen.findByText("[email protected]"));- fireEvent.click(screen.getByText("mock-tier"));- expect(mockHandleTierChange).toHaveBeenCalledWith("PRO");+ expect(await screen.findByText("Loading rate limits...")).toBeDefined();+ expect(await screen.findByTestId("rate-limit-display")).toBeDefined();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.tsdeleted file mode 100644index 00ba9303bc..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/admin/rate-limits/components/__tests__/useRateLimitManager.test.ts+++ /dev/null@@ -1,393 +0,0 @@-import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";-import { renderHook, act, cleanup } from "@testing-library/react";--const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", () => ({- useToast: () => ({ toast: mockToast }),-}));--const mockGetV2GetUserRateLimit = vi.fn();-const mockGetV2SearchUsersByNameOrEmail = vi.fn();-const mockPostV2ResetUserRateLimitUsage = vi.fn();-const mockPostV2SetUserRateLimitTier = vi.fn();--vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({- getV2GetUserRateLimit: (...args: unknown[]) =>- mockGetV2GetUserRateLimit(...args),- getV2SearchUsersByNameOrEmail: (...args: unknown[]) =>- mockGetV2SearchUsersByNameOrEmail(...args),- postV2ResetUserRateLimitUsage: (...args: unknown[]) =>- mockPostV2ResetUserRateLimitUsage(...args),- postV2SetUserRateLimitTier: (...args: unknown[]) =>- mockPostV2SetUserRateLimitTier(...args),-}));--import { useRateLimitManager } from "../useRateLimitManager";--function makeRateLimitResponse(overrides = {}) {- return {- user_id: "user-123",- user_email: "[email protected]",- daily_cost_limit_microdollars: 10_000_000,- weekly_cost_limit_microdollars: 50_000_000,- daily_cost_used_microdollars: 2_500_000,- weekly_cost_used_microdollars: 10_000_000,- tier: "BASIC",- ...overrides,- };-}--beforeEach(() => {- mockToast.mockClear();- mockGetV2GetUserRateLimit.mockReset();- mockGetV2SearchUsersByNameOrEmail.mockReset();- mockPostV2ResetUserRateLimitUsage.mockReset();- mockPostV2SetUserRateLimitTier.mockReset();-});--afterEach(() => {- cleanup();-});--describe("useRateLimitManager", () => {- it("returns initial state", () => {- const { result } = renderHook(() => useRateLimitManager());-- expect(result.current.isSearching).toBe(false);- expect(result.current.isLoadingRateLimit).toBe(false);- expect(result.current.searchResults).toEqual([]);- expect(result.current.selectedUser).toBeNull();- expect(result.current.rateLimitData).toBeNull();- });-- it("handleSearch does nothing for empty query", async () => {- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch(" ");- });-- expect(mockGetV2GetUserRateLimit).not.toHaveBeenCalled();- expect(mockGetV2SearchUsersByNameOrEmail).not.toHaveBeenCalled();- });-- it("handleSearch does direct lookup for email input", async () => {- const data = makeRateLimitResponse();- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch("[email protected]");- });-- expect(mockGetV2GetUserRateLimit).toHaveBeenCalledWith({- email: "[email protected]",- });- expect(result.current.rateLimitData).toEqual(data);- expect(result.current.selectedUser).toEqual({- user_id: "user-123",- user_email: "[email protected]",- });- });-- it("handleSearch does direct lookup for UUID input", async () => {- const uuid = "550e8400-e29b-41d4-a716-446655440000";- const data = makeRateLimitResponse({ user_id: uuid });- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch(uuid);- });-- expect(mockGetV2GetUserRateLimit).toHaveBeenCalledWith({- user_id: uuid,- });- expect(result.current.rateLimitData).toEqual(data);- });-- it("handleSearch shows error toast on direct lookup failure", async () => {- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 404 });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch("[email protected]");- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "Error",- variant: "destructive",- }),- );- expect(result.current.rateLimitData).toBeNull();- });-- it("handleSearch does fuzzy search for partial text", async () => {- const users = [- { user_id: "u1", user_email: "[email protected]" },- { user_id: "u2", user_email: "[email protected]" },- ];- mockGetV2SearchUsersByNameOrEmail.mockResolvedValue({- status: 200,- data: users,- });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch("alice");- });-- expect(mockGetV2SearchUsersByNameOrEmail).toHaveBeenCalledWith({- query: "alice",- limit: 20,- });- expect(result.current.searchResults).toEqual(users);- });-- it("handleSearch shows toast when fuzzy search returns no results", async () => {- mockGetV2SearchUsersByNameOrEmail.mockResolvedValue({- status: 200,- data: [],- });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch("nonexistent");- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({ title: "No results" }),- );- expect(result.current.searchResults).toEqual([]);- });-- it("handleSearch shows error toast on fuzzy search failure", async () => {- mockGetV2SearchUsersByNameOrEmail.mockResolvedValue({ status: 500 });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSearch("alice");- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "Error",- variant: "destructive",- }),- );- });-- it("handleSelectUser fetches rate limit for selected user", async () => {- const data = makeRateLimitResponse();- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- expect(mockGetV2GetUserRateLimit).toHaveBeenCalledWith({- user_id: "user-123",- });- expect(result.current.selectedUser).toEqual({- user_id: "user-123",- user_email: "[email protected]",- });- expect(result.current.rateLimitData).toEqual(data);- });-- it("handleSelectUser shows error toast on fetch failure", async () => {- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 500 });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "Error",- variant: "destructive",- }),- );- expect(result.current.rateLimitData).toBeNull();- });-- it("handleReset calls reset endpoint and updates data", async () => {- const initial = makeRateLimitResponse({- daily_cost_used_microdollars: 5_000_000,- });- const after = makeRateLimitResponse({- daily_cost_used_microdollars: 0,- });- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data: initial });- mockPostV2ResetUserRateLimitUsage.mockResolvedValue({- status: 200,- data: after,- });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- await act(async () => {- await result.current.handleReset(false);- });-- expect(mockPostV2ResetUserRateLimitUsage).toHaveBeenCalledWith({- user_id: "user-123",- reset_weekly: false,- });- expect(result.current.rateLimitData).toEqual(after);- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({ title: "Success" }),- );- });-- it("handleReset does nothing when no rate limit data", async () => {- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleReset(false);- });-- expect(mockPostV2ResetUserRateLimitUsage).not.toHaveBeenCalled();- });-- it("handleReset shows error toast on failure", async () => {- const initial = makeRateLimitResponse();- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data: initial });- mockPostV2ResetUserRateLimitUsage.mockRejectedValue(- new Error("network error"),- );-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- await act(async () => {- await result.current.handleReset(true);- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "Error",- description: "Failed to reset rate limit usage.",- variant: "destructive",- }),- );- });-- it("handleTierChange calls set tier and re-fetches", async () => {- const initial = makeRateLimitResponse({ tier: "BASIC" });- const updated = makeRateLimitResponse({ tier: "PRO" });- mockGetV2GetUserRateLimit- .mockResolvedValueOnce({ status: 200, data: initial })- .mockResolvedValueOnce({ status: 200, data: updated });- mockPostV2SetUserRateLimitTier.mockResolvedValue({ status: 200 });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- await act(async () => {- await result.current.handleTierChange("PRO");- });-- expect(mockPostV2SetUserRateLimitTier).toHaveBeenCalledWith({- user_id: "user-123",- tier: "PRO",- });- expect(result.current.rateLimitData).toEqual(updated);- });-- it("handleTierChange does nothing when no rate limit data", async () => {- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleTierChange("PRO");- });-- expect(mockPostV2SetUserRateLimitTier).not.toHaveBeenCalled();- });-- it("handleReset throws when endpoint returns non-200 status", async () => {- const initial = makeRateLimitResponse({- daily_cost_used_microdollars: 5_000_000,- });- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data: initial });- mockPostV2ResetUserRateLimitUsage.mockResolvedValue({ status: 500 });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- await act(async () => {- await result.current.handleReset(false);- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "Error",- description: "Failed to reset rate limit usage.",- variant: "destructive",- }),- );- });-- it("handleTierChange throws when set-tier endpoint returns non-200", async () => {- const initial = makeRateLimitResponse({ tier: "BASIC" });- mockGetV2GetUserRateLimit.mockResolvedValue({ status: 200, data: initial });- mockPostV2SetUserRateLimitTier.mockResolvedValue({ status: 500 });-- const { result } = renderHook(() => useRateLimitManager());-- await act(async () => {- await result.current.handleSelectUser({- user_id: "user-123",- user_email: "[email protected]",- });- });-- await expect(- act(async () => {- await result.current.handleTierChange("PRO");- }),- ).rejects.toThrow("Failed to update tier");- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.tsdeleted file mode 100644index cbccc16734..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts+++ /dev/null@@ -1,877 +0,0 @@-import { renderHook, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { useBuilderChatPanel } from "../useBuilderChatPanel";--const createBuilderSession = vi.fn();-const createNewGraph = vi.fn();-const setActiveVersion = vi.fn();-const mockRefetchGraph = vi.fn();-const mockUseQueryStates = vi.fn();-const mockUseGetV1GetSpecificGraph = vi.fn();-const mockUseCopilotStream = vi.fn();-const mockUseCopilotPendingChips = vi.fn();--vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({- useGetV1GetSpecificGraph: (...args: unknown[]) =>- mockUseGetV1GetSpecificGraph(...args),- usePostV1CreateNewGraph: () => ({- mutateAsync: createNewGraph,- isPending: false,- }),- usePutV1SetActiveGraphVersion: () => ({ mutateAsync: setActiveVersion }),- getGetV1GetSpecificGraphQueryKey: (id: string) => ["graph", id],-}));--const mockUseGetV2GetSession = vi.fn();-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useGetV2GetSession: (...args: unknown[]) => mockUseGetV2GetSession(...args),- usePostV2CreateSession: () => ({- mutateAsync: createBuilderSession,- isPending: false,- }),- getGetV2GetSessionQueryKey: (id: string) => ["session", id],-}));--vi.mock("@/app/api/helpers", () => ({- okData: (res: unknown) => res,-}));--vi.mock("@/components/molecules/Toast/use-toast", () => ({- useToast: () => ({ toast: vi.fn() }),-}));--vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ invalidateQueries: vi.fn() }),-}));--vi.mock("nuqs", () => ({- parseAsString: Symbol("str"),- parseAsInteger: Symbol("int"),- useQueryStates: (...args: unknown[]) => mockUseQueryStates(...args),-}));--vi.mock(- "@/app/(platform)/copilot/helpers/convertChatSessionToUiMessages",- () => ({- convertChatSessionMessagesToUiMessages: () => ({- messages: [],- durations: new Map(),- }),- }),-);--vi.mock("@/app/(platform)/copilot/useCopilotStream", () => ({- useCopilotStream: (...args: unknown[]) => mockUseCopilotStream(...args),-}));--vi.mock("@/app/(platform)/copilot/useCopilotPendingChips", () => ({- useCopilotPendingChips: (...args: unknown[]) =>- mockUseCopilotPendingChips(...args),-}));--vi.mock("@sentry/nextjs", () => ({- captureException: vi.fn(),-}));--const setQueryStatesMock = vi.fn();--const defaultStream = {- messages: [],- setMessages: vi.fn(),- sendMessage: vi.fn(),- stop: vi.fn(),- status: "ready" as const,- error: undefined,-};--beforeEach(() => {- vi.clearAllMocks();- setQueryStatesMock.mockReset();- mockUseQueryStates.mockReturnValue([- { flowID: null, flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- mockUseGetV1GetSpecificGraph.mockReturnValue({- data: null,- refetch: mockRefetchGraph,- });- mockUseCopilotStream.mockReturnValue(defaultStream);- mockUseCopilotPendingChips.mockReturnValue({- queuedMessages: [],- queueMessage: vi.fn(),- });- mockUseGetV2GetSession.mockReturnValue({- data: undefined,- refetch: vi.fn(),- });-});--describe("useBuilderChatPanel", () => {- it("starts closed with no session", () => {- const { result } = renderHook(() => useBuilderChatPanel());- expect(result.current.isOpen).toBe(false);- expect(result.current.sessionId).toBeNull();- });-- it("toggles open on handleToggle", () => {- const { result, rerender } = renderHook(() => useBuilderChatPanel());- expect(result.current.isOpen).toBe(false);- result.current.handleToggle();- rerender();- expect(result.current.isOpen).toBe(true);- });-- it("surfaces the bootstrapping flag when opened without a flowID", () => {- mockUseQueryStates.mockReturnValue([- { flowID: null, flowExecutionID: null, flowVersion: null },- vi.fn(),- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- expect(result.current.isBootstrapping).toBe(true);- });-- it("forwards fast mode to useCopilotStream", () => {- renderHook(() => useBuilderChatPanel());- expect(mockUseCopilotStream).toHaveBeenCalledWith(- expect.objectContaining({ copilotMode: "fast" }),- );- });-- it("requests a builder session when opened with a flowID", async () => {- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-bound" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-1", flowExecutionID: null, flowVersion: null },- vi.fn(),- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();-- await waitFor(() => {- expect(createBuilderSession).toHaveBeenCalledWith({- data: { builder_graph_id: "graph-1" },- });- });- });-- it("exposes null revert target before any edit_agent turn", () => {- const { result } = renderHook(() => useBuilderChatPanel());- expect(result.current.revertTargetVersion).toBeNull();- });-- it("auto-creates a blank agent when opened with no flowID, writing the new id to the URL", async () => {- createNewGraph.mockResolvedValue({- status: 200,- data: { id: "graph-boot", version: 1 },- });- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();-- await waitFor(() => {- expect(createNewGraph).toHaveBeenCalled();- });- await waitFor(() => {- expect(setQueryStatesMock).toHaveBeenCalledWith({- flowID: "graph-boot",- flowVersion: 1,- });- });- });-- it("surfaces a destructive toast when the bootstrap mutation fails", async () => {- const toast = vi.fn();- const useToastMock = await import("@/components/molecules/Toast/use-toast");- (useToastMock.useToast as unknown as ReturnType<typeof vi.fn>) = vi- .fn()- .mockReturnValue({ toast });- createNewGraph.mockResolvedValue({ status: 500, data: null });- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(createNewGraph).toHaveBeenCalled();- });- // The hook catches and toasts; no throw should reach the test.- expect(result.current.isOpen).toBe(true);- });-- it("sends the message directly when stream status is ready", async () => {- const sendMessage = vi.fn();- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- sendMessage,- status: "ready",- });- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-send" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-send", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-send");- });- await result.current.onSend("hello");- expect(sendMessage).toHaveBeenCalledWith({ text: "hello" });- });-- it("no-ops onSend when no session is bound yet", async () => {- const sendMessage = vi.fn();- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- sendMessage,- status: "ready",- });- const { result } = renderHook(() => useBuilderChatPanel());- await result.current.onSend("nobody home");- expect(sendMessage).not.toHaveBeenCalled();- });-- it("no-ops onSend for empty/whitespace input even when session is live", async () => {- const sendMessage = vi.fn();- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- sendMessage,- status: "ready",- });- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-empty" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "g", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-empty");- });- await result.current.onSend(" ");- expect(sendMessage).not.toHaveBeenCalled();- });-- it("does nothing when handleRevert is called without a revert target", async () => {- const { result } = renderHook(() => useBuilderChatPanel());- await result.current.handleRevert();- expect(setActiveVersion).not.toHaveBeenCalled();- });-- it("forwards the bound graph_id on subsequent panel opens (no duplicate session create)", async () => {- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-stable" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-stable", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(createBuilderSession).toHaveBeenCalledTimes(1);- });- // Close + reopen should not re-bind while the same flowID + sessionId hold.- result.current.handleToggle();- rerender();- result.current.handleToggle();- rerender();- // Allow any pending effect microtasks to settle.- await Promise.resolve();- expect(createBuilderSession).toHaveBeenCalledTimes(1);- });-- it("rebinds for a new graph when the previous bind is still in flight (sentry 13568553)", async () => {- // Regression: the bindingRef lock used to persist across graph- // navigations, so a pending A-request left the lock set and B's bind- // effect early-returned without ever retrying — panel stuck.- // First call: slow resolve so graph-A's bind stays in flight while we navigate.- let resolveA!: (res: unknown) => void;- createBuilderSession- .mockImplementationOnce(- () =>- new Promise((r) => {- resolveA = r;- }),- )- .mockResolvedValueOnce({ status: 200, data: { id: "sess-B" } });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-A", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(createBuilderSession).toHaveBeenCalledWith({- data: { builder_graph_id: "graph-A" },- });- });- // Navigate to B while A is still pending.- mockUseQueryStates.mockReturnValue([- { flowID: "graph-B", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- rerender();- // B's bind effect must fire even though A's is mid-flight — the- // reset-on-graph-change effect clears bindingRef so B is not blocked.- await waitFor(() => {- expect(createBuilderSession).toHaveBeenCalledWith({- data: { builder_graph_id: "graph-B" },- });- });- // Resolve A late — its response must NOT overwrite B's sessionId- // (currentFlowIDRef staleness guard handles that).- resolveA({ status: 200, data: { id: "sess-A-stale" } });- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-B");- });- });-- it("resets session + revert state when flowID becomes null", async () => {- const setMessages = vi.fn();- mockUseCopilotStream.mockReturnValue({ ...defaultStream, setMessages });- // Start with a flowID so the session could bind, then drop it.- mockUseQueryStates.mockReturnValue([- { flowID: "graph-A", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- // Flip to no flowID on the next render.- mockUseQueryStates.mockReturnValue([- { flowID: null, flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- rerender();- await waitFor(() => {- expect(setMessages).toHaveBeenCalledWith([]);- });- expect(result.current.sessionId).toBeNull();- expect(result.current.revertTargetVersion).toBeNull();- });-- it("records a revert target and triggers a graph refetch when edit_agent tool output completes", async () => {- mockUseGetV1GetSpecificGraph.mockReturnValue({- data: { id: "graph-X", version: 5 },- refetch: mockRefetchGraph,- });- const messagesWithEdit = [- {- role: "assistant",- parts: [- {- type: "tool-edit_agent",- toolCallId: "tc-edit-1",- state: "output-available",- output: { agent_id: "graph-X" },- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages: messagesWithEdit,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-X", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result } = renderHook(() => useBuilderChatPanel());- await waitFor(() => {- expect(result.current.revertTargetVersion).toBe(5);- });- expect(mockRefetchGraph).toHaveBeenCalled();- });-- it("writes execution_id to flowExecutionID when run_agent tool output completes", async () => {- const messagesWithRun = [- {- role: "assistant",- parts: [- {- type: "tool-run_agent",- toolCallId: "tc-run-1",- state: "output-available",- output: { execution_id: "exec-abc-123" },- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages: messagesWithRun,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-R", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- renderHook(() => useBuilderChatPanel());- await waitFor(() => {- expect(setQueryStatesMock).toHaveBeenCalledWith({- flowExecutionID: "exec-abc-123",- });- });- });-- // Live-stream tool outputs arrive as JSON STRINGS (the backend stashes- // tool output via json.dumps). Hydrated-from-DB tool outputs arrive as- // already-parsed objects. The effect must handle both shapes.- it("writes flowVersion when edit_agent output is a JSON string (live stream)", async () => {- mockUseGetV1GetSpecificGraph.mockReturnValue({- data: { id: "graph-live", version: 3 },- refetch: mockRefetchGraph,- });- const messagesWithEdit = [- {- role: "assistant",- parts: [- {- type: "tool-edit_agent",- toolCallId: "tc-edit-live-1",- state: "output-available",- output: JSON.stringify({- type: "agent_builder_saved",- agent_id: "graph-live",- graph_version: 4,- }),- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages: messagesWithEdit,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-live", flowExecutionID: null, flowVersion: 3 },- setQueryStatesMock,- ]);- renderHook(() => useBuilderChatPanel());- await waitFor(() => {- expect(setQueryStatesMock).toHaveBeenCalledWith({ flowVersion: 4 });- });- });-- it("writes flowExecutionID when run_agent output is a JSON string (live stream)", async () => {- const messagesWithRun = [- {- role: "assistant",- parts: [- {- type: "tool-run_agent",- toolCallId: "tc-run-live-1",- state: "output-available",- output: JSON.stringify({- type: "agent_output",- execution_id: "exec-live-xyz",- }),- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages: messagesWithRun,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-live", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- renderHook(() => useBuilderChatPanel());- await waitFor(() => {- expect(setQueryStatesMock).toHaveBeenCalledWith({- flowExecutionID: "exec-live-xyz",- });- });- });-- it("ignores tool outputs that are not output-available or not assistant-role", async () => {- const messages = [- {- role: "user",- parts: [- {- type: "tool-edit_agent",- toolCallId: "tc-bad-1",- state: "output-available",- output: { agent_id: "g" },- },- ],- },- {- role: "assistant",- parts: [- {- type: "tool-run_agent",- toolCallId: "tc-bad-2",- state: "partial",- output: { execution_id: "exec-incomplete" },- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "g", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- renderHook(() => useBuilderChatPanel());- // Allow effects to flush without asserting against the tool branches.- await Promise.resolve();- expect(setQueryStatesMock).not.toHaveBeenCalledWith(- expect.objectContaining({ flowExecutionID: "exec-incomplete" }),- );- expect(mockRefetchGraph).not.toHaveBeenCalled();- });-- it("queues a follow-up via the helper when onSend is called while streaming", async () => {- const queueMessage = vi.fn();- const sendMessage = vi.fn();- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- sendMessage,- status: "streaming",- });- mockUseCopilotPendingChips.mockReturnValue({- queuedMessages: [],- queueMessage,- });- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-queue" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-queue", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- vi.doMock("@/app/(platform)/copilot/helpers/queueFollowUpMessage", () => ({- queueFollowUpMessage: vi.fn().mockResolvedValue(undefined),- }));- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-queue");- });- await result.current.onSend("queued msg");- // The message must be appended as a chip AND not sent directly.- expect(queueMessage).toHaveBeenCalledWith("queued msg");- expect(sendMessage).not.toHaveBeenCalled();- });-- it("hydrates messages from the session query when GET /sessions returns 200", async () => {- // Session data present → convertChatSessionMessagesToUiMessages runs and- // the hook forwards the hydrated messages to useCopilotStream.- mockUseGetV2GetSession.mockReturnValue({- data: {- status: 200,- data: {- id: "sess-hydrated",- messages: [{ role: "assistant", content: "welcome" }],- active_stream: null,- },- },- refetch: vi.fn(),- });- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-hydrated" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-hyd", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-hydrated");- });- // useCopilotStream should have been invoked with a non-undefined hydratedMessages.- const lastCall =- mockUseCopilotStream.mock.calls[- mockUseCopilotStream.mock.calls.length - 1- ];- expect(lastCall[0]).toHaveProperty("hydratedMessages");- });-- it("keeps the hydratedMessages reference stable across renders when session data is unchanged", async () => {- // Regression guard: an earlier version recomputed hydratedMessages on every- // render (no useMemo), which broke referential equality in- // useHydrateOnStreamEnd and caused an infinite setState loop (caught by- // React's max-update-depth guard, rendered through the builder- // ErrorBoundary as "Something went wrong"). Pin the reference here.- const sessionData = {- status: 200 as const,- data: {- id: "sess-stable",- messages: [{ role: "assistant", content: "hello" }],- active_stream: null,- },- };- mockUseGetV2GetSession.mockReturnValue({- data: sessionData,- refetch: vi.fn(),- });- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-stable" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-stable", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-stable");- });- const firstCall =- mockUseCopilotStream.mock.calls[- mockUseCopilotStream.mock.calls.length - 1- ];- const firstHydrated = firstCall[0].hydratedMessages;- rerender();- rerender();- const lastCall =- mockUseCopilotStream.mock.calls[- mockUseCopilotStream.mock.calls.length - 1- ];- expect(lastCall[0].hydratedMessages).toBe(firstHydrated);- });-- it("surfaces active_stream=true via hasActiveStream flag forwarded to the stream hook", async () => {- mockUseGetV2GetSession.mockReturnValue({- data: {- status: 200,- data: {- id: "sess-active",- messages: [],- active_stream: { turn_id: "t1", last_message_id: "0-0" },- },- },- refetch: vi.fn(),- });- createBuilderSession.mockResolvedValue({- status: 200,- data: { id: "sess-active" },- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-act", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-active");- });- const lastCall =- mockUseCopilotStream.mock.calls[- mockUseCopilotStream.mock.calls.length - 1- ];- expect(lastCall[0].hasActiveStream).toBe(true);- });-- it("toasts destructively when handleRevert receives a non-200 from setActiveVersion", async () => {- mockUseGetV1GetSpecificGraph.mockReturnValue({- data: { id: "graph-revfail", version: 9 },- refetch: mockRefetchGraph,- });- setActiveVersion.mockResolvedValue({ status: 500 });- const messagesWithEdit = [- {- role: "assistant",- parts: [- {- type: "tool-edit_agent",- toolCallId: "tc-edit-fail",- state: "output-available",- output: { agent_id: "graph-revfail" },- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages: messagesWithEdit,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-revfail", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result } = renderHook(() => useBuilderChatPanel());- await waitFor(() => {- expect(result.current.revertTargetVersion).toBe(9);- });- // Must not throw; the hook catches and toasts.- await result.current.handleRevert();- expect(setActiveVersion).toHaveBeenCalled();- });-- it("surfaces bindError and clears isBootstrapping when createBuilderSession fails", async () => {- createBuilderSession.mockRejectedValue(new Error("boom"));- mockUseQueryStates.mockReturnValue([- { flowID: "graph-err", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(createBuilderSession).toHaveBeenCalled();- });- await waitFor(() => {- expect(result.current.bindError).not.toBeNull();- });- expect(result.current.isBootstrapping).toBe(false);- // Retrying should clear the error and re-invoke the mutation.- createBuilderSession.mockResolvedValueOnce({- status: 200,- data: { id: "sess-retry" },- });- result.current.retryBind();- rerender();- await waitFor(() => {- expect(result.current.sessionId).toBe("sess-retry");- });- expect(result.current.bindError).toBeNull();- });-- it("surfaces bootstrapError when createNewGraph fails and recovers via retryBootstrap", async () => {- createNewGraph.mockRejectedValueOnce(new Error("network"));- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(createNewGraph).toHaveBeenCalled();- });- await waitFor(() => {- expect(result.current.bootstrapError).not.toBeNull();- });- expect(result.current.isBootstrapping).toBe(false);- createNewGraph.mockResolvedValueOnce({- status: 200,- data: { id: "graph-after-retry", version: 1 },- });- result.current.retryBootstrap();- rerender();- await waitFor(() => {- expect(createNewGraph).toHaveBeenCalledTimes(2);- });- await waitFor(() => {- expect(setQueryStatesMock).toHaveBeenCalledWith({- flowID: "graph-after-retry",- flowVersion: 1,- });- });- });-- it("discards a stale createBuilderSession response when flowID changed mid-request", async () => {- // The first call (slow, for graph-A) resolves AFTER the user navigates- // to graph-B — its response id must NOT overwrite the session because- // the staleness check on currentFlowIDRef should bail out.- let resolveA: (v: unknown) => void = () => {};- const slowResponseA = new Promise((resolve) => {- resolveA = resolve;- });- createBuilderSession.mockImplementationOnce(() => slowResponseA);- mockUseQueryStates.mockReturnValue([- { flowID: "graph-A", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result, rerender } = renderHook(() => useBuilderChatPanel());- result.current.handleToggle();- rerender();- await waitFor(() => {- expect(createBuilderSession).toHaveBeenCalledWith({- data: { builder_graph_id: "graph-A" },- });- });- // Navigate to graph-B — reset effect clears sessionId + boundGraphRef.- // The currentFlowIDRef is updated synchronously in an effect so the- // pending graph-A IIFE will observe graph-B on its staleness check.- mockUseQueryStates.mockReturnValue([- { flowID: "graph-B", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- rerender();- // NOW the stale graph-A response resolves — must be discarded because- // currentFlowIDRef.current !== "graph-A".- resolveA({ status: 200, data: { id: "sess-A-STALE" } });- // Flush the post-await microtasks.- await Promise.resolve();- await Promise.resolve();- // Stale response discarded: no sessionId set from it.- expect(result.current.sessionId).not.toBe("sess-A-STALE");- });-- it("reverts to the captured version and invalidates graph queries on handleRevert success", async () => {- mockUseGetV1GetSpecificGraph.mockReturnValue({- data: { id: "graph-R", version: 7 },- refetch: mockRefetchGraph,- });- const invalidateQueries = vi.fn();- const rq = await import("@tanstack/react-query");- (rq.useQueryClient as unknown as ReturnType<typeof vi.fn>) = vi- .fn()- .mockReturnValue({ invalidateQueries });- setActiveVersion.mockResolvedValue({ status: 200 });- // Prime a revert target via an edit_agent tool output.- const messagesWithEdit = [- {- role: "assistant",- parts: [- {- type: "tool-edit_agent",- toolCallId: "tc-edit-r",- state: "output-available",- output: { agent_id: "graph-R" },- },- ],- },- ];- mockUseCopilotStream.mockReturnValue({- ...defaultStream,- messages: messagesWithEdit,- status: "ready",- });- mockUseQueryStates.mockReturnValue([- { flowID: "graph-R", flowExecutionID: null, flowVersion: null },- setQueryStatesMock,- ]);- const { result } = renderHook(() => useBuilderChatPanel());- await waitFor(() => {- expect(result.current.revertTargetVersion).toBe(7);- });- await result.current.handleRevert();- expect(setActiveVersion).toHaveBeenCalledWith({- graphId: "graph-R",- data: { active_graph_version: 7 },- });- expect(setQueryStatesMock).toHaveBeenCalledWith({ flowVersion: 7 });- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.tsindex a6e837c70e..5e94feeda7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts@@ -1,11 +1,18 @@+import type { UIMessage } from "ai";import { beforeEach, describe, expect, it, vi } from "vitest";import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";import {+ ORIGINAL_TITLE,+ deduplicateMessages,+ extractSendMessageText,+ formatNotificationTitle,getCopilotAuthHeaders,getSendSuppressionReason,+ parseSessionIDs,resolveSessionDryRun,+ shouldDebounceReconnect,+ shouldSuppressDuplicateSend,} from "../helpers";-import type { UIMessage } from "ai";vi.mock("@/lib/supabase/actions", () => ({getWebSocketToken: vi.fn(),@@ -21,6 +28,556 @@ import { getSystemHeaders } from "@/lib/impersonation";const mockGetWebSocketToken = vi.mocked(getWebSocketToken);const mockGetSystemHeaders = vi.mocked(getSystemHeaders);+describe("formatNotificationTitle", () => {+ it("returns base title when count is 0", () => {+ expect(formatNotificationTitle(0)).toBe(ORIGINAL_TITLE);+ });++ it("returns formatted title with count", () => {+ expect(formatNotificationTitle(3)).toBe(+ `(3) AutoPilot is ready - ${ORIGINAL_TITLE}`,+ );+ });++ it("returns base title for negative count", () => {+ expect(formatNotificationTitle(-1)).toBe(ORIGINAL_TITLE);+ });++ it("returns base title for NaN", () => {+ expect(formatNotificationTitle(NaN)).toBe(ORIGINAL_TITLE);+ });++ it("returns formatted title for count of 1", () => {+ expect(formatNotificationTitle(1)).toBe(+ `(1) AutoPilot is ready - ${ORIGINAL_TITLE}`,+ );+ });+});++describe("parseSessionIDs", () => {+ it("returns empty set for null", () => {+ expect(parseSessionIDs(null)).toEqual(new Set());+ });++ it("returns empty set for undefined", () => {+ expect(parseSessionIDs(undefined)).toEqual(new Set());+ });++ it("returns empty set for empty string", () => {+ expect(parseSessionIDs("")).toEqual(new Set());+ });++ it("parses valid JSON array of strings", () => {+ expect(parseSessionIDs('["a","b","c"]')).toEqual(new Set(["a", "b", "c"]));+ });++ it("filters out non-string elements", () => {+ expect(parseSessionIDs('[1,"valid",null,true,"also-valid"]')).toEqual(+ new Set(["valid", "also-valid"]),+ );+ });++ it("returns empty set for non-array JSON", () => {+ expect(parseSessionIDs('{"key":"value"}')).toEqual(new Set());+ });++ it("returns empty set for JSON string value", () => {+ expect(parseSessionIDs('"oops"')).toEqual(new Set());+ });++ it("returns empty set for JSON number value", () => {+ expect(parseSessionIDs("42")).toEqual(new Set());+ });++ it("returns empty set for malformed JSON", () => {+ expect(parseSessionIDs("{broken")).toEqual(new Set());+ });++ it("deduplicates entries", () => {+ expect(parseSessionIDs('["a","a","b"]')).toEqual(new Set(["a", "b"]));+ });+});++describe("extractSendMessageText", () => {+ it("extracts text from a string argument", () => {+ expect(extractSendMessageText("hello")).toBe("hello");+ });++ it("extracts text from an object with text property", () => {+ expect(extractSendMessageText({ text: "world" })).toBe("world");+ });++ it("returns empty string for null", () => {+ expect(extractSendMessageText(null)).toBe("");+ });++ it("returns empty string for undefined", () => {+ expect(extractSendMessageText(undefined)).toBe("");+ });++ it("converts numbers to string", () => {+ expect(extractSendMessageText(42)).toBe("42");+ });+});++let msgCounter = 0;+function makeMsg(role: "user" | "assistant", text: string): UIMessage {+ return {+ id: `msg-${msgCounter++}`,+ role,+ parts: [{ type: "text", text }],+ };+}++describe("shouldSuppressDuplicateSend", () => {+ it("suppresses when reconnect is scheduled", () => {+ expect(+ shouldSuppressDuplicateSend({+ text: "hello",+ isReconnectScheduled: true,+ lastSubmittedText: null,+ messages: [],+ }),+ ).toBe(true);+ });++ it("allows send when not reconnecting and no prior submission", () => {+ expect(+ shouldSuppressDuplicateSend({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: null,+ messages: [],+ }),+ ).toBe(false);+ });++ it("suppresses when text matches last submitted AND last user message", () => {+ const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];+ expect(+ shouldSuppressDuplicateSend({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBe(true);+ });++ it("allows send when text matches last submitted but differs from last user message", () => {+ const messages = [+ makeMsg("user", "different"),+ makeMsg("assistant", "reply"),+ ];+ expect(+ shouldSuppressDuplicateSend({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBe(false);+ });++ it("allows send when text differs from last submitted", () => {+ const messages = [makeMsg("user", "hello")];+ expect(+ shouldSuppressDuplicateSend({+ text: "new message",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBe(false);+ });++ it("allows send when text is empty", () => {+ expect(+ shouldSuppressDuplicateSend({+ text: "",+ isReconnectScheduled: false,+ lastSubmittedText: "",+ messages: [],+ }),+ ).toBe(false);+ });++ it("allows send with empty messages array even if text matches lastSubmitted", () => {+ expect(+ shouldSuppressDuplicateSend({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages: [],+ }),+ ).toBe(false);+ });+});++describe("getSendSuppressionReason", () => {+ it("returns 'reconnecting' when reconnect is scheduled", () => {+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: true,+ lastSubmittedText: null,+ messages: [],+ }),+ ).toBe("reconnecting");+ });++ it("returns 'reconnecting' even when text would otherwise be a duplicate", () => {+ const messages = [makeMsg("user", "hello")];+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: true,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBe("reconnecting");+ });++ it("returns 'duplicate' when text matches last submitted AND last user message", () => {+ const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBe("duplicate");+ });++ it("returns null when text matches last submitted but differs from last user message", () => {+ const messages = [+ makeMsg("user", "different"),+ makeMsg("assistant", "reply"),+ ];+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBeNull();+ });++ it("returns null when text differs from last submitted", () => {+ const messages = [makeMsg("user", "hello")];+ expect(+ getSendSuppressionReason({+ text: "new message",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ }),+ ).toBeNull();+ });++ it("returns null when not reconnecting and no prior submission", () => {+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: null,+ messages: [],+ }),+ ).toBeNull();+ });++ it("returns null when text is empty", () => {+ expect(+ getSendSuppressionReason({+ text: "",+ isReconnectScheduled: false,+ lastSubmittedText: "",+ messages: [],+ }),+ ).toBeNull();+ });++ it("returns null when messages array is empty even if text matches lastSubmitted", () => {+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages: [],+ }),+ ).toBeNull();+ });+});++// Helper that creates messages with explicit IDs for dedup tests+function makeMsgWithId(+ id: string,+ role: "user" | "assistant",+ text: string,+): UIMessage {+ return { id, role, parts: [{ type: "text", text }] };+}++describe("deduplicateMessages", () => {+ it("removes messages with duplicate IDs", () => {+ const msgs = [+ makeMsgWithId("1", "user", "hello"),+ makeMsgWithId("1", "user", "hello"),+ ];+ expect(deduplicateMessages(msgs)).toHaveLength(1);+ });++ it("removes non-adjacent assistant duplicates with different IDs (SSE replay)", () => {+ const msgs = [+ makeMsgWithId("u1", "user", "hello"),+ makeMsgWithId("a1", "assistant", "Plan of Attack"),+ makeMsgWithId("a2", "assistant", "Next step"),+ // SSE replay appends the same content with new IDs+ makeMsgWithId("a3", "assistant", "Plan of Attack"),+ makeMsgWithId("a4", "assistant", "Next step"),+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(3); // user + 2 unique assistant msgs+ expect(result.map((m) => m.id)).toEqual(["u1", "a1", "a2"]);+ });++ it("keeps identical assistant replies to different user prompts", () => {+ const msgs = [+ makeMsgWithId("u1", "user", "What is 2+2?"),+ makeMsgWithId("a1", "assistant", "4"),+ makeMsgWithId("u2", "user", "What is 1+3?"),+ makeMsgWithId("a2", "assistant", "4"),+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(4);+ });++ it("keeps second answer when same question is asked twice in one session", () => {+ // Regression: scoping by user message TEXT instead of ID would treat both+ // turns as the same context and drop the second identical assistant reply.+ const msgs = [+ makeMsgWithId("u1", "user", "What is 2+2?"),+ makeMsgWithId("a1", "assistant", "4"),+ makeMsgWithId("u2", "user", "What is 2+2?"), // same question, different ID+ makeMsgWithId("a2", "assistant", "4"), // same answer — must be kept+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(4);+ expect(result.map((m) => m.id)).toEqual(["u1", "a1", "u2", "a2"]);+ });++ it("removes adjacent assistant duplicates", () => {+ const msgs = [+ makeMsgWithId("u1", "user", "hello"),+ makeMsgWithId("a1", "assistant", "hi there"),+ makeMsgWithId("a2", "assistant", "hi there"),+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(2);+ });++ it("handles empty message list", () => {+ expect(deduplicateMessages([])).toEqual([]);+ });++ it("passes through unique messages unchanged", () => {+ const msgs = [+ makeMsgWithId("u1", "user", "question 1"),+ makeMsgWithId("a1", "assistant", "answer 1"),+ makeMsgWithId("u2", "user", "question 2"),+ makeMsgWithId("a2", "assistant", "answer 2"),+ ];+ expect(deduplicateMessages(msgs)).toHaveLength(4);+ });++ it("does not create false positives for text parts that contain the separator", () => {+ // "a|b" + "c" and "a" + "b|c" previously collided when joined with "|"+ const msgs: UIMessage[] = [+ makeMsgWithId("u1", "user", "hello"),+ {+ id: "a1",+ role: "assistant",+ parts: [+ { type: "text", text: "a|b" },+ { type: "text", text: "c" },+ ],+ },+ {+ id: "a2",+ role: "assistant",+ parts: [+ { type: "text", text: "a" },+ { type: "text", text: "b|c" },+ ],+ },+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(3); // both assistant messages should be kept+ });++ it("deduplicates by toolCallId for tool-call parts", () => {+ const msgs: UIMessage[] = [+ makeMsgWithId("u1", "user", "run tool"),+ {+ id: "a1",+ role: "assistant",+ parts: [+ {+ type: "dynamic-tool",+ toolCallId: "tc-1",+ toolName: "test",+ state: "input-available",+ input: {},+ },+ ],+ },+ {+ id: "a2",+ role: "assistant",+ parts: [+ {+ type: "dynamic-tool",+ toolCallId: "tc-1",+ toolName: "test",+ state: "input-available",+ input: {},+ },+ ],+ },+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(2); // user + first tool call+ });++ it("passes through assistant messages with empty parts without deduplicating them", () => {+ // contentFingerprint === "[]" when parts is empty; the guard skips fingerprint+ // tracking so these messages are never incorrectly deduplicated against each other.+ const msgs: UIMessage[] = [+ makeMsgWithId("u1", "user", "hello"),+ { id: "a1", role: "assistant", parts: [] },+ { id: "a2", role: "assistant", parts: [] },+ ];+ const result = deduplicateMessages(msgs);+ expect(result).toHaveLength(3); // both empty-parts messages are kept+ });++ it("does not collapse structurally different no-text parts to the same fingerprint", () => {+ // Parts lacking both 'text' and 'toolCallId' (e.g. step-start, step-end)+ // previously all mapped to "" causing false-positive deduplication. Now+ // JSON.stringify(p) is the fallback so distinct part shapes produce+ // distinct fingerprints — and identically-shaped no-text parts still dedupe.+ const msgs: UIMessage[] = [+ makeMsgWithId("u1", "user", "hello"),+ {+ id: "a1",+ role: "assistant",+ parts: [{ type: "step-start" }],+ },+ {+ id: "a2",+ role: "assistant",+ parts: [{ type: "step-end" } as unknown as UIMessage["parts"][number]],+ },+ {+ id: "a3",+ role: "assistant",+ parts: [{ type: "step-start" }],+ },+ ];+ const result = deduplicateMessages(msgs);+ // user + step-start + step-end kept; the second step-start dedupes against a1.+ expect(result).toHaveLength(3);+ expect(result.map((m) => m.id)).toEqual(["u1", "a1", "a2"]);+ });+});++describe("shouldDebounceReconnect", () => {+ const WINDOW_MS = 1_500;++ it("returns null for the first reconnect (lastResumeAt === 0)", () => {+ expect(shouldDebounceReconnect(0, 10_000, WINDOW_MS)).toBeNull();+ });++ it("returns null for a negative lastResumeAt sentinel", () => {+ // Defensive: a negative value is still treated as "no reconnect yet".+ expect(shouldDebounceReconnect(-1, 10_000, WINDOW_MS)).toBeNull();+ });++ it("returns the remaining delay when now is inside the window", () => {+ // 500ms since the last resume — the caller must wait another 1000ms+ // before the storm cap reopens.+ const remaining = shouldDebounceReconnect(1_000, 1_500, WINDOW_MS);+ expect(remaining).toBe(1_000);+ });++ it("coalesces a reconnect that arrives immediately after the previous resume", () => {+ // now === lastResumeAt → sinceLastResume === 0, so the full window remains.+ const remaining = shouldDebounceReconnect(5_000, 5_000, WINDOW_MS);+ expect(remaining).toBe(WINDOW_MS);+ });++ it("returns null when exactly on the window boundary", () => {+ // sinceLastResume === windowMs is NOT inside the window — the next+ // reconnect should fire immediately.+ expect(shouldDebounceReconnect(1_000, 2_500, WINDOW_MS)).toBeNull();+ });++ it("returns null when the window has elapsed", () => {+ expect(shouldDebounceReconnect(1_000, 5_000, WINDOW_MS)).toBeNull();+ });++ it("returns a small remaining delay at the far edge of the window", () => {+ // 1ms before the window closes → 1ms left.+ const remaining = shouldDebounceReconnect(1_000, 2_499, WINDOW_MS);+ expect(remaining).toBe(1);+ });++ it("collapses a burst of reconnects into one debounced scheduling", () => {+ // Simulates the browser tab-throttle storm: three reconnect calls fire+ // within a single second after the last resume. Only the first slot+ // would actually run; subsequent calls must always be coalesced.+ const lastResumeAt = 10_000;+ const firstCallRemaining = shouldDebounceReconnect(+ lastResumeAt,+ 10_100,+ WINDOW_MS,+ );+ const secondCallRemaining = shouldDebounceReconnect(+ lastResumeAt,+ 10_200,+ WINDOW_MS,+ );+ const thirdCallRemaining = shouldDebounceReconnect(+ lastResumeAt,+ 10_300,+ WINDOW_MS,+ );+ expect(firstCallRemaining).toBe(1_400);+ expect(secondCallRemaining).toBe(1_300);+ expect(thirdCallRemaining).toBe(1_200);+ });++ it("allows a reconnect to fire immediately once the window has passed", () => {+ // After the window expires, a retry that came in earlier can now fire+ // rather than stalling the loop. Guards against the regression that+ // motivated the coalesce-instead-of-drop fix.+ const lastResumeAt = 10_000;+ expect(+ shouldDebounceReconnect(lastResumeAt, 10_500, WINDOW_MS),+ ).not.toBeNull();+ expect(shouldDebounceReconnect(lastResumeAt, 11_500, WINDOW_MS)).toBeNull();+ });++ it("honours a custom windowMs value", () => {+ // Shouldn't hard-code 1500 anywhere: the helper is generic over the+ // window.+ expect(shouldDebounceReconnect(1_000, 1_500, 2_000)).toBe(1_500);+ expect(shouldDebounceReconnect(1_000, 3_500, 2_000)).toBeNull();+ });+});+describe("resolveSessionDryRun", () => {it("returns false when queryData is null", () => {expect(resolveSessionDryRun(null)).toBe(false);@@ -113,71 +670,3 @@ describe("getCopilotAuthHeaders", () => {);});});--// ─── getSendSuppressionReason ─────────────────────────────────────────────────--function makeUserMsg(text: string): UIMessage {- return {- id: "msg-1",- role: "user",- content: text,- parts: [{ type: "text", text }],- } as UIMessage;-}--describe("getSendSuppressionReason", () => {- it("returns null when no dedup context exists (fresh ref)", () => {- const result = getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: null,- messages: [],- });- expect(result).toBeNull();- });-- it("returns 'reconnecting' when reconnect is scheduled regardless of text", () => {- const result = getSendSuppressionReason({- text: "hello",- isReconnectScheduled: true,- lastSubmittedText: null,- messages: [],- });- expect(result).toBe("reconnecting");- });-- it("returns 'duplicate' when same text was submitted and is the last user message", () => {- // This is the core regression test: after a successful turn the ref- // is intentionally NOT cleared to null, so submitting the same text- // again is caught here.- const result = getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages: [makeUserMsg("hello")],- });- expect(result).toBe("duplicate");- });-- it("returns null when same ref text but different last user message (different question)", () => {- // User asked "hello" before, got a reply, then asked a different question- // — the last user message in chat is now different, so no suppression.- const result = getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages: [makeUserMsg("hello"), makeUserMsg("something else")],- });- expect(result).toBeNull();- });-- it("returns null when text differs from lastSubmittedText", () => {- const result = getSendSuppressionReason({- text: "new question",- isReconnectScheduled: false,- lastSubmittedText: "old question",- messages: [makeUserMsg("old question")],- });- expect(result).toBeNull();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.tsindex fd95bbdb2c..1f319faf5c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it, beforeEach, afterEach, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ArtifactRef } from "../store";import { useCopilotUIStore } from "../store";vi.mock("@sentry/nextjs", () => ({@@ -11,6 +12,219 @@ vi.mock("@/services/environment", () => ({},}));+function makeArtifact(id: string, title = `file-${id}`): ArtifactRef {+ return {+ id,+ title,+ mimeType: "text/plain",+ sourceUrl: `/api/proxy/api/workspace/files/${id}/download`,+ origin: "agent",+ };+}++function resetStore() {+ useCopilotUIStore.setState({+ artifactPanel: {+ isOpen: false,+ isMinimized: false,+ isMaximized: false,+ width: 600,+ activeArtifact: null,+ history: [],+ },+ });+}++describe("artifactPanel store actions", () => {+ beforeEach(resetStore);++ it("openArtifact opens the panel and sets the active artifact", () => {+ const a = makeArtifact("a");+ useCopilotUIStore.getState().openArtifact(a);+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isOpen).toBe(true);+ expect(s.isMinimized).toBe(false);+ expect(s.activeArtifact?.id).toBe("a");+ expect(s.history).toEqual([]);+ });++ it("openArtifact pushes the previous artifact onto history", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(b);+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.activeArtifact?.id).toBe("b");+ expect(s.history.map((h) => h.id)).toEqual(["a"]);+ });++ it("openArtifact does NOT push history when re-opening the same artifact", () => {+ const a = makeArtifact("a");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(a);+ expect(useCopilotUIStore.getState().artifactPanel.history).toEqual([]);+ });++ it("openArtifact pops the top of history when returning to it (A→B→A)", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(b);+ useCopilotUIStore.getState().openArtifact(a); // ping-pong+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.activeArtifact?.id).toBe("a");+ // History was [a]; returning to a should pop, not push.+ expect(s.history).toEqual([]);+ });++ it("goBackArtifact pops the last entry and becomes active", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(b);+ useCopilotUIStore.getState().goBackArtifact();+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.activeArtifact?.id).toBe("a");+ expect(s.history).toEqual([]);+ });++ it("goBackArtifact is a no-op when history is empty", () => {+ const a = makeArtifact("a");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().goBackArtifact();+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.activeArtifact?.id).toBe("a");+ });++ it("closeArtifactPanel keeps activeArtifact (for exit animation) and clears history", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(b);+ useCopilotUIStore.getState().closeArtifactPanel();+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isOpen).toBe(false);+ expect(s.isMinimized).toBe(false);+ expect(s.activeArtifact?.id).toBe("b");+ expect(s.history).toEqual([]);+ });++ it("openArtifact does not resurrect a previously closed artifact into history", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().closeArtifactPanel();+ useCopilotUIStore.getState().openArtifact(b);++ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isOpen).toBe(true);+ expect(s.activeArtifact?.id).toBe("b");+ expect(s.history).toEqual([]);+ });++ it("openArtifact ignores non-previewable artifacts", () => {+ const binary = {+ ...makeArtifact("bin", "artifact.bin"),+ mimeType: "application/octet-stream",+ };++ useCopilotUIStore.getState().openArtifact(binary);++ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isOpen).toBe(false);+ expect(s.activeArtifact).toBeNull();+ expect(s.history).toEqual([]);+ });++ it("resetArtifactPanel clears active artifact and history", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(b);+ useCopilotUIStore.getState().maximizeArtifactPanel();++ useCopilotUIStore.getState().resetArtifactPanel();++ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isOpen).toBe(false);+ expect(s.isMinimized).toBe(false);+ expect(s.isMaximized).toBe(false);+ expect(s.activeArtifact).toBeNull();+ expect(s.history).toEqual([]);+ });++ it("minimize/restore toggles isMinimized without touching activeArtifact", () => {+ const a = makeArtifact("a");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().minimizeArtifactPanel();+ expect(useCopilotUIStore.getState().artifactPanel.isMinimized).toBe(true);+ useCopilotUIStore.getState().restoreArtifactPanel();+ expect(useCopilotUIStore.getState().artifactPanel.isMinimized).toBe(false);+ expect(useCopilotUIStore.getState().artifactPanel.activeArtifact?.id).toBe(+ "a",+ );+ });++ it("maximize sets isMaximized and clears isMinimized", () => {+ const a = makeArtifact("a");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().minimizeArtifactPanel();+ useCopilotUIStore.getState().maximizeArtifactPanel();+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isMaximized).toBe(true);+ expect(s.isMinimized).toBe(false);+ });++ it("restoreArtifactPanel clears both isMinimized and isMaximized", () => {+ const a = makeArtifact("a");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().maximizeArtifactPanel();+ useCopilotUIStore.getState().restoreArtifactPanel();+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isMaximized).toBe(false);+ expect(s.isMinimized).toBe(false);+ });++ it("setArtifactPanelWidth updates width and clears isMaximized", () => {+ useCopilotUIStore.getState().maximizeArtifactPanel();+ useCopilotUIStore.getState().setArtifactPanelWidth(720);+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.width).toBe(720);+ expect(s.isMaximized).toBe(false);+ });++ it("history is capped at 25 entries (MAX_HISTORY)", () => {+ // Open 27 artifacts sequentially (A0..A26). History should never exceed 25.+ for (let i = 0; i < 27; i++) {+ useCopilotUIStore.getState().openArtifact(makeArtifact(`a${i}`));+ }+ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.activeArtifact?.id).toBe("a26");+ expect(s.history.length).toBe(25);+ // The oldest entry (a0) should have been dropped; a1 is the earliest surviving.+ expect(s.history[0].id).toBe("a1");+ expect(s.history[24].id).toBe("a25");+ });++ it("clearCopilotLocalData resets artifact panel to default", () => {+ const a = makeArtifact("a");+ const b = makeArtifact("b");+ useCopilotUIStore.getState().openArtifact(a);+ useCopilotUIStore.getState().openArtifact(b);+ useCopilotUIStore.getState().maximizeArtifactPanel();++ useCopilotUIStore.getState().clearCopilotLocalData();++ const s = useCopilotUIStore.getState().artifactPanel;+ expect(s.isOpen).toBe(false);+ expect(s.isMinimized).toBe(false);+ expect(s.isMaximized).toBe(false);+ expect(s.activeArtifact).toBeNull();+ expect(s.history).toEqual([]);+ expect(s.width).toBe(600); // DEFAULT_PANEL_WIDTH+ });+});+describe("useCopilotUIStore", () => {beforeEach(() => {window.localStorage.clear();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.tsdeleted file mode 100644index 241802b9ff..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts+++ /dev/null@@ -1,126 +0,0 @@-import { renderHook } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { useChatSession } from "../useChatSession";--const mockUseGetV2GetSession = vi.fn();--vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useGetV2GetSession: (...args: unknown[]) => mockUseGetV2GetSession(...args),- usePostV2CreateSession: () => ({ mutateAsync: vi.fn(), isPending: false }),- getGetV2GetSessionQueryKey: (id: string) => ["session", id],- getGetV2ListSessionsQueryKey: () => ["sessions"],-}));--vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({- invalidateQueries: vi.fn(),- setQueryData: vi.fn(),- }),-}));--vi.mock("nuqs", () => ({- parseAsString: { withDefault: (v: unknown) => v },- useQueryState: () => ["sess-1", vi.fn()],-}));--vi.mock("../helpers/convertChatSessionToUiMessages", () => ({- convertChatSessionMessagesToUiMessages: vi.fn(() => ({- messages: [],- stats: new Map(),- })),-}));--vi.mock("../helpers", () => ({- resolveSessionDryRun: vi.fn(() => false),-}));--vi.mock("@sentry/nextjs", () => ({- captureException: vi.fn(),-}));--function makeQueryResult(- data: object | null,- overrides: Record<string, unknown> = {},-) {- return {- data: data ? { status: 200, data } : undefined,- isLoading: false,- isError: false,- isFetching: false,- refetch: vi.fn(),- ...overrides,- };-}--describe("useChatSession — pagination metadata", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("returns null for oldestSequence when no session data", () => {- mockUseGetV2GetSession.mockReturnValue(makeQueryResult(null));- const { result } = renderHook(() => useChatSession());- expect(result.current.oldestSequence).toBeNull();- });-- it("returns oldestSequence from session data", () => {- mockUseGetV2GetSession.mockReturnValue(- makeQueryResult({- messages: [],- has_more_messages: true,- oldest_sequence: 50,- active_stream: null,- }),- );- const { result } = renderHook(() => useChatSession());- expect(result.current.oldestSequence).toBe(50);- });-- it("returns hasMoreMessages from session data", () => {- mockUseGetV2GetSession.mockReturnValue(- makeQueryResult({- messages: [],- has_more_messages: true,- oldest_sequence: 0,- active_stream: null,- }),- );- const { result } = renderHook(() => useChatSession());- expect(result.current.hasMoreMessages).toBe(true);- });-- it("does not expose cached session data while a refetch is in progress", () => {- mockUseGetV2GetSession.mockReturnValue(- makeQueryResult(- {- messages: [{ role: "user", content: "stale" }],- has_more_messages: true,- oldest_sequence: 50,- active_stream: true,- },- { isFetching: true },- ),- );-- const { result } = renderHook(() => useChatSession());-- expect(result.current.hydratedMessages).toBeUndefined();- expect(result.current.rawSessionMessages).toEqual([]);- expect(result.current.hasActiveStream).toBe(false);- expect(result.current.hasMoreMessages).toBe(false);- expect(result.current.oldestSequence).toBeNull();- // isLoadingSession is scoped to the INITIAL fetch only (isLoading) so- // background refetches do not disable the chat input between keystrokes.- expect(result.current.isLoadingSession).toBe(false);- });-- it("treats the initial fetch as a loading session", () => {- mockUseGetV2GetSession.mockReturnValue(- makeQueryResult(null, { isLoading: true, isFetching: true }),- );-- const { result } = renderHook(() => useChatSession());-- expect(result.current.isLoadingSession).toBe(true);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.tsdeleted file mode 100644index 168720660e..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotNotifications.test.ts+++ /dev/null@@ -1,196 +0,0 @@-import { act, renderHook, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useCopilotNotifications } from "../useCopilotNotifications";--type WsHandler = (notification: Record<string, unknown>) => void;-let capturedHandler: WsHandler | null = null;--const mockApi = {- onWebSocketMessage: vi.fn((_method: string, handler: WsHandler) => {- capturedHandler = handler;- return () => {- capturedHandler = null;- };- }),-};--vi.mock("@/lib/autogpt-server-api/context", () => ({- useBackendAPI: () => mockApi,-}));--const mockStoreState = {- completedSessionIDs: new Set<string>(),- addCompletedSession: vi.fn(),- isNotificationsEnabled: true,- isSoundEnabled: false,-};--vi.mock("../store", () => ({- useCopilotUIStore: {- getState: () => mockStoreState,- setState: vi.fn(),- },-}));--vi.mock("../helpers", () => ({- ORIGINAL_TITLE: "AutoGPT",- formatNotificationTitle: (count: number) => `(${count}) AutoPilot is ready`,- parseSessionIDs: () => new Set<string>(),-}));--vi.mock("@/services/storage/local-storage", () => ({- Key: { COPILOT_COMPLETED_SESSIONS: "copilot-completed-sessions" },- storage: { get: vi.fn(), set: vi.fn(), remove: vi.fn() },-}));--vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- getGetV2ListSessionsQueryKey: () => ["sessions"],-}));--vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ invalidateQueries: vi.fn() }),-}));--const mockNotificationCtor = vi.fn();--function fireCompletion(sessionID: string) {- if (!capturedHandler) throw new Error("handler not captured");- capturedHandler({- type: "copilot_completion",- event: "session_completed",- session_id: sessionID,- });-}--describe("useCopilotNotifications — push SW suppression", () => {- beforeEach(() => {- capturedHandler = null;- mockApi.onWebSocketMessage.mockClear();- mockStoreState.completedSessionIDs = new Set();- mockStoreState.isNotificationsEnabled = true;- mockStoreState.isSoundEnabled = false;- mockStoreState.addCompletedSession.mockClear();-- mockNotificationCtor.mockClear();- const NotificationStub = function Notification(- this: unknown,- title: string,- opts: unknown,- ) {- mockNotificationCtor(title, opts);- } as unknown as typeof Notification;- (NotificationStub as unknown as { permission: string }).permission =- "granted";- Object.defineProperty(globalThis, "Notification", {- value: NotificationStub,- configurable: true,- writable: true,- });-- const AudioStub = function AudioStub(this: Record<string, unknown>) {- this.volume = 0;- this.play = () => Promise.resolve();- } as unknown as typeof Audio;- vi.stubGlobal("Audio", AudioStub);-- // Start with "user away" so the hook triggers the notification path:- // blur fires after mount; simulate by setting visibilityState to hidden.- Object.defineProperty(document, "visibilityState", {- value: "hidden",- configurable: true,- });- });-- afterEach(() => {- vi.restoreAllMocks();- });-- function installServiceWorker(args: {- registration: unknown | null;- pushSubscription?: unknown | null;- }) {- const swReg =- args.registration === null- ? null- : {- pushManager: {- getSubscription: vi- .fn()- .mockResolvedValue(args.pushSubscription ?? null),- },- };- Object.defineProperty(navigator, "serviceWorker", {- value: {- getRegistration: vi.fn().mockResolvedValue(swReg),- },- configurable: true,- });- }-- it("skips in-page Notification when push SW subscription is active", async () => {- installServiceWorker({- registration: {},- pushSubscription: { endpoint: "https://fcm.googleapis.com/x" },- });-- renderHook(() => useCopilotNotifications(null));-- await act(async () => {- fireCompletion("session-1");- await Promise.resolve();- await Promise.resolve();- await Promise.resolve();- });-- expect(mockStoreState.addCompletedSession).toHaveBeenCalledWith(- "session-1",- );- expect(mockNotificationCtor).not.toHaveBeenCalled();- });-- it("uses in-page Notification when SW registration has no push subscription", async () => {- installServiceWorker({- registration: {},- pushSubscription: null,- });-- renderHook(() => useCopilotNotifications(null));-- await act(async () => {- fireCompletion("session-2");- });- await waitFor(() => {- expect(mockNotificationCtor).toHaveBeenCalledTimes(1);- });- expect(mockNotificationCtor.mock.calls[0][0]).toBe("AutoPilot is ready");- });-- it("uses in-page Notification when no SW registration exists", async () => {- installServiceWorker({ registration: null });-- renderHook(() => useCopilotNotifications(null));-- await act(async () => {- fireCompletion("session-3");- });- await waitFor(() => {- expect(mockNotificationCtor).toHaveBeenCalledTimes(1);- });- });-- it("uses in-page Notification when serviceWorker API is unavailable", async () => {- Object.defineProperty(navigator, "serviceWorker", {- value: undefined,- configurable: true,- });-- renderHook(() => useCopilotNotifications(null));-- await act(async () => {- fireCompletion("session-4");- });- await waitFor(() => {- expect(mockNotificationCtor).toHaveBeenCalledTimes(1);- });- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.tsdeleted file mode 100644index 35ee934bf8..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts+++ /dev/null@@ -1,444 +0,0 @@-import { act, renderHook, waitFor } from "@testing-library/react";-import type { UIMessage } from "ai";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { useCopilotStreamStore } from "../copilotStreamStore";-import { useCopilotPage } from "../useCopilotPage";--const mockUseChatSession = vi.fn();-const mockUseCopilotStream = vi.fn();-const mockUseLoadMoreMessages = vi.fn();-const mockQueueFollowUpMessage = vi.fn();-const mockSendNewMessage = vi.fn();-const mockToast = vi.fn();--vi.mock("../useChatSession", () => ({- useChatSession: (...args: unknown[]) => mockUseChatSession(...args),-}));-vi.mock("../useCopilotStream", () => ({- useCopilotStream: (...args: unknown[]) => mockUseCopilotStream(...args),-}));-vi.mock("../useLoadMoreMessages", () => ({- useLoadMoreMessages: (...args: unknown[]) => mockUseLoadMoreMessages(...args),-}));-vi.mock("../useCopilotNotifications", () => ({- useCopilotNotifications: () => undefined,-}));-vi.mock("../useWorkflowImportAutoSubmit", () => ({- useWorkflowImportAutoSubmit: () => undefined,-}));-vi.mock("../useSendMessage", () => ({- useSendMessage: () => ({- onSend: (...args: unknown[]) => mockSendNewMessage(...args),- isUploadingFiles: false,- setPendingFileParts: vi.fn(),- }),-}));-vi.mock("../useSessionTitlePoll", () => ({- useSessionTitlePoll: () => undefined,-}));-vi.mock("../store", () => ({- useCopilotUIStore: () => ({- copilotChatMode: "chat",- copilotLlmModel: null,- isDryRun: false,- }),-}));-vi.mock("../helpers/convertChatSessionToUiMessages", () => ({- concatWithAssistantMerge: (a: unknown[], b: unknown[]) => [...a, ...b],-}));-vi.mock("../helpers", () => ({- deduplicateMessages: (msgs: unknown[]) => msgs,- getLatestAssistantStatusMessage: (- messages: Array<{ role?: string; parts?: unknown[] }>,- ) => {- const last = messages[messages.length - 1] as- | {- role?: string;- parts?: Array<{ type?: string; data?: { message?: unknown } }>;- }- | undefined;- if (last?.role !== "assistant") return null;- for (let i = (last.parts?.length ?? 0) - 1; i >= 0; i--) {- const part = last.parts?.[i];- if (part?.type === "data-cursor") continue;- if (part?.type === "data-status") {- return typeof part.data?.message === "string"- ? part.data.message- : null;- }- return null;- }- return null;- },-}));-vi.mock("../helpers/queueFollowUpMessage", () => ({- queueFollowUpMessage: (...args: unknown[]) =>- mockQueueFollowUpMessage(...args),-}));-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => mockToast(...args),-}));-vi.mock("@/lib/supabase/hooks/useSupabase", () => ({- useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),-}));-vi.mock("@/services/feature-flags/use-get-flag", () => ({- Flag: { CHAT_MODE_OPTION: "CHAT_MODE_OPTION" },- useGetFlag: () => false,-}));--function makeBaseChatSession(overrides: Record<string, unknown> = {}) {- return {- sessionId: "sess-1",- setSessionId: vi.fn(),- hydratedMessages: [],- rawSessionMessages: [],- historicalTurnStats: new Map(),- hasActiveStream: false,- activeStreamStartedAt: null,- hasMoreMessages: false,- oldestSequence: null,- isLoadingSession: false,- isSessionError: false,- createSession: vi.fn(),- isCreatingSession: false,- refetchSession: vi.fn(),- sessionDryRun: false,- ...overrides,- };-}--function makeBaseCopilotStream(overrides: Record<string, unknown> = {}) {- return {- messages: [],- setMessages: vi.fn(),- sendMessage: vi.fn(),- stop: vi.fn(),- status: "ready",- error: undefined,- isReconnecting: false,- isRestoringActiveSession: false,- restoreStatusMessage: null,- isSyncing: false,- isUserStopping: false,- isUserStoppingRef: { current: false },- rateLimitMessage: null,- dismissRateLimit: vi.fn(),- ...overrides,- };-}--function makeBaseLoadMore(overrides: Record<string, unknown> = {}) {- return {- pagedMessages: [],- pagedTurnStats: new Map(),- hasMore: false,- isLoadingMore: false,- loadMore: vi.fn(),- ...overrides,- };-}--describe("useCopilotPage — backward pagination message ordering", () => {- beforeEach(() => {- vi.clearAllMocks();- useCopilotStreamStore.getState().resetAll();- });-- it("prepends pagedMessages before currentMessages", () => {- const pagedMsg = { id: "paged", role: "user" };- const currentMsg = { id: "current", role: "assistant" };- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({ messages: [currentMsg] }),- );- mockUseLoadMoreMessages.mockReturnValue(- makeBaseLoadMore({ pagedMessages: [pagedMsg] }),- );-- const { result } = renderHook(() => useCopilotPage());-- // Backward: pagedMessages (older) come first- expect(result.current.messages[0]).toEqual(pagedMsg);- expect(result.current.messages[1]).toEqual(currentMsg);- });-});--describe("useCopilotPage — active session restore visibility", () => {- beforeEach(() => {- vi.clearAllMocks();- useCopilotStreamStore.getState().resetAll();- });-- it("hides the trailing assistant tail until an active session is resumed", () => {- const userMessage = {- id: "user-1",- role: "user",- parts: [{ type: "text", text: "Tell me more" }],- };- const assistantMessage = {- id: "assistant-1",- role: "assistant",- parts: [{ type: "reasoning", text: "Working on it" }],- };-- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({- messages: [userMessage, assistantMessage],- isRestoringActiveSession: true,- }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());-- const { result } = renderHook(() => useCopilotPage());-- expect(result.current.messages).toEqual([userMessage]);- expect(result.current.isRestoringActiveSession).toBe(true);- });-- it("preserves the hidden replay status message while restore trims the assistant tail", () => {- const userMessage = {- id: "user-1",- role: "user",- parts: [{ type: "text", text: "Tell me more" }],- };- const assistantMessage = {- id: "assistant-1",- role: "assistant",- parts: [- {- type: "data-status",- data: { message: "Contacting the model..." },- },- ],- };-- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({- messages: [userMessage, assistantMessage],- isRestoringActiveSession: true,- }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());-- const { result } = renderHook(() => useCopilotPage());-- expect(result.current.messages).toEqual([userMessage]);- expect(result.current.restoreStatusMessage).toBe("Contacting the model...");- });-- it("prefers the cached live snapshot while restore is still reconnecting", () => {- const userMessage: UIMessage = {- id: "user-1",- role: "user",- parts: [{ type: "text", text: "Tell me more" }],- };- const cachedAssistantMessage: UIMessage = {- id: "assistant-1",- role: "assistant",- parts: [{ type: "reasoning", text: "Working on it" }],- };-- useCopilotStreamStore- .getState()- .setMessageSnapshot("sess-1", [userMessage, cachedAssistantMessage]);-- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({- messages: [userMessage],- isRestoringActiveSession: true,- }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());-- const { result } = renderHook(() => useCopilotPage());-- expect(result.current.messages).toEqual([- userMessage,- cachedAssistantMessage,- ]);- });-});--describe("useCopilotPage — onEnqueue and queuedMessages", () => {- beforeEach(() => {- vi.clearAllMocks();- useCopilotStreamStore.getState().resetAll();- });-- it("exposes onEnqueue (delegating to onSend) and queuedMessages", () => {- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(makeBaseCopilotStream());- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());-- const { result } = renderHook(() => useCopilotPage());-- expect(typeof result.current.onEnqueue).toBe("function");- expect(Array.isArray(result.current.queuedMessages)).toBe(true);- });-});--describe("useCopilotPage — turnStats map merge across pages", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("merges historical (current-page) over paged (older) stats; current-page wins on overlap", () => {- const pagedTurnStats = new Map([- ["older", { durationMs: 1000, createdAt: "2026-04-20T10:00:00Z" }],- ["shared", { durationMs: 2000, createdAt: "2026-04-20T10:00:00Z" }],- ]);- const historicalTurnStats = new Map([- ["current", { durationMs: 3000, createdAt: "2026-04-23T08:32:09Z" }],- ["shared", { durationMs: 4000, createdAt: "2026-04-23T08:32:09Z" }],- ]);-- mockUseChatSession.mockReturnValue(- makeBaseChatSession({ historicalTurnStats }),- );- mockUseCopilotStream.mockReturnValue(makeBaseCopilotStream());- mockUseLoadMoreMessages.mockReturnValue(- makeBaseLoadMore({ pagedTurnStats }),- );-- const { result } = renderHook(() => useCopilotPage());- const stats = result.current.turnStats;-- expect(stats.get("older")).toEqual({- durationMs: 1000,- createdAt: "2026-04-20T10:00:00Z",- });- expect(stats.get("current")).toEqual({- durationMs: 3000,- createdAt: "2026-04-23T08:32:09Z",- });- // Current-page wins on shared keys.- expect(stats.get("shared")).toEqual({- durationMs: 4000,- createdAt: "2026-04-23T08:32:09Z",- });- });-});--describe("useCopilotPage — onSend queue-in-flight path", () => {- beforeEach(() => {- vi.clearAllMocks();- useCopilotStreamStore.getState().resetAll();- });-- it("rejects attaching files while a turn is in flight", async () => {- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({ status: "streaming" }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());-- const { result } = renderHook(() => useCopilotPage());-- const bigFile = new File(["x"], "doc.txt", { type: "text/plain" });- await act(async () => {- await result.current.onSend("hello", [bigFile]);- });-- expect(mockQueueFollowUpMessage).not.toHaveBeenCalled();- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({ title: "Please wait to attach files" }),- );- });-- it("queues a text-only message via queueFollowUpMessage when in flight", async () => {- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({ status: "streaming" }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());- mockQueueFollowUpMessage.mockResolvedValue({- buffer_length: 1,- max_buffer_length: 10,- turn_in_flight: true,- });-- const { result } = renderHook(() => useCopilotPage());-- await act(async () => {- await result.current.onSend("follow-up");- });-- expect(mockQueueFollowUpMessage).toHaveBeenCalledWith(- "sess-1",- "follow-up",- );- // queueMessage should have been called, bringing the entry into queuedMessages.- await waitFor(() => {- expect(result.current.queuedMessages).toContain("follow-up");- });- });-- it("falls back to a normal send when the active turn has already ended", async () => {- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({ status: "streaming" }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());- const notActiveError = new Error("no active turn");- notActiveError.name = "QueueFollowUpNotActiveError";- mockQueueFollowUpMessage.mockRejectedValue(notActiveError);-- const { result } = renderHook(() => useCopilotPage());-- await act(async () => {- await result.current.onSend("follow-up");- });-- expect(mockQueueFollowUpMessage).toHaveBeenCalledWith(- "sess-1",- "follow-up",- );- expect(mockSendNewMessage).toHaveBeenCalledWith("follow-up", undefined);- expect(result.current.queuedMessages).not.toContain("follow-up");- expect(mockToast).not.toHaveBeenCalledWith(- expect.objectContaining({ title: "Could not queue message" }),- );- });-- it("treats a user-stopped turn as no longer in flight for new sends", async () => {- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({- status: "streaming",- isUserStopping: true,- }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());-- const { result } = renderHook(() => useCopilotPage());-- await act(async () => {- await result.current.onSend("follow-up");- });-- expect(mockQueueFollowUpMessage).not.toHaveBeenCalled();- expect(mockSendNewMessage).toHaveBeenCalledWith("follow-up", undefined);- });-- it("surfaces a toast and rethrows when the queue POST fails", async () => {- mockUseChatSession.mockReturnValue(makeBaseChatSession());- mockUseCopilotStream.mockReturnValue(- makeBaseCopilotStream({ status: "streaming" }),- );- mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());- mockQueueFollowUpMessage.mockRejectedValue(new Error("boom"));-- const { result } = renderHook(() => useCopilotPage());-- await act(async () => {- await expect(result.current.onSend("follow-up")).rejects.toThrow(/boom/);- });-- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({ title: "Could not queue message" }),- );- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.tsdeleted file mode 100644index 0a0841f71c..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.ts+++ /dev/null@@ -1,464 +0,0 @@-import { act, renderHook, waitFor } from "@testing-library/react";-import type { UIMessage } from "ai";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--// ── Mock the generated API endpoint so we can control peek responses. ──-const peekMock = vi.fn();-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- getV2GetPendingMessages: (...args: unknown[]) => peekMock(...args),-}));--// Import AFTER mocks are declared.-import { useCopilotPendingChips } from "../useCopilotPendingChips";--function user(id: string, text?: string): UIMessage {- return {- id,- role: "user",- parts: [- {- type: "text" as const,- text: text ?? `user-${id}`,- state: "done" as const,- },- ],- };-}--function assistant(id: string, text?: string): UIMessage {- return {- id,- role: "assistant",- parts: [- {- type: "text" as const,- text: text ?? `assistant-${id}`,- state: "done" as const,- },- ],- };-}--describe("useCopilotPendingChips", () => {- beforeEach(() => {- peekMock.mockReset();- peekMock.mockResolvedValue({- status: 200,- data: { count: 0, messages: [] },- });- });- afterEach(() => {- vi.useRealTimers();- });-- it("restores chips from backend peek on session load", async () => {- peekMock.mockResolvedValueOnce({- status: 200,- data: { count: 2, messages: ["first", "second"] },- });-- const setMessages = vi.fn();- const { result } = renderHook(() =>- useCopilotPendingChips({- sessionId: "sess-1",- status: "ready",- messages: [],- setMessages,- }),- );-- await waitFor(() => {- expect(result.current.queuedMessages).toEqual(["first", "second"]);- });- });-- it("clears chips when the session changes", async () => {- // Initial session returns 2 chips.- peekMock.mockResolvedValueOnce({- status: 200,- data: { count: 2, messages: ["a", "b"] },- });- const setMessages = vi.fn();- const { result, rerender } = renderHook(- ({ sessionId }: { sessionId: string | null }) =>- useCopilotPendingChips({- sessionId,- status: "ready",- messages: [],- setMessages,- }),- { initialProps: { sessionId: "sess-1" } },- );-- await waitFor(() => {- expect(result.current.queuedMessages).toHaveLength(2);- });-- // Next session's peek returns no chips.- peekMock.mockResolvedValueOnce({- status: 200,- data: { count: 0, messages: [] },- });- rerender({ sessionId: "sess-2" });-- await waitFor(() => {- expect(result.current.queuedMessages).toEqual([]);- });- });-- it("queueMessage adds a chip locally without hitting backend", () => {- const setMessages = vi.fn();- const { result } = renderHook(() =>- useCopilotPendingChips({- sessionId: "s",- status: "ready",- messages: [],- setMessages,- }),- );-- act(() => {- result.current.queueMessage("hello");- });- expect(result.current.queuedMessages).toEqual(["hello"]);- });-- it("promotes one bubble per chip when a second new assistant appears (auto-continue)", () => {- const setMessages = vi.fn();-- const { result, rerender } = renderHook(- ({ messages }: { messages: UIMessage[] }) =>- useCopilotPendingChips({- sessionId: "s",- status: "streaming",- messages,- setMessages,- }),- { initialProps: { messages: [user("u1")] } },- );-- // First assistant appears → opener; no promotion (correctly).- rerender({- messages: [user("u1"), assistant("a1", "turn1")],- });-- // User queues two distinct chips while turn 1 is still streaming.- act(() => {- result.current.queueMessage("followup-a");- result.current.queueMessage("followup-b");- });-- setMessages.mockClear();-- // A SECOND new assistant id appears → auto-continue detected.- rerender({- messages: [- user("u1"),- assistant("a1", "turn1"),- assistant("a2", "turn2"),- ],- });-- const promoteCall = setMessages.mock.calls.find(- ([fn]) => typeof fn === "function",- );- expect(promoteCall).toBeDefined();-- const updater = promoteCall![0] as (prev: UIMessage[]) => UIMessage[];- const after = updater([user("u1"), assistant("a1"), assistant("a2")]);-- // One bubble per chip — cardinality preserved.- const promoted = after.filter((m) =>- m.id.startsWith("promoted-auto-continue-"),- );- expect(promoted).toHaveLength(2);- expect(- promoted.map((m) => (m.parts![0] as { text?: string }).text),- ).toEqual(["followup-a", "followup-b"]);-- // Both bubbles inserted before a2.- const a2Idx = after.findIndex((m) => m.id === "a2");- const promotedIndices = promoted.map((m) =>- after.findIndex((x) => x.id === m.id),- );- expect(promotedIndices.every((i) => i < a2Idx)).toBe(true);-- // Chips cleared.- expect(result.current.queuedMessages).toEqual([]);- });-- it("turn-start drain: peek count=0 clears chips once submitted→streaming", async () => {- const setMessages = vi.fn();- peekMock.mockResolvedValueOnce({- status: 200,- data: { count: 1, messages: ["local-chip"] },- });-- type StatusProps = {- status: "ready" | "submitted" | "streaming";- };- const { result, rerender } = renderHook<- ReturnType<typeof useCopilotPendingChips>,- StatusProps- >(- ({ status }) =>- useCopilotPendingChips({- sessionId: "s",- status,- messages: [],- setMessages,- }),- { initialProps: { status: "ready" } },- );-- await waitFor(() => {- expect(result.current.queuedMessages).toEqual(["local-chip"]);- });-- rerender({ status: "submitted" });- peekMock.mockResolvedValue({- status: 200,- data: { count: 0, messages: [] },- });- rerender({ status: "streaming" });-- await waitFor(() => {- expect(result.current.queuedMessages).toEqual([]);- });- });-- it("turn-start drain: non-200 peek response does not clear chips", async () => {- const setMessages = vi.fn();- peekMock.mockResolvedValueOnce({- status: 200,- data: { count: 1, messages: ["keep-me"] },- });-- type StatusProps = {- status: "ready" | "submitted" | "streaming";- };- const { result, rerender } = renderHook<- ReturnType<typeof useCopilotPendingChips>,- StatusProps- >(- ({ status }) =>- useCopilotPendingChips({- sessionId: "s",- status,- messages: [],- setMessages,- }),- { initialProps: { status: "ready" } },- );-- await waitFor(() => {- expect(result.current.queuedMessages).toEqual(["keep-me"]);- });-- rerender({ status: "submitted" });- peekMock.mockResolvedValue({ status: 500, data: undefined });- rerender({ status: "streaming" });-- await act(async () => {- await Promise.resolve();- await Promise.resolve();- });-- expect(result.current.queuedMessages).toEqual(["keep-me"]);- });-- it("mid-turn poll: peek error is swallowed and chips are preserved", async () => {- vi.useFakeTimers();- const setMessages = vi.fn();- const { result } = renderHook(() =>- useCopilotPendingChips({- sessionId: "s",- status: "streaming",- messages: [user("u1"), assistant("a1")],- setMessages,- }),- );-- act(() => {- result.current.queueMessage("survives");- });-- peekMock.mockRejectedValue(new Error("network blip"));-- await act(async () => {- vi.advanceTimersByTime(2_000);- await Promise.resolve();- await Promise.resolve();- });-- expect(result.current.queuedMessages).toEqual(["survives"]);- const promoteCall = setMessages.mock.calls.find(([arg]) => {- if (typeof arg !== "function") return false;- const updated = (arg as (p: UIMessage[]) => UIMessage[])([]);- return updated.some((m) => m.id.startsWith("promoted-"));- });- expect(promoteCall).toBeUndefined();- });-- it("mid-turn poll promotes one bubble per drained chip", async () => {- vi.useFakeTimers();- const setMessages = vi.fn();- const { result } = renderHook(() =>- useCopilotPendingChips({- sessionId: "s",- status: "streaming",- messages: [user("u1"), assistant("a1")],- setMessages,- }),- );-- act(() => {- result.current.queueMessage("chipA");- result.current.queueMessage("chipB");- });-- peekMock.mockResolvedValue({- status: 200,- data: { count: 0, messages: [] },- });-- await act(async () => {- vi.advanceTimersByTime(2_000);- await Promise.resolve();- await Promise.resolve();- });-- const promotedCall = setMessages.mock.calls.find(([arg]) => {- if (typeof arg !== "function") return false;- const updated = (arg as (p: UIMessage[]) => UIMessage[])([]);- return updated.some((m) => m.id.startsWith("promoted-midturn-"));- });- expect(promotedCall).toBeDefined();-- const streamingUpdater = promotedCall![0] as (- prev: UIMessage[],- ) => UIMessage[];- const priorMessages = [user("u1"), assistant("a1", "streaming...")];- const afterPromotion = streamingUpdater(priorMessages);-- // Two chips → two bubbles, both inserted before the streaming assistant.- expect(afterPromotion).toHaveLength(4);- const lastIdx = afterPromotion.length - 1;- expect(afterPromotion[lastIdx].role).toBe("assistant");- expect(afterPromotion[lastIdx].id).toBe("a1");- const promoted = afterPromotion.filter((m) =>- m.id.startsWith("promoted-midturn-"),- );- expect(promoted).toHaveLength(2);- expect(- promoted.map((m) => (m.parts![0] as { text?: string }).text),- ).toEqual(["chipA", "chipB"]);-- expect(result.current.queuedMessages).toEqual([]);- });-- it("mid-turn poll: a peek that resolves after the user switches sessions does not promote into the new session", async () => {- vi.useFakeTimers();- const setMessagesA = vi.fn();- const setMessagesB = vi.fn();- type Props = { sessionId: string; setMessages: typeof setMessagesA };- const { result, rerender } = renderHook<- ReturnType<typeof useCopilotPendingChips>,- Props- >(- ({ sessionId, setMessages }) =>- useCopilotPendingChips({- sessionId,- status: "streaming",- messages: [user("u1"), assistant("a1")],- setMessages,- }),- {- initialProps: { sessionId: "sess-A", setMessages: setMessagesA },- },- );-- act(() => {- result.current.queueMessage("chipA");- });-- // Poll fires for sess-A but resolves AFTER we've switched to sess-B.- let resolvePeek!: (value: unknown) => void;- peekMock.mockImplementationOnce(- () =>- new Promise((resolve) => {- resolvePeek = resolve;- }),- );-- await act(async () => {- vi.advanceTimersByTime(2_000);- });-- // User switches sessions.- rerender({ sessionId: "sess-B", setMessages: setMessagesB });-- // Old poll resolves now — backend says count=0 — but we've already- // moved on to sess-B. The session-id guard must short-circuit so- // setMessagesA is never called for the promotion path.- setMessagesA.mockClear();- await act(async () => {- resolvePeek({ status: 200, data: { count: 0, messages: [] } });- await Promise.resolve();- await Promise.resolve();- });-- const promotedCallA = setMessagesA.mock.calls.find(([arg]) => {- if (typeof arg !== "function") return false;- const updated = (arg as (p: UIMessage[]) => UIMessage[])([]);- return updated.some((m) => m.id.startsWith("promoted-"));- });- expect(promotedCallA).toBeUndefined();- });-- it("mid-turn poll: chip appended during in-flight poll survives the drain", async () => {- vi.useFakeTimers();- const setMessages = vi.fn();- const { result } = renderHook(() =>- useCopilotPendingChips({- sessionId: "s",- status: "streaming",- messages: [user("u1"), assistant("a1")],- setMessages,- }),- );-- act(() => {- result.current.queueMessage("chipA");- });-- // Backend has drained chipA (count=0). The poll's GET resolves, but- // the user appends chipB before the setState commits.- let resolvePeek!: (value: unknown) => void;- peekMock.mockImplementationOnce(- () =>- new Promise((resolve) => {- resolvePeek = resolve;- }),- );-- await act(async () => {- vi.advanceTimersByTime(2_000);- });-- // While the GET is still pending, append a second chip.- act(() => {- result.current.queueMessage("chipB");- });-- // Now resolve the in-flight peek.- await act(async () => {- resolvePeek({ status: 200, data: { count: 0, messages: [] } });- await Promise.resolve();- await Promise.resolve();- });-- // chipA was drained → promoted; chipB survived as a chip.- expect(result.current.queuedMessages).toEqual(["chipB"]);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStop.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStop.test.tsdeleted file mode 100644index 973bd61086..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStop.test.ts+++ /dev/null@@ -1,162 +0,0 @@-import { renderHook } from "@testing-library/react";-import type { UIMessage } from "ai";-import { useRef } from "react";-import { beforeEach, describe, expect, it, vi } from "vitest";--const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => mockToast(...args),-}));--const mockCancel =- vi.fn<(sessionId: string) => Promise<{ status: number; data: unknown }>>();-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- postV2CancelSessionTask: (sessionId: string) => mockCancel(sessionId),-}));--import { useCopilotStop } from "../useCopilotStop";--function asstMessage(parts: UIMessage["parts"], id = "a1"): UIMessage {- return { id, role: "assistant", parts };-}--interface SetupOpts {- sessionId?: string | null;- initialMessages?: UIMessage[];-}--function setup(opts: SetupOpts = {}) {- const sdkStop = vi.fn();- const setIsUserStopping = vi.fn();- let messages: UIMessage[] = opts.initialMessages ?? [];- const setMessages = vi.fn((updater: unknown) => {- if (typeof updater === "function") {- messages = (updater as (prev: UIMessage[]) => UIMessage[])(messages);- } else {- messages = updater as UIMessage[];- }- });-- const { result } = renderHook(() => {- const isUserStoppingRef = useRef(false);- return {- stop: useCopilotStop({- sessionId: "sessionId" in opts ? opts.sessionId! : "sess-1",- sdkStop,- setMessages,- isUserStoppingRef,- setIsUserStopping,- }),- isUserStoppingRef,- };- });-- return {- stop: () => result.current.stop(),- isUserStoppingRef: () => result.current.isUserStoppingRef,- sdkStop,- setMessages,- setIsUserStopping,- getMessages: () => messages,- };-}--describe("useCopilotStop", () => {- beforeEach(() => {- mockToast.mockClear();- mockCancel.mockReset();- });-- it("flips the user-stop flags synchronously and aborts the SDK stream", async () => {- mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });- const { stop, sdkStop, setIsUserStopping, isUserStoppingRef } = setup();-- await stop();-- expect(isUserStoppingRef().current).toBe(true);- expect(setIsUserStopping).toHaveBeenCalledWith(true);- expect(sdkStop).toHaveBeenCalledTimes(1);- });-- it("appends the cancellation marker to the trailing assistant message", async () => {- mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });- const { stop, getMessages } = setup({- initialMessages: [- asstMessage([{ type: "text", text: "partial reply", state: "done" }]),- ],- });-- await stop();- const after = getMessages();- const last = after[after.length - 1];- const tail = last.parts[last.parts.length - 1];- expect(tail.type).toBe("text");- expect((tail as { text: string }).text).toContain("Operation cancelled");- });-- it("leaves messages unchanged when there is no trailing assistant message", async () => {- mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });- const { stop, getMessages } = setup({- initialMessages: [- {- id: "u1",- role: "user",- parts: [{ type: "text", text: "hi", state: "done" }],- },- ],- });-- await stop();- const after = getMessages();- expect(after).toHaveLength(1);- expect(after[0].role).toBe("user");- });-- it("swallows sdkStop errors but still proceeds with cancel", async () => {- mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });- const { stop, sdkStop } = setup();- sdkStop.mockImplementation(() => {- throw new Error("no fetch in flight");- });-- await expect(stop()).resolves.toBeUndefined();- expect(mockCancel).toHaveBeenCalledTimes(1);- });-- it("does not call the cancel endpoint when there is no active sessionId", async () => {- const { stop } = setup({ sessionId: null });- await stop();- expect(mockCancel).not.toHaveBeenCalled();- });-- it("toasts a 'Stop may take a moment' notice on cancel_published_not_confirmed", async () => {- mockCancel.mockResolvedValue({- status: 200,- data: { reason: "cancel_published_not_confirmed" },- });- const { stop } = setup();- await stop();- expect(mockToast).toHaveBeenCalledTimes(1);- expect(mockToast.mock.calls[0][0]).toMatchObject({- title: "Stop may take a moment",- });- });-- it("toasts a destructive notice when the cancel request rejects", async () => {- mockCancel.mockRejectedValue(new Error("network down"));- const { stop } = setup();- await stop();- expect(mockToast).toHaveBeenCalledTimes(1);- expect(mockToast.mock.calls[0][0]).toMatchObject({- title: "Could not stop the task",- variant: "destructive",- });- });-- it("does not toast when the cancel succeeds with a normal reason", async () => {- mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });- const { stop } = setup();- await stop();- expect(mockToast).not.toHaveBeenCalled();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.tsdeleted file mode 100644index 958afb7758..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.ts+++ /dev/null@@ -1,795 +0,0 @@-import { act, cleanup, renderHook } from "@testing-library/react";-import type { UIMessage } from "ai";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--// --- Toast mock (must be stable across rerenders) ----const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => mockToast(...args),-}));--// --- Environment mock ----vi.mock("@/services/environment", () => ({- environment: {- getAGPTServerBaseUrl: () => "http://localhost:8006",- isServerSide: () => false,- },-}));--// --- API endpoints mock ----const mockCancelSessionTask = vi.fn();-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- postV2CancelSessionTask: (...args: unknown[]) =>- mockCancelSessionTask(...args),- getGetV2GetCopilotUsageQueryKey: () => ["usage"],- getGetV2GetSessionQueryKey: (id: string) => ["session", id],-}));--// --- React Query mock ----const mockInvalidateQueries = vi.fn();-vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),-}));--// --- Helpers mock ----const mockHasActiveBackendStream = vi.fn(- (_result: { data?: unknown }) => false,-);-vi.mock("../helpers", () => ({- getCopilotAuthHeaders: vi.fn(async () => ({ Authorization: "Bearer test" })),- deduplicateMessages: (msgs: UIMessage[]) => msgs,- parseSessionIDs: (_raw: string | null | undefined) => new Set<string>(),- extractSendMessageText: (arg: unknown) =>- arg && typeof arg === "object" && "text" in arg- ? String((arg as { text: string }).text)- : String(arg ?? ""),- hasActiveBackendStream: (result: { data?: unknown }) =>- mockHasActiveBackendStream(result),- getLatestAssistantStatusMessage: (messages: UIMessage[]) => {- const last = messages[messages.length - 1];- if (last?.role !== "assistant") return null;- for (let i = last.parts.length - 1; i >= 0; i--) {- const part = last.parts[i] as UIMessage["parts"][number] & {- data?: { message?: unknown };- };- if (part.type === "data-cursor") continue;- if (part.type === "data-status") {- return typeof part.data?.message === "string"- ? part.data.message- : null;- }- return null;- }- return null;- },- hasVisibleAssistantContent: (messages: UIMessage[]) => {- const last = messages[messages.length - 1];- if (last?.role !== "assistant") return false;- return last.parts.some((part: UIMessage["parts"][number]) => {- if (part.type === "text" && part.text.trim().length > 0) return true;- if (part.type === "reasoning" && part.text.trim().length > 0) return true;- if (part.type.startsWith("tool-")) return true;- return false;- });- },- hasInProgressAssistantParts: (message: UIMessage | undefined) => {- if (message?.role !== "assistant") return false;- return message.parts.some((part: UIMessage["parts"][number]) => {- if (!("state" in part) || typeof part.state !== "string") return false;- return (- part.state === "streaming" ||- part.state === "input-streaming" ||- part.state === "input-available"- );- });- },- resolveInProgressTools: (msgs: UIMessage[]) => msgs,- resolveInterruptedMessage: (msgs: UIMessage[]) => msgs,- getSendSuppressionReason: () => null,-}));--// --- ai SDK mock (DefaultChatTransport must be constructible) ----vi.mock("ai", () => ({- DefaultChatTransport: vi.fn().mockImplementation(function () {- return {};- }),-}));--// --- @ai-sdk/react useChat mock with persistent Chat instances ----type UseChatOptions = {- id?: string;- chat?: { id?: string };-};-const capturedUseChatChats: Array<{ id?: string } | undefined> = [];-const mockResumeStream = vi.fn();-const mockSdkStop = vi.fn();-const mockSdkSendMessage = vi.fn();-const mockSetMessages = vi.fn();-let mockMessages: UIMessage[] = [];-let mockStatus: "ready" | "streaming" | "submitted" | "error" = "ready";--vi.mock("@ai-sdk/react", () => ({- Chat: class MockChat {- id: string;- onFinish?: (args: {- isDisconnect?: boolean;- isAbort?: boolean;- }) => void | Promise<void>;- onError?: (error: Error) => void;-- constructor(options: {- id?: string;- onFinish?: (args: {- isDisconnect?: boolean;- isAbort?: boolean;- }) => void | Promise<void>;- onError?: (error: Error) => void;- }) {- this.id = options.id ?? "";- this.onFinish = options.onFinish;- this.onError = options.onError;- }- },- useChat: (opts: UseChatOptions) => {- capturedUseChatChats.push(opts.chat);- return {- messages: mockMessages,- sendMessage: mockSdkSendMessage,- stop: mockSdkStop,- status: mockStatus,- error: undefined,- setMessages: mockSetMessages,- resumeStream: mockResumeStream,- };- },-}));--// Import after mocks-import {- getOrCreateCopilotChatRuntime,- resetCopilotChatRegistry,- shouldReloadCopilotChatRuntime,-} from "../copilotChatRegistry";-import { useCopilotStreamStore } from "../copilotStreamStore";-import { RESTORE_STALL_TIMEOUT_MS } from "../restoreConstants";-import { useCopilotUIStore } from "../store";-import { useCopilotStream } from "../useCopilotStream";--type Args = Parameters<typeof useCopilotStream>[0];--function makeArgs(overrides: Partial<Args> = {}): Args {- return {- sessionId: "sess-1",- hydratedMessages: undefined,- hasActiveStream: false,- refetchSession: vi.fn(async () => ({ data: undefined })),- copilotMode: undefined,- copilotModel: undefined,- ...overrides,- };-}--beforeEach(() => {- vi.useFakeTimers();- mockMessages = [];- mockStatus = "ready";- capturedUseChatChats.length = 0;- mockResumeStream.mockClear();- mockSdkStop.mockClear();- mockSdkSendMessage.mockClear();- mockSetMessages.mockClear();- mockToast.mockClear();- mockHasActiveBackendStream.mockReturnValue(false);- mockInvalidateQueries.mockClear();- resetCopilotChatRegistry();- // Zustand stores are module singletons — wipe per-session coord state so- // tests don't leak into each other.- useCopilotStreamStore.getState().resetAll();-});--afterEach(() => {- vi.useRealTimers();- cleanup();-});--describe("useCopilotStream — hydration/resume race (SECRT-2242)", () => {- it("reuses the same session chat runtime across remounts", () => {- const first = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-1" }),- });- first.unmount();-- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-1" }),- });-- expect(capturedUseChatChats).toHaveLength(2);- expect(capturedUseChatChats[0]?.id).toBe("sess-1");- expect(capturedUseChatChats[1]?.id).toBe("sess-1");- expect(capturedUseChatChats[0]).toBe(capturedUseChatChats[1]);- });-- it("defers resume until hydration completes when hydratedMessages arrives late", () => {- // Arrange: active backend stream, hydration NOT yet complete.- const { rerender } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: undefined,- }),- });-- // Resume effect runs but must wait — no resumeStream fires yet.- expect(mockResumeStream).not.toHaveBeenCalled();-- // Hydration completes: hydratedMessages becomes defined.- rerender(- makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- );-- // pendingResumeRef should have been flushed exactly once.- expect(mockResumeStream).toHaveBeenCalledTimes(1);- });-- it("reports active-session restore until visible content arrives", () => {- const { result, rerender } = renderHook(- (args: Args) => useCopilotStream(args),- {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- },- );-- expect(result.current.isRestoringActiveSession).toBe(true);-- mockStatus = "streaming";- rerender(- makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- );- expect(result.current.isRestoringActiveSession).toBe(true);-- mockMessages = [- {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "Hello" }],- } as unknown as UIMessage,- ];- rerender(- makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- );-- expect(result.current.isRestoringActiveSession).toBe(false);- });-- it("treats a replay status update as enough to leave restore mode", () => {- const { result, rerender } = renderHook(- (args: Args) => useCopilotStream(args),- {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- },- );-- expect(result.current.isRestoringActiveSession).toBe(true);-- mockStatus = "streaming";- mockMessages = [- {- id: "a1",- role: "assistant",- parts: [- {- type: "data-status",- data: { message: "Analyzing result..." },- },- ],- } as unknown as UIMessage,- ];- rerender(- makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- );-- expect(result.current.isRestoringActiveSession).toBe(false);- });-- it("keeps the restore latch closed when hydration lands assistant content while status is still ready", () => {- // Repro for the premature-latch bug: the user reopens a session whose- // backend stream is still active, hydration lands a partial assistant- // message persisted mid-stream into rawMessages, but the live SSE- // GET-resume hasn't produced any bytes yet (status still ``ready``).- // The latch must NOT fire — otherwise the "Retrieving latest messages"- // UI is suppressed and the 6 s restore-stall watchdog can't run.- mockStatus = "ready";- mockMessages = [- {- id: "u1",- role: "user",- parts: [{ type: "text", text: "Hi" }],- } as unknown as UIMessage,- {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "Partial response" }],- } as unknown as UIMessage,- ];-- const { result, rerender } = renderHook(- (args: Args) => useCopilotStream(args),- {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- },- );-- expect(result.current.isRestoringActiveSession).toBe(true);-- // Once the live stream actually flips status to ``streaming`` (resume- // produced its first byte), the latch is allowed to fire.- mockStatus = "streaming";- rerender(- makeArgs({- hasActiveStream: true,- hydratedMessages: [],- }),- );-- expect(result.current.isRestoringActiveSession).toBe(false);- });-- it("kicks the reconnect cascade when restore stays stuck for 6 seconds", async () => {- mockHasActiveBackendStream.mockReturnValue(true);- const refetchSession = vi.fn(async () => ({- data: { status: 200, data: { active_stream: { started_at: "now" } } },- }));-- const { rerender } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [],- refetchSession,- }),- });-- expect(mockResumeStream).toHaveBeenCalledTimes(1);-- mockStatus = "streaming";- rerender(- makeArgs({- hasActiveStream: true,- hydratedMessages: [],- refetchSession,- }),- );-- await act(async () => {- await vi.advanceTimersByTimeAsync(RESTORE_STALL_TIMEOUT_MS + 1_000);- });-- expect(refetchSession).toHaveBeenCalled();- expect(mockResumeStream).toHaveBeenCalledTimes(2);- });-- it("stores the latest per-session snapshot without wiping it on an empty remount", () => {- const userMessage: UIMessage = {- id: "u1",- role: "user",- parts: [{ type: "text", text: "hello", state: "done" }],- };- const assistantMessage: UIMessage = {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "partial", state: "streaming" }],- };- mockMessages = [userMessage, assistantMessage];-- const first = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [userMessage, assistantMessage],- }),- });-- expect(- useCopilotStreamStore.getState().getMessageSnapshot("sess-1"),- ).toEqual([userMessage, assistantMessage]);-- first.unmount();- mockMessages = [];-- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [userMessage, assistantMessage],- }),- });-- expect(- useCopilotStreamStore.getState().getMessageSnapshot("sess-1"),- ).toEqual([userMessage, assistantMessage]);- });-- it("does not double-resume when hydration arrives after an already-queued resume", () => {- const { rerender } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: undefined,- }),- });-- // Hydration completes once — pending resume flushes.- rerender(makeArgs({ hasActiveStream: true, hydratedMessages: [] }));- expect(mockResumeStream).toHaveBeenCalledTimes(1);-- // Subsequent rerender with the same hydration must not re-trigger resume- // because hasResumedRef is now set for this mount.- rerender(makeArgs({ hasActiveStream: true, hydratedMessages: [] }));- expect(mockResumeStream).toHaveBeenCalledTimes(1);- });-- it("resumes immediately when hydration completed before the active-stream flag flipped on", () => {- const { rerender } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: false,- hydratedMessages: [],- }),- });-- expect(mockResumeStream).not.toHaveBeenCalled();-- rerender(makeArgs({ hasActiveStream: true, hydratedMessages: [] }));-- expect(mockResumeStream).toHaveBeenCalledTimes(1);- });-- it("drops a trailing assistant snapshot before full replay resume", () => {- const userMessage: UIMessage = {- id: "u1",- role: "user",- parts: [{ type: "text", text: "hello", state: "done" }],- };- const assistantMessage: UIMessage = {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "partial", state: "streaming" }],- };- mockMessages = [userMessage, assistantMessage];-- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [userMessage, assistantMessage],- }),- });-- const messageUpdaters = mockSetMessages.mock.calls- .map(([arg]) => arg)- .filter((arg) => typeof arg === "function") as Array<- (messages: UIMessage[]) => UIMessage[]- >;- const resumeUpdater = messageUpdaters[messageUpdaters.length - 1];-- expect(resumeUpdater?.([userMessage, assistantMessage])).toEqual([- userMessage,- ]);- expect(mockResumeStream).toHaveBeenCalledTimes(1);- });-- it("keeps a completed trailing assistant before full replay resume", () => {- const userMessage: UIMessage = {- id: "u1",- role: "user",- parts: [{ type: "text", text: "hello", state: "done" }],- };- const assistantMessage: UIMessage = {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "final", state: "done" }],- };- mockMessages = [userMessage, assistantMessage];-- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({- hasActiveStream: true,- hydratedMessages: [userMessage, assistantMessage],- }),- });-- const messageUpdaters = mockSetMessages.mock.calls- .map(([arg]) => arg)- .filter((arg) => typeof arg === "function") as Array<- (messages: UIMessage[]) => UIMessage[]- >;- const resumeUpdater = messageUpdaters[messageUpdaters.length - 1];-- expect(resumeUpdater?.([userMessage, assistantMessage])).toEqual([- userMessage,- assistantMessage,- ]);- expect(mockResumeStream).toHaveBeenCalledTimes(1);- });-});--describe("useCopilotStream — unmount cleanup", () => {- it("keeps the in-flight fetch alive on unmount", () => {- const { unmount } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-A" }),- });-- unmount();-- expect(mockSdkStop).not.toHaveBeenCalled();- });-- it("reconnect timer does not fire resumeStream after unmount", async () => {- const { unmount } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-A" }),- });-- await act(async () => {- await getOrCreateCopilotChatRuntime("sess-A").onFinish?.({- isDisconnect: true,- });- });-- // Parent would remount us with a new session key — simulate the- // unmount that happens before the reconnect timer backoff expires.- unmount();-- await act(async () => {- await vi.advanceTimersByTimeAsync(5_000);- });-- expect(mockResumeStream).not.toHaveBeenCalled();- });-- it("marks a background-disconnected session for full reload on reopen", async () => {- useCopilotStreamStore- .getState()- .updateCoord("sess-A", { lastSubmittedMessageText: "hello" });- useCopilotStreamStore.getState().setMessageSnapshot("sess-A", [- {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "partial" }],- } as unknown as UIMessage,- ]);-- const firstRuntime = getOrCreateCopilotChatRuntime("sess-A");- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-A" }),- }).unmount();-- await act(async () => {- await (- firstRuntime.chat as unknown as {- onFinish?: (args: { isDisconnect?: boolean }) => Promise<void> | void;- }- ).onFinish?.({ isDisconnect: true });- });-- expect(shouldReloadCopilotChatRuntime("sess-A")).toBe(true);- expect(- useCopilotStreamStore.getState().getMessageSnapshot("sess-A"),- ).toEqual([]);- expect(- useCopilotStreamStore.getState().getCoord("sess-A")- .lastSubmittedMessageText,- ).toBeNull();-- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-A" }),- });-- expect(capturedUseChatChats.at(-1)).not.toBe(firstRuntime.chat);- expect(shouldReloadCopilotChatRuntime("sess-A")).toBe(false);- });-});--describe("useCopilotStream — forced reconnect timeout (SECRT-2241)", () => {- it("forces UI back to idle after 30s of continuous reconnection", async () => {- const refetchSession = vi.fn(async () => ({ data: undefined }));- const { result } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ refetchSession }),- });-- // Kick off reconnect via a disconnect finish.- await act(async () => {- await getOrCreateCopilotChatRuntime("sess-1").onFinish?.({- isDisconnect: true,- });- });-- // Initially reconnect is scheduled — but we won't let it succeed. Instead- // advance exactly 30s so the forced-timeout callback fires.- mockToast.mockClear();- await act(async () => {- await vi.advanceTimersByTimeAsync(30_000);- });-- // Forced timeout should have fired its toast.- const timeoutToast = mockToast.mock.calls.find(- ([call]) => (call as { title?: string }).title === "Connection timed out",- );- expect(timeoutToast).toBeDefined();-- // isReconnecting should flip back to false once reconnectExhausted is set.- expect(result.current.isReconnecting).toBe(false);- });-- it("forced-timeout does not fire after unmount", async () => {- const { unmount } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs(),- });-- await act(async () => {- await getOrCreateCopilotChatRuntime("sess-1").onFinish?.({- isDisconnect: true,- });- });-- // Parent remounts on session switch — the old mount unmounts. Any- // pending timers belong to that mount and must not fire toasts after- // its teardown.- unmount();-- mockToast.mockClear();- await act(async () => {- await vi.advanceTimersByTimeAsync(30_000);- });-- const timeoutToast = mockToast.mock.calls.find(- ([call]) => (call as { title?: string }).title === "Connection timed out",- );- expect(timeoutToast).toBeUndefined();- });-});--// Cursor tracking for incremental resume was removed — resume always replays-// from "0-0" because AI SDK v5's UIMessageStream parser throws on orphan-// `*-delta` / `*-end` chunks, and a cursor-based XREAD skips the envelope +-// `*-start` chunks that precede the cursor. See copilotStreamTransport.ts.--describe("useCopilotStream — mount preserves session runtime state", () => {- it("does not clear the chat runtime on mount", () => {- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-A" }),- });-- expect(mockSetMessages).not.toHaveBeenCalledWith([]);- });-});--describe("useCopilotStream — rate-limit recovery", () => {- it("restores the unsent text and drops the optimistic user bubble on 429 usage-limit", async () => {- useCopilotUIStore.getState().setInitialPrompt(null);- useCopilotStreamStore- .getState()- .updateCoord("sess-1", { lastSubmittedMessageText: "recover me" });-- const { result } = renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-1" }),- });-- await act(async () => {- await getOrCreateCopilotChatRuntime("sess-1").onError?.(- new Error(JSON.stringify({ detail: "Daily usage limit exceeded" })),- );- });-- expect(useCopilotUIStore.getState().initialPrompt).toBe("recover me");- expect(result.current.rateLimitMessage).toContain("Daily usage limit");- expect(- useCopilotStreamStore.getState().getCoord("sess-1")- .lastSubmittedMessageText,- ).toBeNull();-- const dropCall = mockSetMessages.mock.calls.find(([arg]) => {- if (typeof arg !== "function") return false;- const prev: UIMessage[] = [- {- id: "u1",- role: "user",- parts: [{ type: "text", text: "recover me" }],- } as unknown as UIMessage,- ];- const next = (arg as (p: UIMessage[]) => UIMessage[])(prev);- return next.length === 0;- });- expect(dropCall).toBeTruthy();-- // Branch: when the trailing message is NOT a user bubble (e.g. an- // assistant turn already landed), the rollback updater must leave the- // list untouched so we don't clobber the assistant reply.- const updater = mockSetMessages.mock.calls- .map(([arg]) => arg)- .find(- (arg): arg is (p: UIMessage[]) => UIMessage[] =>- typeof arg === "function",- );- expect(updater).toBeDefined();- const assistantOnly: UIMessage[] = [- {- id: "a1",- role: "assistant",- parts: [{ type: "text", text: "ok" }],- } as unknown as UIMessage,- ];- expect(updater!(assistantOnly)).toBe(assistantOnly);- expect(updater!([])).toEqual([]);- });-- it("skips composer restore on 429 when there is no captured unsent text", async () => {- useCopilotUIStore.getState().setInitialPrompt(null);- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-1" }),- });-- await act(async () => {- await getOrCreateCopilotChatRuntime("sess-1").onError?.(- new Error(JSON.stringify({ detail: "Daily usage limit exceeded" })),- );- });-- // No prior sendMessage → coord lastSubmittedMessageText stays null →- // restore branch must be skipped. The store stays untouched and- // setMessages is NOT invoked with a rollback updater.- expect(useCopilotUIStore.getState().initialPrompt).toBeNull();- const rollbackUpdaterCall = mockSetMessages.mock.calls.find(- ([arg]) => typeof arg === "function",- );- expect(rollbackUpdaterCall).toBeUndefined();- });-- it("preserves the unsent text in the store when the user is already typing a new draft", async () => {- useCopilotUIStore.getState().setInitialPrompt(null);- useCopilotStreamStore- .getState()- .updateCoord("sess-1", { lastSubmittedMessageText: "rate-limited" });-- const composer = document.createElement("textarea");- composer.id = "chat-input";- composer.value = "user is typing a new draft";- document.body.appendChild(composer);-- try {- renderHook((args: Args) => useCopilotStream(args), {- initialProps: makeArgs({ sessionId: "sess-1" }),- });-- await act(async () => {- await getOrCreateCopilotChatRuntime("sess-1").onError?.(- new Error(JSON.stringify({ detail: "Daily usage limit exceeded" })),- );- });-- // Composer non-empty → don't write to the recovery slot, don't clear- // the per-session unsent buffer. The user keeps their draft and the- // rate-limited text stays available for a future reload/resume.- expect(useCopilotUIStore.getState().initialPrompt).toBeNull();- expect(- useCopilotStreamStore.getState().getCoord("sess-1")- .lastSubmittedMessageText,- ).toBe("rate-limited");- } finally {- document.body.removeChild(composer);- }- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.tsdeleted file mode 100644index ea06d1c4d5..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts+++ /dev/null@@ -1,441 +0,0 @@-import { renderHook } from "@testing-library/react";-import type { UIMessage } from "ai";-import { describe, expect, it, vi } from "vitest";--const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => mockToast(...args),-}));--import {- _resetInterruptedToastLedgerForTests,- useHydrateOnStreamEnd,-} from "../useHydrateOnStreamEnd";--/** Use distinct default text per id so the assistant dedup doesn't collapse them. */-function msg(id: string, text?: string): UIMessage {- return {- id,- role: "assistant",- parts: [- {- type: "text" as const,- text: text ?? `text-${id}`,- state: "done" as const,- },- ],- };-}--describe("useHydrateOnStreamEnd", () => {- it("does nothing while streaming", () => {- const setMessages = vi.fn();- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: null,- status: "streaming",- hydratedMessages: [msg("a")],- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );- expect(setMessages).not.toHaveBeenCalled();- });-- it("does nothing while a reconnect is scheduled", () => {- const setMessages = vi.fn();- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: null,- status: "ready",- hydratedMessages: [msg("a")],- isReconnectScheduled: true,- hasActiveStream: false,- setMessages,- }),- );- expect(setMessages).not.toHaveBeenCalled();- });-- it("length-gated top-up when there is no pending force-hydrate", () => {- // Fresh mount at "ready" → force-hydrate was never armed.- // The hook should top up only if the fresh data is strictly larger.- const setMessages = vi.fn();- const fresh = [msg("a"), msg("b"), msg("c")];- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: null,- status: "ready",- hydratedMessages: fresh,- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );- expect(setMessages).toHaveBeenCalledTimes(1);- // setMessages was called with an updater — invoke with a short prev.- const updater = setMessages.mock.calls[0][0] as (- prev: UIMessage[],- ) => UIMessage[];- expect(updater([msg("x")])).toHaveLength(3);- // And with a longer prev, no-op.- expect(updater([msg("x"), msg("y"), msg("z"), msg("w")])).toHaveLength(4);- });-- it("waits for fresh reference after streaming→ready, then force-hydrates", () => {- const setMessages = vi.fn();- const staleSnapshot = [msg("s1")];-- const { rerender } = renderHook(- ({- status,- hydratedMessages,- }: {- status: "streaming" | "ready";- hydratedMessages: UIMessage[];- }) =>- useHydrateOnStreamEnd({- sessionId: null,- status,- hydratedMessages,- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- {- initialProps: {- status: "streaming",- hydratedMessages: staleSnapshot,- },- },- );-- // While streaming, no hydration activity.- expect(setMessages).not.toHaveBeenCalled();-- // Flip to ready with the SAME hydrated reference (stale) — the force-- // hydrate flag is armed, but we must not overwrite yet.- rerender({ status: "ready", hydratedMessages: staleSnapshot });- expect(setMessages).not.toHaveBeenCalled();-- // New reference arrives → force-hydrate runs once.- const fresh = [msg("s1"), msg("s2")];- rerender({ status: "ready", hydratedMessages: fresh });- expect(setMessages).toHaveBeenCalledTimes(1);- const updater = setMessages.mock.calls[0][0];- // Force-hydrate uses an updater so it can preserve any in-flight- // promoted-* user bubbles whose text isn't in the hydrated DB rows.- expect(typeof updater).toBe("function");- expect(- (updater as (prev: UIMessage[]) => UIMessage[])([]).map((m) => m.id),- ).toEqual(["s1", "s2"]);-- // Subsequent rerender with same fresh ref → no additional call.- rerender({ status: "ready", hydratedMessages: fresh });- expect(setMessages).toHaveBeenCalledTimes(1);- });-- it("preserves promoted user bubbles whose text isn't in the hydrated DB rows", () => {- // Simulates: Claude saw a queued message via mid-turn injection but the- // persist rolled back, so the DB has no matching user row. We must NOT- // drop the in-flight bubble during force-hydrate.- const setMessages = vi.fn();- const stale = [msg("a")];- const { rerender } = renderHook(- ({- status,- hydratedMessages,- }: {- status: "submitted" | "streaming" | "ready" | "error";- hydratedMessages: UIMessage[];- }) =>- useHydrateOnStreamEnd({- sessionId: null,- status,- hydratedMessages,- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- { initialProps: { status: "streaming", hydratedMessages: stale } },- );-- // Arm force-hydrate, then drop in a fresh hydrated reference.- rerender({ status: "ready", hydratedMessages: stale });- const fresh = [msg("a"), msg("b")];- rerender({ status: "ready", hydratedMessages: fresh });- expect(setMessages).toHaveBeenCalledTimes(1);-- const updater = setMessages.mock.calls[0][0] as (- prev: UIMessage[],- ) => UIMessage[];-- const promoted: UIMessage = {- id: "promoted-midturn-xyz",- role: "user",- parts: [{ type: "text", text: "queued message", state: "done" }],- };- const result = updater([msg("a"), promoted, msg("b")]);- // Promoted bubble survives because no hydrated user message contains its text.- expect(result.map((m) => m.id)).toEqual(["a", "b", "promoted-midturn-xyz"]);- });-- it("drops promoted bubbles whose text is already represented in the DB", () => {- const setMessages = vi.fn();- const stale = [msg("a")];- const { rerender } = renderHook(- ({- status,- hydratedMessages,- }: {- status: "submitted" | "streaming" | "ready" | "error";- hydratedMessages: UIMessage[];- }) =>- useHydrateOnStreamEnd({- sessionId: null,- status,- hydratedMessages,- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- { initialProps: { status: "streaming", hydratedMessages: stale } },- );-- rerender({ status: "ready", hydratedMessages: stale });- const persistedUser: UIMessage = {- id: "session-seq-3",- role: "user",- parts: [{ type: "text", text: "queued message", state: "done" }],- };- const fresh = [msg("a"), persistedUser, msg("b")];- rerender({ status: "ready", hydratedMessages: fresh });-- const updater = setMessages.mock.calls[0][0] as (- prev: UIMessage[],- ) => UIMessage[];-- const promoted: UIMessage = {- id: "promoted-midturn-xyz",- role: "user",- parts: [{ type: "text", text: "queued message", state: "done" }],- };- const result = updater([msg("a"), promoted, msg("b")]);- // No duplicate — DB user row already covers the bubble's text.- expect(result.map((m) => m.id)).toEqual(["a", "session-seq-3", "b"]);- });-- it("ignores undefined or empty hydratedMessages", () => {- const setMessages = vi.fn();- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: null,- status: "ready",- hydratedMessages: undefined,- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );- expect(setMessages).not.toHaveBeenCalled();- });-- it("resolves in-progress parts + toasts when hydrated state is zombied and no active stream", () => {- mockToast.mockClear();- const setMessages = vi.fn();- const zombie: UIMessage = {- id: "a",- role: "assistant",- parts: [- {- type: "text" as const,- text: "half-written reply",- state: "streaming" as const,- },- ],- };-- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: "zombie-session",- status: "ready",- hydratedMessages: [zombie],- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );-- expect(mockToast).toHaveBeenCalledTimes(1);- expect(mockToast.mock.calls[0][0]).toMatchObject({- title: "Previous response was interrupted",- });- // setMessages is invoked once with a length-gated updater — pass a short- // prev and expect the replaced (finalised) messages back.- expect(setMessages).toHaveBeenCalledTimes(1);- const updater = setMessages.mock.calls[0][0] as (- prev: UIMessage[],- ) => UIMessage[];- const finalised = updater([]);- const last = finalised[finalised.length - 1];- const lastPart = last.parts[last.parts.length - 1];- expect(lastPart.type).toBe("text");- // Last appended part is the interrupted marker.- expect((lastPart as { text: string }).text.includes("interrupted")).toBe(- true,- );- });-- it("leaves zombie parts alone when backend still has active stream", () => {- mockToast.mockClear();- const setMessages = vi.fn();- const partial: UIMessage = {- id: "a",- role: "assistant",- parts: [- {- type: "text" as const,- text: "still writing",- state: "streaming" as const,- },- ],- };-- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: "active-session",- status: "ready",- hydratedMessages: [partial],- isReconnectScheduled: false,- hasActiveStream: true,- setMessages,- }),- );-- expect(mockToast).not.toHaveBeenCalled();- });-- it("does not fire interrupted toast against the pre-turn stale snapshot", () => {- mockToast.mockClear();- _resetInterruptedToastLedgerForTests();-- const setMessages = vi.fn();- const stale: UIMessage[] = [- {- id: "a",- role: "assistant",- parts: [- {- type: "text" as const,- text: "half-written reply",- state: "streaming" as const,- },- ],- },- ];-- const { rerender } = renderHook(- ({- status,- hydratedMessages,- }: {- status: "streaming" | "ready";- hydratedMessages: UIMessage[];- }) =>- useHydrateOnStreamEnd({- sessionId: "sess-stale-toast",- status,- hydratedMessages,- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- { initialProps: { status: "streaming", hydratedMessages: stale } },- );-- // status flip with the SAME stale snapshot — force-hydrate is armed,- // but the data is still the pre-turn ref. Toast must NOT fire here:- // the interrupted bubble may not exist once the refetch lands.- rerender({ status: "ready", hydratedMessages: stale });- expect(mockToast).not.toHaveBeenCalled();- expect(setMessages).not.toHaveBeenCalled();-- // Fresh ref arrives, still has zombie parts → toast fires alongside- // the apply.- const fresh: UIMessage[] = [- {- id: "a",- role: "assistant",- parts: [- {- type: "text" as const,- text: "half-written reply",- state: "streaming" as const,- },- ],- },- ];- rerender({ status: "ready", hydratedMessages: fresh });- expect(mockToast).toHaveBeenCalledTimes(1);- });-- it("only fires the interrupted toast once per session across remounts", () => {- mockToast.mockClear();- _resetInterruptedToastLedgerForTests();-- const setMessages = vi.fn();- const zombie: UIMessage = {- id: "a",- role: "assistant",- parts: [- {- type: "text" as const,- text: "half-written reply",- state: "streaming" as const,- },- ],- };-- // Mount #1 — toast fires.- const first = renderHook(() =>- useHydrateOnStreamEnd({- sessionId: "sess-toast",- status: "ready",- hydratedMessages: [zombie],- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );- expect(mockToast).toHaveBeenCalledTimes(1);- first.unmount();-- // Mount #2 — same sessionId, fresh ref-state but already-shown ledger.- // Reproduces "switch away then back" — useRef would reset and re-toast.- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: "sess-toast",- status: "ready",- hydratedMessages: [zombie],- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );- expect(mockToast).toHaveBeenCalledTimes(1);-- // Different session id → new toast is allowed.- renderHook(() =>- useHydrateOnStreamEnd({- sessionId: "sess-toast-other",- status: "ready",- hydratedMessages: [zombie],- isReconnectScheduled: false,- hasActiveStream: false,- setMessages,- }),- );- expect(mockToast).toHaveBeenCalledTimes(2);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.tsdeleted file mode 100644index 251b5192d7..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.ts+++ /dev/null@@ -1,215 +0,0 @@-import { act, renderHook, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { useLoadMoreMessages } from "../useLoadMoreMessages";--const mockGetV2GetSession = vi.fn();--vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- getV2GetSession: (...args: unknown[]) => mockGetV2GetSession(...args),-}));--vi.mock("../helpers/convertChatSessionToUiMessages", () => ({- convertChatSessionMessagesToUiMessages: vi.fn(() => ({- messages: [],- stats: new Map(),- })),- extractToolOutputsFromRaw: vi.fn(() => []),-}));--const BASE_ARGS = {- sessionId: "sess-1",- initialOldestSequence: 50,- initialHasMore: true,- initialPageRawMessages: [],-};--function makeSuccessResponse(overrides: {- messages?: unknown[];- has_more_messages?: boolean;- oldest_sequence?: number;-}) {- return {- status: 200,- data: {- messages: overrides.messages ?? [],- has_more_messages: overrides.has_more_messages ?? false,- oldest_sequence: overrides.oldest_sequence ?? 0,- },- };-}--describe("useLoadMoreMessages", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("initialises with empty pagedMessages and correct cursors", () => {- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));- expect(result.current.pagedMessages).toHaveLength(0);- expect(result.current.hasMore).toBe(true);- expect(result.current.isLoadingMore).toBe(false);- });-- it("resets all state on sessionId change", () => {- const { result, rerender } = renderHook(- (props) => useLoadMoreMessages(props),- { initialProps: BASE_ARGS },- );-- rerender({- ...BASE_ARGS,- sessionId: "sess-2",- initialOldestSequence: 10,- initialHasMore: false,- });-- expect(result.current.pagedMessages).toHaveLength(0);- expect(result.current.hasMore).toBe(false);- expect(result.current.isLoadingMore).toBe(false);- });-- describe("loadMore — backward pagination", () => {- it("calls getV2GetSession with before_sequence", async () => {- mockGetV2GetSession.mockResolvedValueOnce(- makeSuccessResponse({- messages: [{ role: "user", content: "old", sequence: 0 }],- has_more_messages: false,- oldest_sequence: 0,- }),- );-- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));-- await act(async () => {- await result.current.loadMore();- });-- expect(mockGetV2GetSession).toHaveBeenCalledWith(- "sess-1",- expect.objectContaining({ before_sequence: 50 }),- );- expect(result.current.hasMore).toBe(false);- });-- it("is a no-op when hasMore is false", async () => {- const { result } = renderHook(() =>- useLoadMoreMessages({ ...BASE_ARGS, initialHasMore: false }),- );-- await act(async () => {- await result.current.loadMore();- });-- expect(mockGetV2GetSession).not.toHaveBeenCalled();- });-- it("is a no-op when oldestSequence is null", async () => {- const { result } = renderHook(() =>- useLoadMoreMessages({ ...BASE_ARGS, initialOldestSequence: null }),- );-- await act(async () => {- await result.current.loadMore();- });-- expect(mockGetV2GetSession).not.toHaveBeenCalled();- });- });-- describe("loadMore — error handling", () => {- it("does not set hasMore=false on first error", async () => {- mockGetV2GetSession.mockRejectedValueOnce(new Error("network error"));-- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));-- await act(async () => {- await result.current.loadMore();- });-- expect(result.current.hasMore).toBe(true);- expect(result.current.isLoadingMore).toBe(false);- });-- it("sets hasMore=false after MAX_CONSECUTIVE_ERRORS (3) errors", async () => {- mockGetV2GetSession.mockRejectedValue(new Error("network error"));-- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));-- for (let i = 0; i < 3; i++) {- await act(async () => {- await result.current.loadMore();- });- await waitFor(() => expect(result.current.isLoadingMore).toBe(false));- }-- expect(result.current.hasMore).toBe(false);- });-- it("ignores non-200 response and increments error count", async () => {- mockGetV2GetSession.mockResolvedValueOnce({ status: 500, data: {} });-- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));-- await act(async () => {- await result.current.loadMore();- });-- expect(result.current.hasMore).toBe(true);- expect(result.current.isLoadingMore).toBe(false);- });- });-- describe("loadMore — MAX_OLDER_MESSAGES truncation", () => {- it("truncates accumulated messages at MAX_OLDER_MESSAGES (2000)", async () => {- mockGetV2GetSession.mockResolvedValueOnce(- makeSuccessResponse({- messages: Array.from({ length: 2001 }, (_, i) => ({- role: "user",- content: `msg ${i}`,- sequence: i,- })),- has_more_messages: true,- oldest_sequence: 0,- }),- );-- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));-- await act(async () => {- await result.current.loadMore();- });-- expect(result.current.hasMore).toBe(false);- });- });-- describe("pagedMessages — initialPageRawMessages extraToolOutputs", () => {- it("calls extractToolOutputsFromRaw with non-empty initialPageRawMessages", async () => {- const { extractToolOutputsFromRaw } = await import(- "../helpers/convertChatSessionToUiMessages"- );-- const rawMsg = { role: "user", content: "old", sequence: 0 };- mockGetV2GetSession.mockResolvedValueOnce(- makeSuccessResponse({- messages: [rawMsg],- has_more_messages: false,- oldest_sequence: 0,- }),- );-- const { result } = renderHook(() =>- useLoadMoreMessages({- ...BASE_ARGS,- initialPageRawMessages: [{ role: "assistant", content: "response" }],- }),- );-- await act(async () => {- await result.current.loadMore();- });-- expect(extractToolOutputsFromRaw).toHaveBeenCalled();- });- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsdeleted file mode 100644index 6a3348b82d..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.ts+++ /dev/null@@ -1,240 +0,0 @@-import { renderHook } from "@testing-library/react";-import { useRef } from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => mockToast(...args),-}));--const mockUploadFileDirect = vi.fn();-vi.mock("@/lib/direct-upload", () => ({- uploadFileDirect: (...args: unknown[]) => mockUploadFileDirect(...args),-}));--import { useCopilotStreamStore } from "../copilotStreamStore";-import { useSendMessage } from "../useSendMessage";--function file(name: string, size = 100, type = "text/plain"): File {- const blob = new Blob([new Uint8Array(size)], { type });- return new File([blob], name, { type });-}--function setupHook(opts: {- sessionId: string | null;- createSession?: () => Promise<string | undefined>;-}) {- const sendMessage = vi.fn();- const createSession =- opts.createSession ??- vi.fn(async () => "new-session" as string | undefined);-- const { result, rerender } = renderHook(- ({ sessionId }: { sessionId: string | null }) => {- const isUserStoppingRef = useRef(true);- const hook = useSendMessage({- sessionId,- sendMessage,- createSession,- isUserStoppingRef,- });- return { ...hook, isUserStoppingRef };- },- { initialProps: { sessionId: opts.sessionId } },- );- return { result, rerender, sendMessage, createSession };-}--describe("useSendMessage", () => {- beforeEach(() => {- mockToast.mockClear();- mockUploadFileDirect.mockReset();- // Reset shared store between tests via the store's own resetAll helper- // to avoid clobbering its internal action functions.- useCopilotStreamStore.getState().resetAll();- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it("does nothing when both text and files are empty", async () => {- const { result, sendMessage } = setupHook({ sessionId: "s1" });- await result.current.onSend(" ");- expect(sendMessage).not.toHaveBeenCalled();- });-- it("dispatches a plain text message immediately when a session exists", async () => {- const { result, sendMessage } = setupHook({ sessionId: "s1" });- await result.current.onSend("hello");- expect(sendMessage).toHaveBeenCalledWith({ text: "hello" });- });-- it("flips isUserStoppingRef back to false on each send", async () => {- const { result, sendMessage } = setupHook({ sessionId: "s1" });- expect(result.current.isUserStoppingRef.current).toBe(true);- await result.current.onSend("hello");- expect(result.current.isUserStoppingRef.current).toBe(false);- expect(sendMessage).toHaveBeenCalledTimes(1);- });-- it("rejects more than 10 attached files with a destructive toast", async () => {- const { result, sendMessage } = setupHook({ sessionId: "s1" });- const tooMany = Array.from({ length: 11 }, (_, i) => file(`f${i}.txt`));- await result.current.onSend("text", tooMany);- expect(sendMessage).not.toHaveBeenCalled();- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "Too many files",- variant: "destructive",- }),- );- });-- it("rejects a single file larger than the 100 MB limit", async () => {- const { result, sendMessage } = setupHook({ sessionId: "s1" });- const big = file("huge.bin", 101 * 1024 * 1024, "application/octet-stream");- await result.current.onSend("text", [big]);- expect(sendMessage).not.toHaveBeenCalled();- expect(mockToast).toHaveBeenCalledWith(- expect.objectContaining({- title: "File too large",- variant: "destructive",- }),- );- });-- it("uploads files and sends a message with file parts", async () => {- mockUploadFileDirect.mockResolvedValueOnce({- file_id: "fid-1",- name: "doc.txt",- mime_type: "text/plain",- });- const { result, sendMessage } = setupHook({ sessionId: "s1" });- await result.current.onSend("with file", [file("doc.txt")]);-- expect(mockUploadFileDirect).toHaveBeenCalledTimes(1);- expect(sendMessage).toHaveBeenCalledTimes(1);- const arg = sendMessage.mock.calls[0][0] as {- text: string;- files: {- type: string;- mediaType: string;- filename: string;- url: string;- }[];- };- expect(arg.text).toBe("with file");- expect(arg.files).toHaveLength(1);- expect(arg.files[0]).toMatchObject({- type: "file",- filename: "doc.txt",- mediaType: "text/plain",- });- expect(arg.files[0].url).toContain("fid-1");- });-- it("toasts and throws when every upload fails", async () => {- mockUploadFileDirect.mockRejectedValue(new Error("network down"));- const { result, sendMessage } = setupHook({ sessionId: "s1" });- await expect(- result.current.onSend("with file", [file("a.txt"), file("b.txt")]),- ).rejects.toThrow();- expect(sendMessage).not.toHaveBeenCalled();- // One per-file toast PLUS one aggregate failure toast.- const titles = mockToast.mock.calls.map(- (c) => (c[0] as { title: string }).title,- );- expect(titles).toContain("File upload failed");- });-- it("uses pre-built file parts from the store and skips upload", async () => {- // Mount BEFORE seeding parts — the post-session-creation flush effect- // calls takePendingFirstSend on mount with a sessionId, which clears- // pendingFileParts as a side effect.- const { result, sendMessage } = setupHook({ sessionId: "s1" });- useCopilotStreamStore.getState().setPendingFileParts([- {- type: "file" as const,- mediaType: "image/png",- filename: "img.png",- url: "/api/proxy/x",- },- ]);- await result.current.onSend("see attached");- expect(mockUploadFileDirect).not.toHaveBeenCalled();- expect(sendMessage).toHaveBeenCalledWith({- text: "see attached",- files: [expect.objectContaining({ type: "file", filename: "img.png" })],- });- // Pre-built parts are consumed once.- expect(useCopilotStreamStore.getState().pendingFileParts).toEqual([]);- });-- it("stashes a first-send to the store and creates a session when none exists", async () => {- const createSession = vi.fn(async () => "new-id" as string | undefined);- const { result } = setupHook({ sessionId: null, createSession });- await result.current.onSend("hi", [file("a.txt")]);- expect(createSession).toHaveBeenCalledTimes(1);- expect(useCopilotStreamStore.getState().pendingFirstSend?.text).toBe("hi");- expect(- useCopilotStreamStore.getState().pendingFirstSend?.files,- ).toHaveLength(1);- });-- it("blocks a second send while a no-session createSession is in flight", async () => {- let resolveCreate: (value: string) => void = () => {};- const createSession = vi.fn(- () => new Promise<string>((r) => (resolveCreate = r)),- );- const { result } = setupHook({ sessionId: null, createSession });-- // Two rapid sends with no session — only the first should make it through.- const first = result.current.onSend("first");- const second = result.current.onSend("second");-- // Resolve the in-flight create.- resolveCreate("new-id");- await Promise.all([first, second]);-- expect(createSession).toHaveBeenCalledTimes(1);- // pendingFirstSend reflects the FIRST message — the second short-circuits- // without overwriting.- expect(useCopilotStreamStore.getState().pendingFirstSend?.text).toBe(- "first",- );- });-- it("clears the pending first-send when createSession rejects", async () => {- const createSession = vi.fn(async () => {- throw new Error("create failed");- });- const { result } = setupHook({ sessionId: null, createSession });- await expect(result.current.onSend("hi")).rejects.toThrow();- expect(useCopilotStreamStore.getState().pendingFirstSend).toBeNull();- expect(useCopilotStreamStore.getState().pendingFileParts).toEqual([]);- });-- it("dispatches the queued first-send once a sessionId becomes available", async () => {- useCopilotStreamStore.getState().setPendingFirstSend({- text: "queued",- files: [],- });- const { rerender, sendMessage } = setupHook({ sessionId: null });- rerender({ sessionId: "now-active" });- expect(sendMessage).toHaveBeenCalledWith({ text: "queued" });- });-- it("setPendingFileParts forwards to the store", () => {- const { result } = setupHook({ sessionId: "s1" });- result.current.setPendingFileParts([- {- type: "file" as const,- mediaType: "image/jpeg",- filename: "x.jpg",- url: "/api/y",- },- ]);- expect(useCopilotStreamStore.getState().pendingFileParts).toHaveLength(1);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionDeletion.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionDeletion.test.tsdeleted file mode 100644index 888f9595ed..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionDeletion.test.ts+++ /dev/null@@ -1,232 +0,0 @@-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { act, cleanup, renderHook } from "@testing-library/react";-import React from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mockToast = vi.fn();-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => mockToast(...args),-}));--const setSessionIdMock = vi.fn();-let currentSessionId: string | null = "s1";-vi.mock("nuqs", () => ({- parseAsString: {},- useQueryState: () => [- currentSessionId,- (next: string | null) => {- currentSessionId = next;- setSessionIdMock(next);- },- ],-}));--interface UIStoreShape {- sessionToDelete: { id: string; title: string | null | undefined } | null;- setSessionToDelete: (- v: { id: string; title: string | null | undefined } | null,- ) => void;-}--let storeState: UIStoreShape = {- sessionToDelete: null,- setSessionToDelete: vi.fn((v) => {- storeState = { ...storeState, sessionToDelete: v };- }),-};-vi.mock("../store", () => ({- useCopilotUIStore: () => storeState,-}));--type DeleteHandler = (vars: { sessionId: string }) => Promise<unknown>;-let deleteImpl: DeleteHandler = async () => ({});-let isPending = false;-const onSuccessRef: { current?: (data: unknown, vars: unknown) => void } = {};-const onErrorRef: { current?: (err: unknown) => void } = {};--vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => {- return {- getGetV2ListSessionsQueryKey: () => ["sessions-list"],- useDeleteV2DeleteSession: ({- mutation,- }: {- mutation?: {- onSuccess?: (data: unknown, vars: unknown) => void;- onError?: (err: unknown) => void;- };- }) => {- onSuccessRef.current = mutation?.onSuccess;- onErrorRef.current = mutation?.onError;- return {- mutate: (vars: { sessionId: string }) => {- deleteImpl(vars).then(- (data) => onSuccessRef.current?.(data, vars),- (err) => onErrorRef.current?.(err),- );- },- isPending,- };- },- };-});--import { useSessionDeletion } from "../useSessionDeletion";--function makeWrapper(client: QueryClient) {- return function Wrapper({ children }: { children: React.ReactNode }) {- return React.createElement(QueryClientProvider, { client }, children);- };-}--describe("useSessionDeletion", () => {- let client: QueryClient;-- beforeEach(() => {- mockToast.mockClear();- setSessionIdMock.mockClear();- currentSessionId = "s1";- storeState = {- sessionToDelete: null,- setSessionToDelete: vi.fn((v) => {- storeState = { ...storeState, sessionToDelete: v };- }),- };- deleteImpl = async () => ({});- isPending = false;- client = new QueryClient();- });-- afterEach(() => {- cleanup();- vi.restoreAllMocks();- });-- it("requestDelete stages a session into the store", () => {- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });- act(() => {- result.current.requestDelete("target", "Target chat");- });- expect(storeState.setSessionToDelete).toHaveBeenCalledWith({- id: "target",- title: "Target chat",- });- });-- it("requestDelete is a no-op while a delete is in flight", () => {- isPending = true;- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });- act(() => {- result.current.requestDelete("target", "Target");- });- expect(storeState.setSessionToDelete).not.toHaveBeenCalled();- });-- it("cancelDelete clears the staged session when not deleting", () => {- storeState = {- ...storeState,- sessionToDelete: { id: "target", title: "Target" },- };- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });- act(() => {- result.current.cancelDelete();- });- expect(storeState.setSessionToDelete).toHaveBeenCalledWith(null);- });-- it("cancelDelete is a no-op while a delete is in flight", () => {- isPending = true;- storeState = {- ...storeState,- sessionToDelete: { id: "target", title: "Target" },- };- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });- act(() => {- result.current.cancelDelete();- });- expect(storeState.setSessionToDelete).not.toHaveBeenCalled();- });-- it("confirmDelete clears the active sessionId on success when it matches", async () => {- currentSessionId = "s1";- storeState = {- ...storeState,- sessionToDelete: { id: "s1", title: "Active" },- };- const invalidateSpy = vi.spyOn(client, "invalidateQueries");- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });-- await act(async () => {- result.current.confirmDelete();- });-- expect(setSessionIdMock).toHaveBeenCalledWith(null);- expect(invalidateSpy).toHaveBeenCalledWith({- queryKey: ["sessions-list"],- });- expect(storeState.setSessionToDelete).toHaveBeenLastCalledWith(null);- });-- it("confirmDelete keeps the active session when a different one was deleted", async () => {- currentSessionId = "s1";- storeState = {- ...storeState,- sessionToDelete: { id: "different", title: "Other" },- };- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });-- await act(async () => {- result.current.confirmDelete();- });-- expect(setSessionIdMock).not.toHaveBeenCalled();- expect(storeState.setSessionToDelete).toHaveBeenLastCalledWith(null);- });-- it("confirmDelete is a no-op when no session is staged", async () => {- storeState = { ...storeState, sessionToDelete: null };- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });- await act(async () => {- result.current.confirmDelete();- });- expect(setSessionIdMock).not.toHaveBeenCalled();- expect(mockToast).not.toHaveBeenCalled();- });-- it("toasts and clears the staged session on delete error", async () => {- storeState = {- ...storeState,- sessionToDelete: { id: "s1", title: "Active" },- };- deleteImpl = async () => {- throw new Error("network down");- };- const { result } = renderHook(() => useSessionDeletion(), {- wrapper: makeWrapper(client),- });-- await act(async () => {- result.current.confirmDelete();- });-- expect(mockToast).toHaveBeenCalledTimes(1);- expect(mockToast.mock.calls[0][0]).toMatchObject({- title: "Failed to delete chat",- variant: "destructive",- });- expect(storeState.setSessionToDelete).toHaveBeenLastCalledWith(null);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionTitlePoll.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionTitlePoll.test.tsdeleted file mode 100644index dd0493fabf..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionTitlePoll.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, renderHook } from "@testing-library/react";-import React from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { getGetV2ListSessionsQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";-import { useSessionTitlePoll } from "../useSessionTitlePoll";--interface SessionRow {- id: string;- title: string | null;-}--function listKey() {- return getGetV2ListSessionsQueryKey({ limit: 50 });-}--function seedSessions(client: QueryClient, sessions: SessionRow[]) {- client.setQueryData(listKey(), { status: 200, data: { sessions } });-}--function makeWrapper(client: QueryClient) {- return function Wrapper({ children }: { children: React.ReactNode }) {- return React.createElement(QueryClientProvider, { client }, children);- };-}--interface RenderProps {- status: "submitted" | "streaming" | "ready" | "error";- sessionId: string | null;- isReconnecting: boolean;-}--function renderPollHook(client: QueryClient, initial: RenderProps) {- return renderHook(- ({ status, sessionId, isReconnecting }: RenderProps) =>- useSessionTitlePoll({ status, sessionId, isReconnecting }),- {- wrapper: makeWrapper(client),- initialProps: initial,- },- );-}--describe("useSessionTitlePoll", () => {- let client: QueryClient;- let invalidateSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- vi.useFakeTimers();- client = new QueryClient();- invalidateSpy = vi.spyOn(client, "invalidateQueries");- });-- afterEach(() => {- cleanup();- vi.useRealTimers();- vi.restoreAllMocks();- });-- it("does not poll when there is no session", () => {- renderPollHook(client, {- status: "ready",- sessionId: null,- isReconnecting: false,- });- expect(invalidateSpy).not.toHaveBeenCalled();- });-- it("does not poll when reconnecting", async () => {- const { rerender } = renderPollHook(client, {- status: "streaming",- sessionId: "s1",- isReconnecting: true,- });- rerender({ status: "ready", sessionId: "s1", isReconnecting: true });- await vi.advanceTimersByTimeAsync(0);- expect(invalidateSpy).not.toHaveBeenCalled();- });-- it("kicks off an immediate invalidate + interval on streaming→ready", async () => {- seedSessions(client, [{ id: "s1", title: null }]);- const { rerender } = renderPollHook(client, {- status: "streaming",- sessionId: "s1",- isReconnecting: false,- });- rerender({ status: "ready", sessionId: "s1", isReconnecting: false });-- // Immediate invalidate.- expect(invalidateSpy).toHaveBeenCalledTimes(1);-- // Each tick re-invalidates while no title appears.- await vi.advanceTimersByTimeAsync(2_000);- expect(invalidateSpy).toHaveBeenCalledTimes(2);- await vi.advanceTimersByTimeAsync(2_000);- expect(invalidateSpy).toHaveBeenCalledTimes(3);- });-- it("stops polling once a title shows up in the cached session list", async () => {- seedSessions(client, [{ id: "s1", title: null }]);- const { rerender } = renderPollHook(client, {- status: "streaming",- sessionId: "s1",- isReconnecting: false,- });- rerender({ status: "ready", sessionId: "s1", isReconnecting: false });- expect(invalidateSpy).toHaveBeenCalledTimes(1); // initial-- // Backend writes the title before the next tick.- seedSessions(client, [{ id: "s1", title: "New title" }]);- await vi.advanceTimersByTimeAsync(2_000);- // First tick: clears interval (sees title), no extra invalidate.- expect(invalidateSpy).toHaveBeenCalledTimes(1);-- // Subsequent ticks must NOT fire — interval cleared.- await vi.advanceTimersByTimeAsync(20_000);- expect(invalidateSpy).toHaveBeenCalledTimes(1);- });-- it("gives up after the max attempt count", async () => {- seedSessions(client, [{ id: "s1", title: null }]);- const { rerender } = renderPollHook(client, {- status: "streaming",- sessionId: "s1",- isReconnecting: false,- });- rerender({ status: "ready", sessionId: "s1", isReconnecting: false });- // Initial + 5 attempts = 6 total invalidations, then nothing more.- for (let i = 0; i < 5; i++) await vi.advanceTimersByTimeAsync(2_000);- expect(invalidateSpy).toHaveBeenCalledTimes(6);- await vi.advanceTimersByTimeAsync(20_000);- expect(invalidateSpy).toHaveBeenCalledTimes(6);- });-- it("clears the interval when sessionId changes", async () => {- seedSessions(client, [{ id: "s1", title: null }]);- const { rerender } = renderPollHook(client, {- status: "streaming",- sessionId: "s1",- isReconnecting: false,- });- rerender({ status: "ready", sessionId: "s1", isReconnecting: false });- expect(invalidateSpy).toHaveBeenCalledTimes(1); // initial for s1-- rerender({ status: "ready", sessionId: "s2", isReconnecting: false });- invalidateSpy.mockClear();- // The s1 interval should be torn down — no further invalidates from it.- await vi.advanceTimersByTimeAsync(20_000);- expect(invalidateSpy).not.toHaveBeenCalled();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useStreamActivityWatchdog.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useStreamActivityWatchdog.test.tsdeleted file mode 100644index fa4e00ce46..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useStreamActivityWatchdog.test.ts+++ /dev/null@@ -1,163 +0,0 @@-import { renderHook } from "@testing-library/react";-import { act } from "react";-import { useRef } from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { useStreamActivityWatchdog } from "../useStreamActivityWatchdog";--type Status = "submitted" | "streaming" | "ready" | "error";--type HookArgs = Parameters<typeof useStreamActivityWatchdog>[0];--function setup(initial: Partial<HookArgs> = {}) {- const reconnect = vi.fn();- const { result, rerender } = renderHook(- ({- status,- activityToken,- isReconnectScheduled,- isUserStopping,- sessionId,- }: {- status: Status;- activityToken: string | number;- isReconnectScheduled: boolean;- isUserStopping: boolean;- sessionId: string | null;- }) => {- const isUserStoppingRef = useRef(isUserStopping);- isUserStoppingRef.current = isUserStopping;- const handleReconnectRef = useRef(reconnect);- handleReconnectRef.current = reconnect;- useStreamActivityWatchdog({- sessionId,- status,- activityToken,- isReconnectScheduled,- isUserStoppingRef,- handleReconnectRef,- });- return { reconnect };- },- {- initialProps: {- status: "streaming" as Status,- activityToken: initial.activityToken ?? "0",- isReconnectScheduled: initial.isReconnectScheduled ?? false,- isUserStopping: false,- sessionId:- initial.sessionId === undefined ? "sess-1" : initial.sessionId,- },- },- );- return { result, rerender, reconnect };-}--describe("useStreamActivityWatchdog", () => {- beforeEach(() => {- vi.useFakeTimers();- });- afterEach(() => {- vi.useRealTimers();- });-- it("fires reconnect after 60 s of inactivity while streaming", () => {- const { reconnect } = setup();-- act(() => {- vi.advanceTimersByTime(59_000);- });- expect(reconnect).not.toHaveBeenCalled();-- act(() => {- vi.advanceTimersByTime(1_000);- });- expect(reconnect).toHaveBeenCalledTimes(1);- });-- it("resets the timer on activity", () => {- const { rerender, reconnect } = setup({ activityToken: "0" });-- act(() => {- vi.advanceTimersByTime(50_000);- });-- rerender({- status: "streaming",- activityToken: "1",- isReconnectScheduled: false,- isUserStopping: false,- sessionId: "sess-1",- });-- act(() => {- vi.advanceTimersByTime(59_000);- });- expect(reconnect).not.toHaveBeenCalled();-- act(() => {- vi.advanceTimersByTime(1_000);- });- expect(reconnect).toHaveBeenCalledTimes(1);- });-- it("does not fire when a reconnect is already scheduled", () => {- const { reconnect } = setup({ isReconnectScheduled: true });-- act(() => {- vi.advanceTimersByTime(120_000);- });- expect(reconnect).not.toHaveBeenCalled();- });-- it("does not fire for ready / error status", () => {- const { rerender, reconnect } = setup();-- rerender({- status: "ready",- activityToken: "0",- isReconnectScheduled: false,- isUserStopping: false,- sessionId: "sess-1",- });-- act(() => {- vi.advanceTimersByTime(120_000);- });- expect(reconnect).not.toHaveBeenCalled();- });-- it("does not fire when the user explicitly stopped", () => {- const { rerender, reconnect } = setup();-- rerender({- status: "streaming",- activityToken: "0",- isReconnectScheduled: false,- isUserStopping: true,- sessionId: "sess-1",- });-- act(() => {- vi.advanceTimersByTime(120_000);- });- expect(reconnect).not.toHaveBeenCalled();- });-- it("does not fire without a session id", () => {- const { rerender, reconnect } = setup();-- rerender({- status: "streaming",- activityToken: "0",- isReconnectScheduled: false,- isUserStopping: false,- sessionId: null,- });-- act(() => {- vi.advanceTimersByTime(120_000);- });- expect(reconnect).not.toHaveBeenCalled();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWakeResync.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWakeResync.test.tsdeleted file mode 100644index 4f7bcd51fd..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWakeResync.test.ts+++ /dev/null@@ -1,225 +0,0 @@-import { cleanup, renderHook } from "@testing-library/react";-import {- afterEach,- beforeEach,- describe,- expect,- it,- vi,- type Mock,-} from "vitest";--import { useWakeResync } from "../useWakeResync";--type RefetchResult = { data?: unknown };--interface SetupOpts {- initialSessionId?: string | null;- refetchResult?: RefetchResult;- refetchImpl?: () => Promise<RefetchResult>;- initialMounted?: boolean;-}--function withVisibilityState(state: "visible" | "hidden") {- Object.defineProperty(document, "visibilityState", {- configurable: true,- get: () => state,- });-}--function fireVisibilityChange() {- document.dispatchEvent(new Event("visibilitychange"));-}--function setup(opts: SetupOpts = {}) {- const sessionIdRef = {- current: "initialSessionId" in opts ? opts.initialSessionId! : "sess-1",- };- const isMountedRef = { current: opts.initialMounted ?? true };- const refetchSession =- (opts.refetchImpl as Mock<() => Promise<RefetchResult>>) ??- vi.fn(async () => opts.refetchResult ?? { data: undefined });- const resumeStream = vi.fn();- const resumeStreamRef = { current: resumeStream };-- const hook = renderHook(() =>- useWakeResync({- sessionIdRef,- isMountedRef,- refetchSession,- resumeStreamRef,- }),- );-- return { hook, sessionIdRef, isMountedRef, refetchSession, resumeStream };-}--describe("useWakeResync", () => {- beforeEach(() => {- vi.useFakeTimers();- withVisibilityState("visible");- });-- afterEach(() => {- cleanup();- vi.useRealTimers();- vi.restoreAllMocks();- });-- it("does nothing when there is no session", async () => {- const { refetchSession } = setup({ initialSessionId: null });-- // Hide → wait long enough → re-show.- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000);- withVisibilityState("visible");- fireVisibilityChange();-- await vi.runAllTimersAsync();- expect(refetchSession).not.toHaveBeenCalled();- });-- it("skips re-sync when the page was hidden for less than the threshold", async () => {- const { refetchSession } = setup();-- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(5_000); // < 30s threshold- withVisibilityState("visible");- fireVisibilityChange();-- await vi.runAllTimersAsync();- expect(refetchSession).not.toHaveBeenCalled();- });-- it("refetches and does not resume when backend has no active stream", async () => {- const refetchSession = vi.fn(async () => ({- data: { status: 200, data: { active_stream: null } },- }));- const { resumeStream } = setup({ refetchImpl: refetchSession });-- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000); // > 30s- withVisibilityState("visible");- fireVisibilityChange();-- await vi.runAllTimersAsync();- expect(refetchSession).toHaveBeenCalledTimes(1);- expect(resumeStream).not.toHaveBeenCalled();- });-- it("resumes the stream when the refetch reports an active backend stream", async () => {- const refetchSession = vi.fn(async () => ({- data: {- status: 200,- data: { active_stream: { turn_id: "t1", started_at: "2026-01-01" } },- },- }));- const { resumeStream } = setup({ refetchImpl: refetchSession });-- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000);- withVisibilityState("visible");- fireVisibilityChange();-- await vi.runAllTimersAsync();- expect(refetchSession).toHaveBeenCalledTimes(1);- expect(resumeStream).toHaveBeenCalledTimes(1);- });-- it("does not resume when the session changed during the refetch", async () => {- let resolveRefetch: (v: RefetchResult) => void = () => {};- const refetchSession = vi.fn(- () => new Promise<RefetchResult>((r) => (resolveRefetch = r)),- );- const { resumeStream, sessionIdRef } = setup({- refetchImpl: refetchSession,- });-- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000);- withVisibilityState("visible");- fireVisibilityChange();-- // Simulate the user navigating to a different session before the- // refetch resolves.- sessionIdRef.current = "different-session";- resolveRefetch({- data: { status: 200, data: { active_stream: { turn_id: "t1" } } },- });-- await vi.runAllTimersAsync();- expect(resumeStream).not.toHaveBeenCalled();- });-- it("does not resume when the host unmounted during the refetch", async () => {- let resolveRefetch: (v: RefetchResult) => void = () => {};- const refetchSession = vi.fn(- () => new Promise<RefetchResult>((r) => (resolveRefetch = r)),- );- const { resumeStream, isMountedRef } = setup({- refetchImpl: refetchSession,- });-- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000);- withVisibilityState("visible");- fireVisibilityChange();-- isMountedRef.current = false;- resolveRefetch({- data: { status: 200, data: { active_stream: { turn_id: "t1" } } },- });-- await vi.runAllTimersAsync();- expect(resumeStream).not.toHaveBeenCalled();- });-- it("swallows refetch errors and clears isSyncing in finally", async () => {- const refetchSession = vi.fn(async () => {- throw new Error("boom");- });- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- const { hook } = setup({ refetchImpl: refetchSession });-- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000);- withVisibilityState("visible");- fireVisibilityChange();-- await vi.runAllTimersAsync();- expect(refetchSession).toHaveBeenCalledTimes(1);- expect(warn).toHaveBeenCalled();- expect(hook.result.current.isSyncing).toBe(false);- });-- it("only updates the hidden-at timestamp when going to hidden, not visible", async () => {- const refetchSession = vi.fn(async () => ({ data: undefined }));- setup({ refetchImpl: refetchSession });-- // Hidden → visible after only 5s: skipped.- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(5_000);- withVisibilityState("visible");- fireVisibilityChange();- await vi.runAllTimersAsync();- expect(refetchSession).not.toHaveBeenCalled();-- // Hidden again → visible after 60s: triggers (NOT 5s + 60s = 65s- // measured from the FIRST hidden — only the most recent hidden counts).- withVisibilityState("hidden");- fireVisibilityChange();- vi.advanceTimersByTime(60_000);- withVisibilityState("visible");- fireVisibilityChange();- await vi.runAllTimersAsync();- expect(refetchSession).toHaveBeenCalledTimes(1);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWorkflowImportAutoSubmit.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWorkflowImportAutoSubmit.test.tsdeleted file mode 100644index 693e8ad857..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWorkflowImportAutoSubmit.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { cleanup, renderHook, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mockSetInitialPrompt = vi.fn();-vi.mock("../store", () => ({- useCopilotUIStore: () => ({ setInitialPrompt: mockSetInitialPrompt }),-}));--import { useWorkflowImportAutoSubmit } from "../useWorkflowImportAutoSubmit";--function setLocation(href: string) {- // happy-dom allows reassigning window.location.href via History API; we- // can also mutate via URL + replaceState for hash/query coverage.- const next = new URL(href);- window.history.replaceState(- null,- "",- `${next.pathname}${next.search}${next.hash}`,- );-}--describe("useWorkflowImportAutoSubmit", () => {- beforeEach(() => {- mockSetInitialPrompt.mockClear();- sessionStorage.clear();- setLocation("http://localhost/copilot");- });-- afterEach(() => {- cleanup();- vi.restoreAllMocks();- });-- it("does nothing when there is no hash and no sessionStorage prompt", () => {- const onSend = vi.fn();- renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),- );- expect(onSend).not.toHaveBeenCalled();- expect(mockSetInitialPrompt).not.toHaveBeenCalled();- });-- it("populates the initial prompt from a hash without autosubmit", () => {- setLocation("http://localhost/copilot#prompt=Hello%20world");- const onSend = vi.fn();- renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),- );- expect(onSend).not.toHaveBeenCalled();- expect(mockSetInitialPrompt).toHaveBeenCalledWith("Hello world");- // Hash is cleared after consumption.- expect(window.location.hash).toBe("");- });-- it("auto-submits when autosubmit=true is set on the query string", async () => {- setLocation(- "http://localhost/copilot?autosubmit=true#prompt=auto%20submit%20me",- );- const onSend = vi.fn(async () => {});- renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),- );- await waitFor(() => expect(onSend).toHaveBeenCalledWith("auto submit me"));- expect(mockSetInitialPrompt).not.toHaveBeenCalled();- expect(window.location.search).toBe(""); // autosubmit param cleared- });-- it("falls back to setInitialPrompt when an autosubmit send rejects", async () => {- setLocation(- "http://localhost/copilot?autosubmit=true#prompt=auto%20submit%20me",- );- const onSend = vi.fn(async () => {- throw new Error("network down");- });- renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),- );- await waitFor(() =>- expect(mockSetInitialPrompt).toHaveBeenCalledWith("auto submit me"),- );- });-- it("uses sessionStorage prompt over the hash, including pre-uploaded file part", async () => {- setLocation("http://localhost/copilot?autosubmit=true#prompt=ignored");- sessionStorage.setItem("importWorkflowPrompt", "from-storage");- sessionStorage.setItem(- "importWorkflowFile",- JSON.stringify({- fileId: "11111111-2222-3333-4444-555555555555",- fileName: "wf.json",- mimeType: "application/json",- }),- );-- const setPendingFileParts = vi.fn();- const onSend = vi.fn(async () => {});- renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts }),- );- await waitFor(() => expect(onSend).toHaveBeenCalledWith("from-storage"));- expect(setPendingFileParts).toHaveBeenCalledWith([- expect.objectContaining({- type: "file",- mediaType: "application/json",- filename: "wf.json",- }),- ]);- expect(sessionStorage.getItem("importWorkflowPrompt")).toBeNull();- expect(sessionStorage.getItem("importWorkflowFile")).toBeNull();- });-- it("rejects malformed file ids (not a UUID) and skips the file part", async () => {- sessionStorage.setItem("importWorkflowPrompt", "with-bad-file");- sessionStorage.setItem(- "importWorkflowFile",- JSON.stringify({- fileId: "../etc/passwd",- fileName: "evil",- mimeType: "application/json",- }),- );- setLocation("http://localhost/copilot?autosubmit=true");- const setPendingFileParts = vi.fn();- const onSend = vi.fn(async () => {});- renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts }),- );- await waitFor(() => expect(onSend).toHaveBeenCalled());- expect(setPendingFileParts).not.toHaveBeenCalled();- });-- it("skips processing on subsequent renders (only runs once)", () => {- setLocation("http://localhost/copilot#prompt=run-once");- const onSend = vi.fn();- const { rerender } = renderHook(() =>- useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),- );- expect(mockSetInitialPrompt).toHaveBeenCalledTimes(1);- rerender();- rerender();- expect(mockSetInitialPrompt).toHaveBeenCalledTimes(1);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.tssimilarity index 99%rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.tsindex 6346450606..66004bc953 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { classifyArtifact } from "./helpers";+import { classifyArtifact } from "../helpers";describe("classifyArtifact", () => {it("routes PDF by extension", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsxindex 6a4347cbb0..9127b07abf 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx@@ -455,6 +455,183 @@ describe("ArtifactContent", () => {expect(retryButtons.length).toBeGreaterThan(0);});+ it("surfaces a network failure as a visible error message", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockRejectedValue(new Error("Network error")),+ );++ const artifact = makeArtifact({ id: "network-error-artifact" });+ const classification = makeClassification({ type: "html" });++ render(+ <ArtifactContent+ artifact={artifact}+ isSourceView={false}+ classification={classification}+ />,+ );++ await screen.findByText("Failed to load content", {}, { timeout: 2500 });+ expect(screen.getByText(/Network error/)).toBeTruthy();+ });++ it("retries transient HTML 5xx failures and renders content once a later attempt succeeds", async () => {+ let callCount = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(() => {+ callCount++;+ if (callCount < 3) {+ return Promise.resolve({+ ok: false,+ status: 503,+ headers: { get: () => "application/json" },+ json: () => Promise.resolve({ detail: "temporary upstream error" }),+ });+ }+ return Promise.resolve({+ ok: true,+ text: () => Promise.resolve("<html>ok now</html>"),+ });+ }),+ );++ const artifact = makeArtifact({+ id: "transient-html-retry",+ title: "flaky.html",+ mimeType: "text/html",+ });+ const classification = makeClassification({ type: "html" });++ const { container } = render(+ <ArtifactContent+ artifact={artifact}+ isSourceView={false}+ classification={classification}+ />,+ );++ await screen.findByTitle("flaky.html", {}, { timeout: 2500 });+ expect(callCount).toBe(3);+ const iframe = container.querySelector("iframe");+ expect(iframe?.getAttribute("srcdoc")).toContain("ok now");+ expect(screen.queryByText("Failed to load content")).toBeNull();+ });++ it("surfaces backend error detail from JSON error responses", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: false,+ status: 404,+ headers: { get: () => "application/json" },+ json: () => Promise.resolve({ detail: "File not found" }),+ }),+ );++ const artifact = makeArtifact({ id: "json-error-detail" });+ const classification = makeClassification({ type: "html" });++ render(+ <ArtifactContent+ artifact={artifact}+ isSourceView={false}+ classification={classification}+ />,+ );++ await screen.findByText("Failed to load content");+ expect(screen.getByText(/404/)).toBeTruthy();+ expect(screen.getByText(/File not found/)).toBeTruthy();+ });++ it("does not retry non-transient 403 failures", async () => {+ let callCount = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(() => {+ callCount++;+ return Promise.resolve({+ ok: false,+ status: 403,+ text: () => Promise.resolve("Forbidden"),+ });+ }),+ );++ const artifact = makeArtifact({ id: "forbidden-no-retry" });+ const classification = makeClassification({ type: "text" });++ render(+ <ArtifactContent+ artifact={artifact}+ isSourceView={false}+ classification={classification}+ />,+ );++ await screen.findByText("Failed to load content");+ expect(screen.getByText(/403/)).toBeTruthy();+ expect(callCount).toBe(1);+ });++ it("shows error state when a PDF download returns a non-2xx response", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: false,+ status: 500,+ text: () => Promise.resolve("Server Error"),+ }),+ );++ const artifact = makeArtifact({+ id: "pdf-error",+ title: "broken.pdf",+ mimeType: "application/pdf",+ });+ const classification = makeClassification({ type: "pdf" });++ const { container } = render(+ <ArtifactContent+ artifact={artifact}+ isSourceView={false}+ classification={classification}+ />,+ );++ await screen.findByText("Failed to load content", {}, { timeout: 2500 });+ expect(screen.getByText(/500/)).toBeTruthy();+ expect(container.querySelector("iframe")).toBeNull();+ });++ it("shows error state when a PDF download fails with a network error", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockRejectedValue(new Error("PDF network failure")),+ );++ const artifact = makeArtifact({+ id: "pdf-network-error",+ title: "broken.pdf",+ mimeType: "application/pdf",+ });+ const classification = makeClassification({ type: "pdf" });++ const { container } = render(+ <ArtifactContent+ artifact={artifact}+ isSourceView={false}+ classification={classification}+ />,+ );++ await screen.findByText("Failed to load content", {}, { timeout: 2500 });+ expect(screen.getByText(/PDF network failure/)).toBeTruthy();+ expect(container.querySelector("iframe")).toBeNull();+ });+// SECRT-2224: "try again doesn't do anything". The retry itself works — the// user's complaint is that there's no visible feedback when the same error// returns (e.g. a 404 for a deleted file). Clicking Try Again must flip thediff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactReactPreview.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactReactPreview.test.tsxsimilarity index 93%rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactReactPreview.test.tsxrename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactReactPreview.test.tsxindex be5b17781d..4acd26086b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactReactPreview.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactReactPreview.test.tsx@@ -1,13 +1,13 @@import { render, screen, waitFor } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-import { ArtifactReactPreview } from "./ArtifactReactPreview";+import { ArtifactReactPreview } from "../ArtifactReactPreview";import {buildReactArtifactSrcDoc,collectPreviewStyles,transpileReactArtifactSource,-} from "./reactArtifactPreview";+} from "../reactArtifactPreview";-vi.mock("./reactArtifactPreview", () => ({+vi.mock("../reactArtifactPreview", () => ({buildReactArtifactSrcDoc: vi.fn(),collectPreviewStyles: vi.fn(),transpileReactArtifactSource: vi.fn(),diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/transpileReactArtifact.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/transpileReactArtifact.test.tssimilarity index 98%rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/transpileReactArtifact.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/transpileReactArtifact.test.tsindex 3da1ee84fa..7d7f7f15b9 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/transpileReactArtifact.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/transpileReactArtifact.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { transpileReactArtifactSource } from "./transpileReactArtifact";+import { transpileReactArtifactSource } from "../transpileReactArtifact";describe("transpileReactArtifactSource", () => {it("transpiles a simple TSX function component", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/useArtifactContent.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/useArtifactContent.test.tsdeleted file mode 100644index 0d3c866805..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/useArtifactContent.test.ts+++ /dev/null@@ -1,501 +0,0 @@-import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";-import { renderHook, waitFor, act } from "@testing-library/react";-import {- useArtifactContent,- getCachedArtifactContent,- clearContentCache,-} from "../useArtifactContent";-import type { ArtifactRef } from "../../../../store";-import type { ArtifactClassification } from "../../helpers";--function makeArtifact(overrides?: Partial<ArtifactRef>): ArtifactRef {- return {- id: "file-001",- title: "test.txt",- mimeType: "text/plain",- sourceUrl: "/api/proxy/api/workspace/files/file-001/download",- origin: "agent",- ...overrides,- };-}--function makeClassification(- overrides?: Partial<ArtifactClassification>,-): ArtifactClassification {- return {- type: "text",- icon: vi.fn() as any,- label: "Text",- openable: true,- hasSourceToggle: false,- ...overrides,- };-}--describe("useArtifactContent", () => {- beforeEach(() => {- clearContentCache();- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- text: () => Promise.resolve("file content here"),- blob: () => Promise.resolve(new Blob(["pdf bytes"])),- }),- );- });-- afterEach(() => {- clearContentCache();- vi.restoreAllMocks();- });-- it("fetches text content for text artifacts", async () => {- const artifact = makeArtifact();- const classification = makeClassification({ type: "text" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(() => {- expect(result.current.isLoading).toBe(false);- });-- expect(result.current.content).toBe("file content here");- expect(result.current.error).toBeNull();- });-- it("skips fetch for image artifacts", async () => {- const artifact = makeArtifact({ mimeType: "image/png" });- const classification = makeClassification({ type: "image" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- expect(result.current.isLoading).toBe(false);- expect(result.current.content).toBeNull();- expect(fetch).not.toHaveBeenCalled();- });-- it("creates blob URL for PDF artifacts", async () => {- const artifact = makeArtifact({ mimeType: "application/pdf" });- const classification = makeClassification({ type: "pdf" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(() => {- expect(result.current.isLoading).toBe(false);- });-- expect(result.current.pdfUrl).toMatch(/^blob:/);- });-- it("sets error on fetch failure", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: false,- status: 404,- text: () => Promise.resolve("Not found"),- }),- );-- // Use a unique ID to avoid hitting the module-level content cache- const artifact = makeArtifact({ id: "error-test-unique" });- const classification = makeClassification({ type: "text" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(result.current.error).toContain("404");- expect(result.current.content).toBeNull();- });-- it("caches fetched content and exposes via getCachedArtifactContent", async () => {- const artifact = makeArtifact({ id: "cache-test" });- const classification = makeClassification({ type: "text" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(() => {- expect(result.current.content).toBe("file content here");- });-- expect(getCachedArtifactContent("cache-test")).toBe("file content here");- });-- it("sets error on fetch failure for HTML artifacts (stale artifact)", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: false,- status: 404,- text: () => Promise.resolve("Not found"),- }),- );-- const artifact = makeArtifact({ id: "stale-html-artifact" });- const classification = makeClassification({ type: "html" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(result.current.error).toContain("404");- expect(result.current.content).toBeNull();- });-- it("sets error on network failure", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockRejectedValue(new Error("Network error")),- );-- const artifact = makeArtifact({ id: "network-error-artifact" });- const classification = makeClassification({ type: "html" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(result.current.error).toContain("Network error");- expect(result.current.content).toBeNull();- });-- it("retries transient HTML fetch failures before surfacing an error", async () => {- let callCount = 0;- vi.stubGlobal(- "fetch",- vi.fn().mockImplementation(() => {- callCount++;- if (callCount < 3) {- return Promise.resolve({- ok: false,- status: 503,- headers: {- get: () => "application/json",- },- json: () => Promise.resolve({ detail: "temporary upstream error" }),- });- }-- return Promise.resolve({- ok: true,- text: () => Promise.resolve("<html>ok now</html>"),- });- }),- );-- const artifact = makeArtifact({ id: "transient-html-retry" });- const classification = makeClassification({ type: "html" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.content).toBe("<html>ok now</html>");- },- { timeout: 2500 },- );-- expect(callCount).toBe(3);- expect(result.current.error).toBeNull();- });-- it("surfaces backend error detail from JSON responses", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: false,- status: 404,- headers: {- get: () => "application/json",- },- json: () => Promise.resolve({ detail: "File not found" }),- }),- );-- const artifact = makeArtifact({ id: "json-error-detail" });- const classification = makeClassification({ type: "html" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(result.current.error).toContain("404");- expect(result.current.error).toContain("File not found");- });-- it("retry after 404 on HTML artifact clears cache and re-fetches", async () => {- let callCount = 0;- vi.stubGlobal(- "fetch",- vi.fn().mockImplementation(() => {- callCount++;- if (callCount === 1) {- return Promise.resolve({- ok: false,- status: 404,- text: () => Promise.resolve("Not found"),- });- }- return Promise.resolve({- ok: true,- text: () => Promise.resolve("<html>recovered</html>"),- });- }),- );-- const artifact = makeArtifact({ id: "retry-html-artifact" });- const classification = makeClassification({ type: "html" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(() => {- expect(result.current.error).toBeTruthy();- });-- act(() => {- result.current.retry();- });-- await waitFor(- () => {- expect(result.current.content).toBe("<html>recovered</html>");- },- { timeout: 2500 },- );-- expect(result.current.error).toBeNull();- });-- it("retry clears cache and re-fetches", async () => {- let callCount = 0;- vi.stubGlobal(- "fetch",- vi.fn().mockImplementation(() => {- callCount++;- return Promise.resolve({- ok: true,- text: () => Promise.resolve(`response ${callCount}`),- });- }),- );-- const artifact = makeArtifact({ id: "retry-test" });- const classification = makeClassification({ type: "text" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(() => {- expect(result.current.content).toBe("response 1");- });-- act(() => {- result.current.retry();- });-- await waitFor(() => {- expect(result.current.content).toBe("response 2");- });- });-- // ── Non-transient errors ──────────────────────────────────────────-- it("rejects immediately on 403 without retrying", async () => {- let callCount = 0;- vi.stubGlobal(- "fetch",- vi.fn().mockImplementation(() => {- callCount++;- return Promise.resolve({- ok: false,- status: 403,- text: () => Promise.resolve("Forbidden"),- });- }),- );-- const artifact = makeArtifact({ id: "forbidden-no-retry" });- const classification = makeClassification({ type: "text" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(callCount).toBe(1);- expect(result.current.error).toContain("403");- });-- // ── Video skip-fetch ──────────────────────────────────────────────-- it("skips fetch for video artifacts (like image)", async () => {- const artifact = makeArtifact({- id: "video-skip",- mimeType: "video/mp4",- });- const classification = makeClassification({ type: "video" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- expect(result.current.isLoading).toBe(false);- expect(result.current.content).toBeNull();- expect(result.current.pdfUrl).toBeNull();- expect(fetch).not.toHaveBeenCalled();- });-- // ── PDF error paths ───────────────────────────────────────────────-- it("sets error on PDF fetch failure (non-2xx)", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: false,- status: 500,- text: () => Promise.resolve("Server Error"),- }),- );-- const artifact = makeArtifact({ id: "pdf-error" });- const classification = makeClassification({ type: "pdf" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(result.current.error).toContain("500");- expect(result.current.pdfUrl).toBeNull();- });-- it("sets error on PDF network failure", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockRejectedValue(new Error("PDF network failure")),- );-- const artifact = makeArtifact({ id: "pdf-network-error" });- const classification = makeClassification({ type: "pdf" });-- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );-- await waitFor(- () => {- expect(result.current.error).toBeTruthy();- },- { timeout: 2500 },- );-- expect(result.current.error).toContain("PDF network failure");- expect(result.current.pdfUrl).toBeNull();- });-- // ── LRU cache eviction ────────────────────────────────────────────-- it("evicts oldest entry when cache exceeds 12 items", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockImplementation((url: string) => {- const fileId = url.match(/files\/([^/]+)\/download/)?.[1] ?? "unknown";- return Promise.resolve({- ok: true,- text: () => Promise.resolve(`content-${fileId}`),- });- }),- );-- const classification = makeClassification({ type: "text" });-- // Fill the cache with 12 entries (cache max = 12)- for (let i = 0; i < 12; i++) {- const artifact = makeArtifact({- id: `lru-${i}`,- sourceUrl: `/api/proxy/api/workspace/files/lru-${i}/download`,- });- const { result } = renderHook(() =>- useArtifactContent(artifact, classification),- );- await waitFor(() => {- expect(result.current.isLoading).toBe(false);- });- }-- // All 12 should be cached- expect(getCachedArtifactContent("lru-0")).toBe("content-lru-0");- expect(getCachedArtifactContent("lru-11")).toBe("content-lru-11");-- // Adding a 13th should evict lru-0 (the oldest)- const artifact13 = makeArtifact({- id: "lru-12",- sourceUrl: "/api/proxy/api/workspace/files/lru-12/download",- });- const { result: result13 } = renderHook(() =>- useArtifactContent(artifact13, classification),- );- await waitFor(() => {- expect(result13.current.isLoading).toBe(false);- });-- expect(getCachedArtifactContent("lru-0")).toBeUndefined();- expect(getCachedArtifactContent("lru-1")).toBe("content-lru-1");- expect(getCachedArtifactContent("lru-12")).toBe("content-lru-12");- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/useArtifactContentHelpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/useArtifactContentHelpers.test.tsnew file mode 100644index 0000000000..3fe0655850--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/useArtifactContentHelpers.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import React from "react";+import {+ getCachedArtifactContent,+ clearContentCache,+} from "../useArtifactContent";+import { ArtifactContent } from "../ArtifactContent";+import type { ArtifactRef } from "../../../../store";+import type { ArtifactClassification } from "../../helpers";++vi.mock("@/components/contextual/OutputRenderers", () => ({+ globalRegistry: {+ getRenderer: vi.fn().mockReturnValue({+ render: vi.fn(() => React.createElement("div", null, "rendered")),+ }),+ },+}));++vi.mock(+ "@/components/contextual/OutputRenderers/renderers/CodeRenderer",+ () => ({+ codeRenderer: {+ render: vi.fn(() => React.createElement("div", null, "code")),+ },+ }),+);++vi.mock("../ArtifactReactPreview", () => ({+ ArtifactReactPreview: vi.fn(() =>+ React.createElement("div", { "data-testid": "react-preview" }),+ ),+}));++function makeArtifact(overrides?: Partial<ArtifactRef>): ArtifactRef {+ return {+ id: "file-001",+ title: "test.txt",+ mimeType: "text/plain",+ sourceUrl: "/api/proxy/api/workspace/files/file-001/download",+ origin: "agent",+ ...overrides,+ };+}++function makeClassification(+ overrides?: Partial<ArtifactClassification>,+): ArtifactClassification {+ return {+ type: "text",+ icon: vi.fn(() => null) as unknown as ArtifactClassification["icon"],+ label: "Text",+ openable: true,+ hasSourceToggle: false,+ ...overrides,+ };+}++describe("useArtifactContent helpers (module-level cache)", () => {+ beforeEach(() => {+ clearContentCache();+ });++ afterEach(() => {+ cleanup();+ clearContentCache();+ vi.unstubAllGlobals();+ });++ it("populates the module cache so getCachedArtifactContent can read it from outside the panel", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ text: () => Promise.resolve("file content here"),+ }),+ );++ const artifact = makeArtifact({ id: "cache-test" });++ render(+ React.createElement(ArtifactContent, {+ artifact,+ isSourceView: false,+ classification: makeClassification({ type: "text" }),+ }),+ );++ await screen.findByText("rendered");+ expect(getCachedArtifactContent("cache-test")).toBe("file content here");+ });++ it("evicts the oldest cache entry once more than 12 artifacts have been loaded (LRU)", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation((url: string) => {+ const fileId = url.match(/files\/([^/]+)\/download/)?.[1] ?? "unknown";+ return Promise.resolve({+ ok: true,+ text: () => Promise.resolve(`content-${fileId}`),+ });+ }),+ );++ const classification = makeClassification({ type: "text" });++ for (let i = 0; i < 12; i++) {+ const artifact = makeArtifact({+ id: `lru-${i}`,+ sourceUrl: `/api/proxy/api/workspace/files/lru-${i}/download`,+ });+ const { unmount } = render(+ React.createElement(ArtifactContent, {+ artifact,+ isSourceView: false,+ classification,+ }),+ );+ await screen.findByText("rendered");+ unmount();+ }++ expect(getCachedArtifactContent("lru-0")).toBe("content-lru-0");+ expect(getCachedArtifactContent("lru-11")).toBe("content-lru-11");++ const artifact13 = makeArtifact({+ id: "lru-12",+ sourceUrl: "/api/proxy/api/workspace/files/lru-12/download",+ });+ const { unmount } = render(+ React.createElement(ArtifactContent, {+ artifact: artifact13,+ isSourceView: false,+ classification,+ }),+ );+ await screen.findByText("rendered");+ unmount();++ expect(getCachedArtifactContent("lru-0")).toBeUndefined();+ expect(getCachedArtifactContent("lru-1")).toBe("content-lru-1");+ expect(getCachedArtifactContent("lru-12")).toBe("content-lru-12");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/downloadArtifact.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/downloadArtifact.test.tsdeleted file mode 100644index fd9ca76079..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/downloadArtifact.test.ts+++ /dev/null@@ -1,121 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";-import type { ArtifactRef } from "../../store";-import { downloadArtifact } from "./downloadArtifact";--function makeArtifact(title: string): ArtifactRef {- return {- id: "abc",- title,- mimeType: "text/plain",- sourceUrl: "/api/proxy/api/workspace/files/abc/download",- origin: "agent",- };-}--afterEach(() => {- vi.restoreAllMocks();-});--describe("downloadArtifact filename sanitization", () => {- it("strips path separators and control characters", async () => {- global.fetch = vi.fn().mockResolvedValue({- ok: true,- blob: () => Promise.resolve(new Blob(["x"])),- });- const clicks: HTMLAnchorElement[] = [];- const originalCreate = document.createElement.bind(document);- vi.spyOn(document, "createElement").mockImplementation((tag: string) => {- const el = originalCreate(tag);- if (tag === "a") {- clicks.push(el as HTMLAnchorElement);- // Prevent actual navigation in test env.- (el as HTMLAnchorElement).click = () => {};- }- return el;- });- global.URL.createObjectURL = vi.fn(() => "blob:mock");- global.URL.revokeObjectURL = vi.fn();-- await downloadArtifact(makeArtifact("../../etc/passwd"));- // ..→_ then /→_ gives ____etc_passwd (no leading ..)- expect(clicks[0]?.download).toBe("____etc_passwd");- });-- it("replaces Windows-reserved characters", async () => {- global.fetch = vi.fn().mockResolvedValue({- ok: true,- blob: () => Promise.resolve(new Blob(["x"])),- });- const clicks: HTMLAnchorElement[] = [];- const originalCreate = document.createElement.bind(document);- vi.spyOn(document, "createElement").mockImplementation((tag: string) => {- const el = originalCreate(tag);- if (tag === "a") {- clicks.push(el as HTMLAnchorElement);- (el as HTMLAnchorElement).click = () => {};- }- return el;- });- global.URL.createObjectURL = vi.fn(() => "blob:mock");- global.URL.revokeObjectURL = vi.fn();-- await downloadArtifact(makeArtifact('a<b>c:"d*e?f|g'));- expect(clicks[0]?.download).toBe("a_b_c__d_e_f_g");- });-- it("falls back to 'download' when title is empty after sanitization", async () => {- global.fetch = vi.fn().mockResolvedValue({- ok: true,- blob: () => Promise.resolve(new Blob(["x"])),- });- const clicks: HTMLAnchorElement[] = [];- const originalCreate = document.createElement.bind(document);- vi.spyOn(document, "createElement").mockImplementation((tag: string) => {- const el = originalCreate(tag);- if (tag === "a") {- clicks.push(el as HTMLAnchorElement);- (el as HTMLAnchorElement).click = () => {};- }- return el;- });- global.URL.createObjectURL = vi.fn(() => "blob:mock");- global.URL.revokeObjectURL = vi.fn();-- await downloadArtifact(makeArtifact(""));- expect(clicks[0]?.download).toBe("download");- });-- it("keeps normal filenames intact", async () => {- global.fetch = vi.fn().mockResolvedValue({- ok: true,- blob: () => Promise.resolve(new Blob(["x"])),- });- const clicks: HTMLAnchorElement[] = [];- const originalCreate = document.createElement.bind(document);- vi.spyOn(document, "createElement").mockImplementation((tag: string) => {- const el = originalCreate(tag);- if (tag === "a") {- clicks.push(el as HTMLAnchorElement);- (el as HTMLAnchorElement).click = () => {};- }- return el;- });- global.URL.createObjectURL = vi.fn(() => "blob:mock");- global.URL.revokeObjectURL = vi.fn();-- await downloadArtifact(makeArtifact("report-2024 (final).pdf"));- expect(clicks[0]?.download).toBe("report-2024 (final).pdf");- });-- it("rejects when fetch returns non-ok status", async () => {- global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 404 });- await expect(downloadArtifact(makeArtifact("x.txt"))).rejects.toThrow(- /Download failed: 404/,- );- });-- it("rejects when fetch itself throws", async () => {- global.fetch = vi.fn().mockRejectedValue(new Error("network"));- await expect(downloadArtifact(makeArtifact("x.txt"))).rejects.toThrow();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsxindex ff2e41a29c..166331746a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx@@ -2,10 +2,36 @@ import React from "react";import { render, screen, cleanup } from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ChatContainer } from "../ChatContainer";+import { useCopilotUIStore } from "../../../store";const mockIsUsageLimitReached = vi.fn();const mockArtifactsEnabled = vi.fn(() => false);-const mockArtifactPanelOpen = vi.fn(() => false);++const ARTIFACT_A_ID = "11111111-0000-0000-0000-000000000000";+const ARTIFACT_B_ID = "22222222-0000-0000-0000-000000000000";++function makeArtifact(id: string, title = `${id}.txt`) {+ return {+ id,+ title,+ mimeType: "text/plain",+ sourceUrl: `/api/proxy/api/workspace/files/${id}/download`,+ origin: "agent" as const,+ };+}++function resetCopilotStore() {+ useCopilotUIStore.setState({+ artifactPanel: {+ isOpen: false,+ isMinimized: false,+ isMaximized: false,+ width: 600,+ activeArtifact: null,+ history: [],+ },+ });+}vi.mock("framer-motion", () => ({LayoutGroup: ({ children }: { children: React.ReactNode }) => <>{children}</>,@@ -61,19 +87,6 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({useGetFlag: () => mockArtifactsEnabled(),}));-vi.mock("../../../store", () => ({- useCopilotUIStore: (- selector?: (state: { artifactPanel: { isOpen: boolean } }) => unknown,- ) => {- const state = { artifactPanel: { isOpen: mockArtifactPanelOpen() } };- return typeof selector === "function" ? selector(state) : state;- },-}));--vi.mock("../useAutoOpenArtifacts", () => ({- useAutoOpenArtifacts: vi.fn(),-}));-vi.mock("../../ChatMessagesContainer/ChatMessagesContainer", () => ({ChatMessagesContainer: ({bottomContentPadding,@@ -140,12 +153,13 @@ describe("ChatContainer", () => {beforeEach(() => {mockIsUsageLimitReached.mockReturnValue(false);mockArtifactsEnabled.mockReturnValue(false);- mockArtifactPanelOpen.mockReturnValue(false);+ resetCopilotStore();vi.stubGlobal("ResizeObserver", MockResizeObserver);});afterEach(() => {cleanup();+ resetCopilotStore();vi.clearAllMocks();vi.unstubAllGlobals();});@@ -169,4 +183,120 @@ describe("ChatContainer", () => {expect(screen.queryByTestId("usage-limit-backdrop")).toBeNull();expect(screen.queryByRole("alert")).toBeNull();});++ describe("auto-open artifact panel behavior", () => {+ it("does not auto-open the artifact panel on initial render", () => {+ mockArtifactsEnabled.mockReturnValue(true);++ render(<ChatContainer {...baseProps} />);++ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);+ const wrapper = screen.getByTestId(+ "chat-messages-container",+ ).parentElement;+ expect(wrapper?.className).toContain("max-w-3xl");+ });++ it("does not auto-open when rerendering within the same session", () => {+ mockArtifactsEnabled.mockReturnValue(true);++ const { rerender } = render(<ChatContainer {...baseProps} />);+ rerender(<ChatContainer {...baseProps} />);++ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);+ const wrapper = screen.getByTestId(+ "chat-messages-container",+ ).parentElement;+ expect(wrapper?.className).toContain("max-w-3xl");+ });++ it("resets the panel state when sessionId changes", () => {+ mockArtifactsEnabled.mockReturnValue(true);+ useCopilotUIStore+ .getState()+ .openArtifact(makeArtifact(ARTIFACT_A_ID, "a.txt"));+ useCopilotUIStore+ .getState()+ .openArtifact(makeArtifact(ARTIFACT_B_ID, "b.txt"));++ const { rerender } = render(+ <ChatContainer {...baseProps} sessionId="s1" />,+ );++ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(true);++ rerender(<ChatContainer {...baseProps} sessionId="s2" />);++ const panel = useCopilotUIStore.getState().artifactPanel;+ expect(panel.isOpen).toBe(false);+ expect(panel.activeArtifact).toBeNull();+ expect(panel.history).toEqual([]);+ const wrapper = screen.getByTestId(+ "chat-messages-container",+ ).parentElement;+ expect(wrapper?.className).toContain("max-w-3xl");+ });++ it("does not carry a stale back stack into the next session", () => {+ mockArtifactsEnabled.mockReturnValue(true);+ useCopilotUIStore+ .getState()+ .openArtifact(makeArtifact(ARTIFACT_A_ID, "a.txt"));+ useCopilotUIStore+ .getState()+ .openArtifact(makeArtifact(ARTIFACT_B_ID, "b.txt"));++ const { rerender } = render(+ <ChatContainer {...baseProps} sessionId="s1" />,+ );+ rerender(<ChatContainer {...baseProps} sessionId="s2" />);++ useCopilotUIStore.getState().openArtifact(makeArtifact("c", "c.txt"));++ const panel = useCopilotUIStore.getState().artifactPanel;+ expect(panel.activeArtifact?.id).toBe("c");+ expect(panel.history).toEqual([]);+ });++ it("closes the panel on unmount so nav-away cannot resurrect it (SECRT-2254)", () => {+ mockArtifactsEnabled.mockReturnValue(true);+ useCopilotUIStore+ .getState()+ .openArtifact(makeArtifact(ARTIFACT_A_ID, "a.txt"));+ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(true);++ const { unmount } = render(<ChatContainer {...baseProps} />);+ unmount();++ const panel = useCopilotUIStore.getState().artifactPanel;+ expect(panel.isOpen).toBe(false);+ expect(panel.activeArtifact).toBeNull();+ expect(panel.history).toEqual([]);+ });++ it("does not re-open a panel whose store state is stale on fresh mount (SECRT-2220)", () => {+ mockArtifactsEnabled.mockReturnValue(true);+ useCopilotUIStore.setState({+ artifactPanel: {+ isOpen: true,+ isMinimized: false,+ isMaximized: false,+ width: 600,+ activeArtifact: makeArtifact(ARTIFACT_A_ID, "stale.txt"),+ history: [],+ },+ });++ const { unmount } = render(<ChatContainer {...baseProps} />);+ unmount();++ render(<ChatContainer {...baseProps} />);++ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);+ const wrapper = screen.getByTestId(+ "chat-messages-container",+ ).parentElement;+ expect(wrapper?.className).toContain("max-w-3xl");+ });+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/useAutoOpenArtifacts.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/useAutoOpenArtifacts.test.tsdeleted file mode 100644index bc0a66709e..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/useAutoOpenArtifacts.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, expect, it, beforeEach, afterEach } from "vitest";-import { renderHook } from "@testing-library/react";-import { useAutoOpenArtifacts } from "../useAutoOpenArtifacts";-import { useCopilotUIStore } from "../../../store";--// Capture the real store actions before any test can replace them.-const realOpenArtifact = useCopilotUIStore.getState().openArtifact;-const realResetArtifactPanel = useCopilotUIStore.getState().resetArtifactPanel;--function resetStore() {- useCopilotUIStore.setState({- openArtifact: realOpenArtifact,- resetArtifactPanel: realResetArtifactPanel,- artifactPanel: {- isOpen: false,- isMinimized: false,- isMaximized: false,- width: 600,- activeArtifact: null,- history: [],- },- });-}--describe("useAutoOpenArtifacts", () => {- beforeEach(resetStore);- afterEach(resetStore);-- it("does not auto-open artifacts on initial message load", () => {- renderHook(() => useAutoOpenArtifacts({ sessionId: "session-1" }));- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);- });-- it("does not auto-open when rerendering within the same session", () => {- const { rerender } = renderHook(- ({ sessionId }: { sessionId: string }) =>- useAutoOpenArtifacts({ sessionId }),- { initialProps: { sessionId: "session-1" } },- );-- rerender({ sessionId: "session-1" });- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);- });-- it("panel should fully reset when session changes", () => {- const artifact = {- id: "file1",- title: "image.png",- mimeType: "image/png",- sourceUrl: "/api/proxy/api/workspace/files/file1/download",- origin: "agent" as const,- };- useCopilotUIStore.getState().openArtifact(artifact);- useCopilotUIStore.getState().openArtifact({- ...artifact,- id: "file2",- title: "second.png",- sourceUrl: "/api/proxy/api/workspace/files/file2/download",- });- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(true);-- const { rerender } = renderHook(- ({ sessionId }: { sessionId: string }) =>- useAutoOpenArtifacts({ sessionId }),- { initialProps: { sessionId: "session-1" } },- );-- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(true);-- rerender({ sessionId: "session-2" });-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.activeArtifact).toBeNull();- expect(s.history).toEqual([]);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.tsdeleted file mode 100644index 237e9b80f5..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.ts+++ /dev/null@@ -1,145 +0,0 @@-import { act, cleanup, renderHook } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { useCopilotUIStore } from "../../store";-import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";--const A_ID = "11111111-0000-0000-0000-000000000000";-const B_ID = "22222222-0000-0000-0000-000000000000";--function makeArtifact(id: string, title = `${id}.txt`) {- return {- id,- title,- mimeType: "text/plain",- sourceUrl: `/api/proxy/api/workspace/files/${id}/download`,- origin: "agent" as const,- };-}--function resetStore() {- useCopilotUIStore.setState({- artifactPanel: {- isOpen: false,- isMinimized: false,- isMaximized: false,- width: 600,- activeArtifact: null,- history: [],- },- });-}--describe("useAutoOpenArtifacts", () => {- beforeEach(resetStore);- // Testing Library auto-cleanup isn't registered in our Vitest setup, so- // mounted `renderHook` instances (and their unmount cleanups) would leak- // between tests — here the unmount effect in useAutoOpenArtifacts would- // fire after the next test had already run and corrupt its assertions.- afterEach(cleanup);-- it("does not auto-open on initial render", () => {- renderHook(() => useAutoOpenArtifacts({ sessionId: "s1" }));- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);- });-- it("does not auto-open when rerendering within the same session", () => {- const { rerender } = renderHook(- ({ sessionId }) => useAutoOpenArtifacts({ sessionId }),- { initialProps: { sessionId: "s1" } },- );-- act(() => {- rerender({ sessionId: "s1" });- });-- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);- });-- it("resets the panel state when sessionId changes", () => {- useCopilotUIStore.getState().openArtifact(makeArtifact(A_ID, "a.txt"));- useCopilotUIStore.getState().openArtifact(makeArtifact(B_ID, "b.txt"));-- const { rerender } = renderHook(- ({ sessionId }) => useAutoOpenArtifacts({ sessionId }),- { initialProps: { sessionId: "s1" } },- );-- act(() => {- rerender({ sessionId: "s2" });- });-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.activeArtifact).toBeNull();- expect(s.history).toEqual([]);- });-- it("does not carry a stale back stack into the next session", () => {- useCopilotUIStore.getState().openArtifact(makeArtifact(A_ID, "a.txt"));- useCopilotUIStore.getState().openArtifact(makeArtifact(B_ID, "b.txt"));-- const { rerender } = renderHook(- ({ sessionId }) => useAutoOpenArtifacts({ sessionId }),- { initialProps: { sessionId: "s1" } },- );-- act(() => {- rerender({ sessionId: "s2" });- });-- useCopilotUIStore.getState().openArtifact(makeArtifact("c", "c.txt"));-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.activeArtifact?.id).toBe("c");- expect(s.history).toEqual([]);- });-- // SECRT-2254: "had agent panel open then went to profile then went to home- // and agent panel was still open". Nav-away unmounts the copilot page; if- // the panel state persists in the store, coming back re-renders it open.- it("closes the panel on unmount so nav-away → nav-back doesn't resurrect it (SECRT-2254)", () => {- useCopilotUIStore.getState().openArtifact(makeArtifact(A_ID, "a.txt"));- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(true);-- const { unmount } = renderHook(() =>- useAutoOpenArtifacts({ sessionId: "s1" }),- );-- act(() => {- unmount();- });-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.activeArtifact).toBeNull();- expect(s.history).toEqual([]);- });-- // SECRT-2220: "keep closed by default" — a fresh mount (e.g. user returns to- // /copilot) must start with a closed panel even if the store somehow carries- // stale state from a prior life.- it("does not re-open a panel whose store state is stale on fresh mount (SECRT-2220)", () => {- // Simulate the store being left in an open state by a previous page life.- useCopilotUIStore.setState({- artifactPanel: {- isOpen: true,- isMinimized: false,- isMaximized: false,- width: 600,- activeArtifact: makeArtifact(A_ID, "stale.txt"),- history: [],- },- });-- const { unmount } = renderHook(() =>- useAutoOpenArtifacts({ sessionId: "s1" }),- );- act(() => {- unmount();- });-- // Next mount of the page should see a clean store.- renderHook(() => useAutoOpenArtifacts({ sessionId: "s1" }));- expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);- });-});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.tsxindex 506df99c22..0527ed95d2 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@@ -6,8 +6,17 @@ import {act,waitFor,} from "@/tests/integrations/test-utils";+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";++const mockCancel =+ vi.fn<(sessionId: string) => Promise<{ status: number; data: unknown }>>();+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ postV2CancelSessionTask: (sessionId: string) => mockCancel(sessionId),+}));let mockCopilotMode = "extended_thinking";const mockSetCopilotChatMode = vi.fn((mode: string) => {@@ -65,11 +74,29 @@ vi.mock("@/components/ai-elements/prompt-input", () => ({PromptInputFooter: ({ children }: { children: React.ReactNode }) => (<div>{children}</div>),- PromptInputSubmit: ({ disabled }: { disabled?: boolean }) => (- <button disabled={disabled} data-testid="submit">- Send- </button>- ),+ PromptInputSubmit: ({+ disabled,+ status,+ onStop,+ }: {+ disabled?: boolean;+ status?: string;+ onStop?: () => void;+ }) =>+ status === "streaming" ? (+ <button+ type="button"+ onClick={onStop}+ data-testid="stop"+ aria-label="Stop"+ >+ Stop+ </button>+ ) : (+ <button disabled={disabled} data-testid="submit">+ Send+ </button>+ ),PromptInputTextarea: (props: {id?: string;value?: string;@@ -146,8 +173,10 @@ const mockOnSend = vi.fn();afterEach(() => {cleanup();vi.clearAllMocks();+ mockCancel.mockReset();mockCopilotMode = "extended_thinking";mockCopilotLlmModel = "standard";+ mockFlagValue = false;});describe("ChatInput mode toggle", () => {@@ -424,3 +453,326 @@ describe("ChatInput model toggle", () => {);});});++describe("ChatInput submit behavior", () => {+ it("does not call onSend when textarea is empty", () => {+ const onSend = vi.fn().mockResolvedValue(undefined);+ render(<ChatInput onSend={onSend} />);+ const form = screen.getByTestId("submit").closest("form")!;+ fireEvent.submit(form);+ expect(onSend).not.toHaveBeenCalled();+ });++ it("sends trimmed value and clears textarea", async () => {+ const onSend = vi.fn().mockResolvedValue(undefined);+ render(<ChatInput onSend={onSend} />);+ const textarea = screen.getByTestId("textarea") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: " hello " } });+ const form = textarea.closest("form")!;+ fireEvent.submit(form);+ await waitFor(() => {+ expect(onSend).toHaveBeenCalledWith("hello", undefined);+ });+ await waitFor(() => {+ expect(textarea.value).toBe("");+ });+ });++ it("does not call onSend when disabled", () => {+ const onSend = vi.fn().mockResolvedValue(undefined);+ render(<ChatInput onSend={onSend} disabled />);+ const textarea = screen.getByTestId("textarea") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "hello" } });+ const form = textarea.closest("form")!;+ fireEvent.submit(form);+ expect(onSend).not.toHaveBeenCalled();+ });++ it("prevents double-submit while a send is in flight", async () => {+ let resolveFirst: (() => void) | undefined;+ const onSend = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveFirst = resolve;+ }),+ );+ render(<ChatInput onSend={onSend} />);+ const textarea = screen.getByTestId("textarea") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "hello" } });+ const form = textarea.closest("form")!;+ fireEvent.submit(form);+ fireEvent.submit(form);+ expect(onSend).toHaveBeenCalledTimes(1);+ await act(async () => {+ resolveFirst?.();+ });+ });++ it("allows sending again after a failed send", async () => {+ const swallowWindow = (e: PromiseRejectionEvent) => e.preventDefault();+ const swallowProcess = () => undefined;+ window.addEventListener("unhandledrejection", swallowWindow);+ process.on("unhandledRejection", swallowProcess);+ try {+ let failNext = true;+ const onSend = vi.fn(async () => {+ if (failNext) {+ failNext = false;+ throw new Error("fail");+ }+ });+ render(<ChatInput onSend={onSend} />);+ const textarea = screen.getByTestId("textarea") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "hello" } });+ const form = textarea.closest("form")!;+ fireEvent.submit(form);+ await waitFor(() => {+ expect(onSend).toHaveBeenCalledTimes(1);+ });+ fireEvent.change(textarea, { target: { value: "retry" } });+ fireEvent.submit(form);+ await waitFor(() => {+ expect(onSend).toHaveBeenCalledTimes(2);+ });+ expect(onSend).toHaveBeenLastCalledWith("retry", undefined);+ } finally {+ window.removeEventListener("unhandledrejection", swallowWindow);+ process.off("unhandledRejection", swallowProcess);+ }+ });+});++interface StopHarnessProps {+ sessionId: string | null;+ sdkStop: () => void;+ setMessages: (+ updater: ((prev: UIMessage[]) => UIMessage[]) | UIMessage[],+ ) => void;+ setIsUserStopping: (value: boolean) => void;+}++function StopHarness({+ sessionId,+ sdkStop,+ setMessages,+ setIsUserStopping,+}: StopHarnessProps) {+ const isUserStoppingRef = useRef(false);+ const stop = useCopilotStop({+ sessionId,+ sdkStop,+ setMessages: setMessages as Parameters<+ typeof useCopilotStop+ >[0]["setMessages"],+ isUserStoppingRef,+ setIsUserStopping,+ });+ return <ChatInput onSend={vi.fn()} isStreaming onStop={stop} />;+}++function asstMessage(parts: UIMessage["parts"], id = "a1"): UIMessage {+ return { id, role: "assistant", parts };+}++describe("ChatInput stop button", () => {+ it("appends a cancellation marker to the trailing assistant message", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ let messages: UIMessage[] = [+ asstMessage([{ type: "text", text: "partial reply", state: "done" }]),+ ];+ const setMessages = vi.fn((updater: unknown) => {+ if (typeof updater === "function") {+ messages = (updater as (prev: UIMessage[]) => UIMessage[])(messages);+ } else {+ messages = updater as UIMessage[];+ }+ });++ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={vi.fn()}+ setMessages={setMessages}+ setIsUserStopping={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ const last = messages[messages.length - 1];+ const tail = last.parts[last.parts.length - 1];+ expect(tail.type).toBe("text");+ expect((tail as { text: string }).text).toContain("Operation cancelled");+ });+ });++ it("leaves messages unchanged when there is no trailing assistant message", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ let messages: UIMessage[] = [+ {+ id: "u1",+ role: "user",+ parts: [{ type: "text", text: "hi", state: "done" }],+ },+ ];+ const setMessages = vi.fn((updater: unknown) => {+ if (typeof updater === "function") {+ messages = (updater as (prev: UIMessage[]) => UIMessage[])(messages);+ } else {+ messages = updater as UIMessage[];+ }+ });++ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={vi.fn()}+ setMessages={setMessages}+ setIsUserStopping={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ expect(mockCancel).toHaveBeenCalled();+ });+ expect(messages).toHaveLength(1);+ expect(messages[0].role).toBe("user");+ });++ it("aborts the SDK stream and flips the user-stopping flag when clicked", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const sdkStop = vi.fn();+ const setIsUserStopping = vi.fn();++ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={sdkStop}+ setMessages={vi.fn()}+ setIsUserStopping={setIsUserStopping}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ expect(sdkStop).toHaveBeenCalledTimes(1);+ expect(setIsUserStopping).toHaveBeenCalledWith(true);+ });+ });++ it("still proceeds with cancel if sdkStop throws", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const sdkStop = vi.fn(() => {+ throw new Error("no fetch in flight");+ });++ const swallowWindow = (e: PromiseRejectionEvent) => e.preventDefault();+ const swallowProcess = () => undefined;+ window.addEventListener("unhandledrejection", swallowWindow);+ process.on("unhandledRejection", swallowProcess);+ try {+ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={sdkStop}+ setMessages={vi.fn()}+ setIsUserStopping={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ expect(mockCancel).toHaveBeenCalledTimes(1);+ });+ } finally {+ window.removeEventListener("unhandledrejection", swallowWindow);+ process.off("unhandledRejection", swallowProcess);+ }+ });++ it("does not call the cancel endpoint when there is no active sessionId", async () => {+ const setIsUserStopping = vi.fn();+ render(+ <StopHarness+ sessionId={null}+ sdkStop={vi.fn()}+ setMessages={vi.fn()}+ setIsUserStopping={setIsUserStopping}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));+ await waitFor(() => {+ expect(setIsUserStopping).toHaveBeenCalledWith(true);+ });+ expect(mockCancel).not.toHaveBeenCalled();+ });++ it("toasts a 'Stop may take a moment' notice on cancel_published_not_confirmed", async () => {+ const { toast } = await import("@/components/molecules/Toast/use-toast");+ mockCancel.mockResolvedValue({+ status: 200,+ data: { reason: "cancel_published_not_confirmed" },+ });++ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={vi.fn()}+ setMessages={vi.fn()}+ setIsUserStopping={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Stop may take a moment" }),+ );+ });+ });++ it("toasts a destructive notice when the cancel request rejects", async () => {+ const { toast } = await import("@/components/molecules/Toast/use-toast");+ mockCancel.mockRejectedValue(new Error("network down"));++ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={vi.fn()}+ setMessages={vi.fn()}+ setIsUserStopping={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Could not stop the task",+ variant: "destructive",+ }),+ );+ });+ });++ it("does not toast when the cancel succeeds with a normal reason", async () => {+ const { toast } = await import("@/components/molecules/Toast/use-toast");+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });++ render(+ <StopHarness+ sessionId="sess-1"+ sdkStop={vi.fn()}+ setMessages={vi.fn()}+ setIsUserStopping={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByTestId("stop"));++ await waitFor(() => {+ expect(mockCancel).toHaveBeenCalled();+ });+ expect(toast).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.tsdeleted file mode 100644index 5f2b8d87cb..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.ts+++ /dev/null@@ -1,146 +0,0 @@-import { renderHook, act, waitFor } from "@testing-library/react";-import { describe, expect, it, vi, beforeEach } from "vitest";-import { useChatInput } from "../useChatInput";--vi.mock("@/app/(platform)/copilot/store", () => ({- useCopilotUIStore: () => ({- initialPrompt: null,- setInitialPrompt: vi.fn(),- }),-}));--describe("useChatInput", () => {- const mockOnSend = vi.fn();-- beforeEach(() => {- vi.clearAllMocks();- mockOnSend.mockResolvedValue(undefined);- });-- it("does not send when value is empty", async () => {- const { result } = renderHook(() => useChatInput({ onSend: mockOnSend }));-- await act(async () => {- await result.current.handleSend();- });-- expect(mockOnSend).not.toHaveBeenCalled();- });-- it("sends trimmed value and clears input", async () => {- const { result } = renderHook(() => useChatInput({ onSend: mockOnSend }));-- act(() => {- result.current.setValue(" hello ");- });-- await act(async () => {- await result.current.handleSend();- });-- expect(mockOnSend).toHaveBeenCalledWith("hello");- expect(result.current.value).toBe("");- });-- it("submits the live form value when React state has not caught up", async () => {- const { result } = renderHook(() => useChatInput({ onSend: mockOnSend }));- const form = document.createElement("form");- const textarea = document.createElement("textarea");- textarea.name = "message";- textarea.value = " visible textarea value ";- form.append(textarea);-- act(() => {- result.current.setValue("");- });-- act(() => {- result.current.handleSubmit({- preventDefault: vi.fn(),- currentTarget: form,- } as unknown as Parameters<typeof result.current.handleSubmit>[0]);- });-- await waitFor(() => {- expect(mockOnSend).toHaveBeenCalledWith("visible textarea value");- });- });-- it("does not send when disabled", async () => {- const { result } = renderHook(() =>- useChatInput({ onSend: mockOnSend, disabled: true }),- );-- act(() => {- result.current.setValue("hello");- });-- await act(async () => {- await result.current.handleSend();- });-- expect(mockOnSend).not.toHaveBeenCalled();- });-- it("prevents double-submit via ref guard", async () => {- let resolveFirst: () => void;- const slowSend = vi.fn(- () =>- new Promise<void>((resolve) => {- resolveFirst = resolve;- }),- );-- const { result } = renderHook(() => useChatInput({ onSend: slowSend }));-- act(() => {- result.current.setValue("hello");- });-- act(() => {- void result.current.handleSend();- });-- await act(async () => {- await result.current.handleSend();- });-- expect(slowSend).toHaveBeenCalledTimes(1);-- await act(async () => {- resolveFirst!();- });- });-- it("allows sending empty when canSendEmpty is true", async () => {- const { result } = renderHook(() =>- useChatInput({ onSend: mockOnSend, canSendEmpty: true }),- );-- await act(async () => {- await result.current.handleSend();- });-- expect(mockOnSend).toHaveBeenCalledWith("");- });-- it("resets isSending after onSend throws", async () => {- mockOnSend.mockRejectedValue(new Error("fail"));-- const { result } = renderHook(() => useChatInput({ onSend: mockOnSend }));-- act(() => {- result.current.setValue("hello");- });-- await act(async () => {- try {- await result.current.handleSend();- } catch {- // expected- }- });-- expect(result.current.isSending).toBe(false);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.tssimilarity index 99%rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.tsindex bf64d0e88f..eb94cd2044 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts@@ -4,8 +4,8 @@ import {filePartToArtifactRef,isReasoningToolPart,splitReasoningAndResponse,-} from "./helpers";-import type { MessagePart } from "./helpers";+} from "../helpers";+import type { MessagePart } from "../helpers";function textPart(text: string): MessagePart {return { type: "text", text } as MessagePart;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsxnew file mode 100644index 0000000000..8f4ac14d13--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/__tests__/ChatSidebar.test.tsx@@ -0,0 +1,158 @@+import {+ getDeleteV2DeleteSessionMockHandler,+ getDeleteV2DeleteSessionMockHandler422,+ getGetV2ListSessionsMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ within,+} from "@/tests/integrations/test-utils";+import { SidebarProvider } from "@/components/ui/sidebar";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotUIStore } from "../../../store";+import { ChatSidebar } from "../ChatSidebar";++const toastMock = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >();+ return {+ ...actual,+ toast: (...args: unknown[]) => toastMock(...args),+ };+});++vi.mock("../../UsageLimits/UsageLimits", () => ({+ UsageLimits: () => null,+}));+vi.mock("../components/NotificationToggle/NotificationToggle", () => ({+ NotificationToggle: () => null,+}));++const sessions = [+ {+ id: "s1",+ title: "Active chat",+ is_processing: false,+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+ },+ {+ id: "s2",+ title: "Other chat",+ is_processing: false,+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+ },+];++function renderSidebar() {+ return render(+ <SidebarProvider>+ <ChatSidebar />+ </SidebarProvider>,+ );+}++async function openDeleteDialogFor(title: string) {+ const sessionRow = (await screen.findByText(title)).closest("div.group");+ if (!sessionRow) throw new Error(`row not found for ${title}`);+ const moreButton = within(sessionRow as HTMLElement).getByRole("button", {+ name: /more actions/i,+ });+ fireEvent.pointerDown(moreButton, { button: 0 });+ const deleteItem = await screen.findByRole("menuitem", {+ name: /delete chat/i,+ });+ fireEvent.click(deleteItem);+}++describe("ChatSidebar — delete flow", () => {+ beforeEach(() => {+ toastMock.mockClear();+ useCopilotUIStore.setState({ sessionToDelete: null });+ server.use(+ getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),+ );+ });++ afterEach(() => {+ server.resetHandlers();+ });++ it("opens the delete dialog with the chosen session title", async () => {+ renderSidebar();++ await openDeleteDialogFor("Other chat");++ expect(+ await screen.findByRole("heading", { name: /delete chat/i }),+ ).toBeDefined();+ expect(screen.getByText(/"Other chat"/)).toBeDefined();+ expect(useCopilotUIStore.getState().sessionToDelete).toMatchObject({+ id: "s2",+ title: "Other chat",+ });+ });++ it("clears the staged session when Cancel is clicked", async () => {+ renderSidebar();++ await openDeleteDialogFor("Active chat");+ expect(useCopilotUIStore.getState().sessionToDelete).not.toBeNull();++ const cancelButton = await screen.findByRole("button", { name: /cancel/i });+ fireEvent.click(cancelButton);++ expect(useCopilotUIStore.getState().sessionToDelete).toBeNull();+ });++ it("closes the dialog after a successful delete", async () => {+ server.use(getDeleteV2DeleteSessionMockHandler());+ renderSidebar();++ await openDeleteDialogFor("Other chat");+ expect(+ await screen.findByRole("heading", { name: /delete chat/i }),+ ).toBeDefined();+ const confirmButton = await screen.findByRole("button", {+ name: /^delete$/i,+ });+ fireEvent.click(confirmButton);++ await vi.waitFor(() => {+ expect(useCopilotUIStore.getState().sessionToDelete).toBeNull();+ });+ await vi.waitFor(() => {+ expect(+ screen.queryByRole("heading", { name: /delete chat/i }),+ ).toBeNull();+ });+ expect(toastMock).not.toHaveBeenCalled();+ });++ it("toasts on delete failure and clears the staged session", async () => {+ server.use(getDeleteV2DeleteSessionMockHandler422());+ renderSidebar();++ await openDeleteDialogFor("Active chat");+ const confirmButton = await screen.findByRole("button", {+ name: /^delete$/i,+ });+ fireEvent.click(confirmButton);++ await vi.waitFor(() => {+ expect(toastMock).toHaveBeenCalledTimes(1);+ });+ expect(toastMock.mock.calls[0][0]).toMatchObject({+ title: "Failed to delete chat",+ variant: "destructive",+ });+ expect(useCopilotUIStore.getState().sessionToDelete).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/TurnStatsBar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/TurnStatsBar.test.tsxindex 9b48fd0c71..134357e641 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/TurnStatsBar.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/TurnStatsBar.test.tsx@@ -1,12 +1,30 @@-import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import {+ act,+ fireEvent,+ render,+ screen,+} from "@/tests/integrations/test-utils";import type { UIDataTypes, UIMessage, UITools } from "ai";-import { describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { TurnStatsBar } from "../TurnStatsBar";+import { useElapsedTimer } from "../useElapsedTimer";type Msg = UIMessage<unknown, UIDataTypes, UITools>;const EMPTY: Msg[] = [];+interface HarnessProps {+ isRunning: boolean;+ anchor?: string | null;+}++// Renders TurnStatsBar driven by the real useElapsedTimer hook so the timer's+// behaviour is observable through the rendered "Thought for Xs" label.+function TimerHarness({ isRunning, anchor }: HarnessProps) {+ const { elapsedSeconds } = useElapsedTimer(isRunning, anchor);+ return <TurnStatsBar turnMessages={EMPTY} elapsedSeconds={elapsedSeconds} />;+}+describe("TurnStatsBar", () => {it("renders nothing when there is no time, no timestamp, and no counters", () => {const { container } = render(<TurnStatsBar turnMessages={EMPTY} />);@@ -104,3 +122,83 @@ describe("TurnStatsBar", () => {expect(bar?.textContent).toMatch(/1\s*action/);});});++describe("TurnStatsBar — live elapsed timer", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-04-23T10:00:00.000Z"));+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("ticks once per second while running so the label reflects real time", () => {+ const { container } = render(<TimerHarness isRunning />);+ // Elapsed starts at 0, which renders nothing.+ expect(container.firstChild).toBeNull();+ act(() => {+ vi.advanceTimersByTime(3000);+ });+ expect(screen.getByText(/Thought for 3s/)).toBeDefined();+ });++ it("freezes the displayed elapsed time when isRunning flips to false", () => {+ const { rerender } = render(<TimerHarness isRunning />);+ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(screen.getByText(/Thought for 2s/)).toBeDefined();++ rerender(<TimerHarness isRunning={false} />);+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ // No further ticks — label stays at the last reading.+ expect(screen.getByText(/Thought for 2s/)).toBeDefined();+ });++ it("anchors to an ISO timestamp so a fresh mount reflects real elapsed time", () => {+ const anchor = new Date("2026-04-23T09:59:45.000Z").toISOString();+ render(<TimerHarness isRunning anchor={anchor} />);+ expect(screen.getByText(/Thought for 15s/)).toBeDefined();+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ expect(screen.getByText(/Thought for 20s/)).toBeDefined();+ });++ it("clamps a future-dated anchor to zero rather than a negative reading", () => {+ const anchor = new Date("2026-04-23T10:00:10.000Z").toISOString();+ const { container } = render(<TimerHarness isRunning anchor={anchor} />);+ // Elapsed clamped to 0 → TurnStatsBar renders nothing.+ expect(container.firstChild).toBeNull();+ });++ it("falls back to mount-time counting when the anchor is invalid", () => {+ const { container } = render(+ <TimerHarness isRunning anchor="not-a-date" />,+ );+ expect(container.firstChild).toBeNull();+ act(() => {+ vi.advanceTimersByTime(4000);+ });+ expect(screen.getByText(/Thought for 4s/)).toBeDefined();+ });++ it("re-syncs when a late-arriving anchor replaces the previous one mid-run", () => {+ const { rerender } = render(<TimerHarness isRunning anchor={null} />);+ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(screen.getByText(/Thought for 2s/)).toBeDefined();++ rerender(+ <TimerHarness+ isRunning+ anchor={new Date("2026-04-23T09:59:00.000Z").toISOString()}+ />,+ );+ // Clock is at 10:00:02, anchor is 60s earlier, so elapsed jumps to 62s.+ expect(screen.getByText(/Thought for 1m 2s/)).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/useElapsedTimer.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/useElapsedTimer.test.tsdeleted file mode 100644index f07a1c4c00..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/__tests__/useElapsedTimer.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { act, renderHook } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useElapsedTimer } from "../useElapsedTimer";--describe("useElapsedTimer", () => {- beforeEach(() => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-04-23T10:00:00.000Z"));- });- afterEach(() => {- vi.useRealTimers();- });-- it("starts at zero and ticks once per second while running", () => {- const { result } = renderHook(() => useElapsedTimer(true));- expect(result.current.elapsedSeconds).toBe(0);- act(() => vi.advanceTimersByTime(3000));- expect(result.current.elapsedSeconds).toBe(3);- });-- it("stops ticking and resets when isRunning flips to false", () => {- const { result, rerender } = renderHook(- ({ running }) => useElapsedTimer(running),- { initialProps: { running: true } },- );- act(() => vi.advanceTimersByTime(2000));- expect(result.current.elapsedSeconds).toBe(2);- rerender({ running: false });- act(() => vi.advanceTimersByTime(5000));- // No ticks after stop — elapsed stays at last reading until the next- // `running:true` transition, which re-anchors to the current time.- expect(result.current.elapsedSeconds).toBe(2);- });-- it("anchors to an ISO timestamp so a fresh mount reflects real elapsed time", () => {- // Anchor 15s in the past relative to the mocked system time.- const anchor = new Date("2026-04-23T09:59:45.000Z").toISOString();- const { result } = renderHook(() => useElapsedTimer(true, anchor));- expect(result.current.elapsedSeconds).toBe(15);- act(() => vi.advanceTimersByTime(5000));- expect(result.current.elapsedSeconds).toBe(20);- });-- it("clamps a future-dated anchor to zero rather than a negative seconds count", () => {- const anchor = new Date("2026-04-23T10:00:10.000Z").toISOString();- const { result } = renderHook(() => useElapsedTimer(true, anchor));- expect(result.current.elapsedSeconds).toBe(0);- });-- it("falls back to mount-time counting when anchor is invalid", () => {- const { result } = renderHook(() => useElapsedTimer(true, "not-a-date"));- expect(result.current.elapsedSeconds).toBe(0);- act(() => vi.advanceTimersByTime(4000));- expect(result.current.elapsedSeconds).toBe(4);- });-- it("re-syncs when a late-arriving anchor replaces the previous one mid-run", () => {- // Simulate the real case: timer mounts with no anchor (session data- // hasn't loaded yet), starts counting from mount. Then the session- // query resolves and surfaces the actual server timestamp, which should- // correct the elapsed reading rather than being ignored.- const { result, rerender } = renderHook(- ({ anchor }: { anchor: string | null }) => useElapsedTimer(true, anchor),- { initialProps: { anchor: null as string | null } },- );- act(() => vi.advanceTimersByTime(2000));- expect(result.current.elapsedSeconds).toBe(2);-- rerender({- anchor: new Date("2026-04-23T09:59:00.000Z").toISOString(),- });- // Clock is at 10:00:02 (after the 2s advance), anchor is 60s earlier,- // so elapsed jumps to 62.- expect(result.current.elapsedSeconds).toBe(62);- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.test.tsdeleted file mode 100644index 7c61390f1f..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.test.ts+++ /dev/null@@ -1,554 +0,0 @@-import type { UIMessage } from "ai";-import { describe, expect, it } from "vitest";-import {- ORIGINAL_TITLE,- deduplicateMessages,- extractSendMessageText,- formatNotificationTitle,- getSendSuppressionReason,- parseSessionIDs,- shouldDebounceReconnect,- shouldSuppressDuplicateSend,-} from "./helpers";--describe("formatNotificationTitle", () => {- it("returns base title when count is 0", () => {- expect(formatNotificationTitle(0)).toBe(ORIGINAL_TITLE);- });-- it("returns formatted title with count", () => {- expect(formatNotificationTitle(3)).toBe(- `(3) AutoPilot is ready - ${ORIGINAL_TITLE}`,- );- });-- it("returns base title for negative count", () => {- expect(formatNotificationTitle(-1)).toBe(ORIGINAL_TITLE);- });-- it("returns base title for NaN", () => {- expect(formatNotificationTitle(NaN)).toBe(ORIGINAL_TITLE);- });-- it("returns formatted title for count of 1", () => {- expect(formatNotificationTitle(1)).toBe(- `(1) AutoPilot is ready - ${ORIGINAL_TITLE}`,- );- });-});--describe("parseSessionIDs", () => {- it("returns empty set for null", () => {- expect(parseSessionIDs(null)).toEqual(new Set());- });-- it("returns empty set for undefined", () => {- expect(parseSessionIDs(undefined)).toEqual(new Set());- });-- it("returns empty set for empty string", () => {- expect(parseSessionIDs("")).toEqual(new Set());- });-- it("parses valid JSON array of strings", () => {- expect(parseSessionIDs('["a","b","c"]')).toEqual(new Set(["a", "b", "c"]));- });-- it("filters out non-string elements", () => {- expect(parseSessionIDs('[1,"valid",null,true,"also-valid"]')).toEqual(- new Set(["valid", "also-valid"]),- );- });-- it("returns empty set for non-array JSON", () => {- expect(parseSessionIDs('{"key":"value"}')).toEqual(new Set());- });-- it("returns empty set for JSON string value", () => {- expect(parseSessionIDs('"oops"')).toEqual(new Set());- });-- it("returns empty set for JSON number value", () => {- expect(parseSessionIDs("42")).toEqual(new Set());- });-- it("returns empty set for malformed JSON", () => {- expect(parseSessionIDs("{broken")).toEqual(new Set());- });-- it("deduplicates entries", () => {- expect(parseSessionIDs('["a","a","b"]')).toEqual(new Set(["a", "b"]));- });-});--describe("extractSendMessageText", () => {- it("extracts text from a string argument", () => {- expect(extractSendMessageText("hello")).toBe("hello");- });-- it("extracts text from an object with text property", () => {- expect(extractSendMessageText({ text: "world" })).toBe("world");- });-- it("returns empty string for null", () => {- expect(extractSendMessageText(null)).toBe("");- });-- it("returns empty string for undefined", () => {- expect(extractSendMessageText(undefined)).toBe("");- });-- it("converts numbers to string", () => {- expect(extractSendMessageText(42)).toBe("42");- });-});--let msgCounter = 0;-function makeMsg(role: "user" | "assistant", text: string): UIMessage {- return {- id: `msg-${msgCounter++}`,- role,- parts: [{ type: "text", text }],- };-}--describe("shouldSuppressDuplicateSend", () => {- it("suppresses when reconnect is scheduled", () => {- expect(- shouldSuppressDuplicateSend({- text: "hello",- isReconnectScheduled: true,- lastSubmittedText: null,- messages: [],- }),- ).toBe(true);- });-- it("allows send when not reconnecting and no prior submission", () => {- expect(- shouldSuppressDuplicateSend({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: null,- messages: [],- }),- ).toBe(false);- });-- it("suppresses when text matches last submitted AND last user message", () => {- const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];- expect(- shouldSuppressDuplicateSend({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages,- }),- ).toBe(true);- });-- it("allows send when text matches last submitted but differs from last user message", () => {- const messages = [- makeMsg("user", "different"),- makeMsg("assistant", "reply"),- ];- expect(- shouldSuppressDuplicateSend({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages,- }),- ).toBe(false);- });-- it("allows send when text differs from last submitted", () => {- const messages = [makeMsg("user", "hello")];- expect(- shouldSuppressDuplicateSend({- text: "new message",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages,- }),- ).toBe(false);- });-- it("allows send when text is empty", () => {- expect(- shouldSuppressDuplicateSend({- text: "",- isReconnectScheduled: false,- lastSubmittedText: "",- messages: [],- }),- ).toBe(false);- });-- it("allows send with empty messages array even if text matches lastSubmitted", () => {- expect(- shouldSuppressDuplicateSend({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages: [],- }),- ).toBe(false);- });-});--describe("getSendSuppressionReason", () => {- it("returns 'reconnecting' when reconnect is scheduled", () => {- expect(- getSendSuppressionReason({- text: "hello",- isReconnectScheduled: true,- lastSubmittedText: null,- messages: [],- }),- ).toBe("reconnecting");- });-- it("returns 'reconnecting' even when text would otherwise be a duplicate", () => {- const messages = [makeMsg("user", "hello")];- expect(- getSendSuppressionReason({- text: "hello",- isReconnectScheduled: true,- lastSubmittedText: "hello",- messages,- }),- ).toBe("reconnecting");- });-- it("returns 'duplicate' when text matches last submitted AND last user message", () => {- const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];- expect(- getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages,- }),- ).toBe("duplicate");- });-- it("returns null when text matches last submitted but differs from last user message", () => {- const messages = [- makeMsg("user", "different"),- makeMsg("assistant", "reply"),- ];- expect(- getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages,- }),- ).toBeNull();- });-- it("returns null when text differs from last submitted", () => {- const messages = [makeMsg("user", "hello")];- expect(- getSendSuppressionReason({- text: "new message",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages,- }),- ).toBeNull();- });-- it("returns null when not reconnecting and no prior submission", () => {- expect(- getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: null,- messages: [],- }),- ).toBeNull();- });-- it("returns null when text is empty", () => {- expect(- getSendSuppressionReason({- text: "",- isReconnectScheduled: false,- lastSubmittedText: "",- messages: [],- }),- ).toBeNull();- });-- it("returns null when messages array is empty even if text matches lastSubmitted", () => {- expect(- getSendSuppressionReason({- text: "hello",- isReconnectScheduled: false,- lastSubmittedText: "hello",- messages: [],- }),- ).toBeNull();- });-});--// Helper that creates messages with explicit IDs for dedup tests-function makeMsgWithId(- id: string,- role: "user" | "assistant",- text: string,-): UIMessage {- return { id, role, parts: [{ type: "text", text }] };-}--describe("deduplicateMessages", () => {- it("removes messages with duplicate IDs", () => {- const msgs = [- makeMsgWithId("1", "user", "hello"),- makeMsgWithId("1", "user", "hello"),- ];- expect(deduplicateMessages(msgs)).toHaveLength(1);- });-- it("removes non-adjacent assistant duplicates with different IDs (SSE replay)", () => {- const msgs = [- makeMsgWithId("u1", "user", "hello"),- makeMsgWithId("a1", "assistant", "Plan of Attack"),- makeMsgWithId("a2", "assistant", "Next step"),- // SSE replay appends the same content with new IDs- makeMsgWithId("a3", "assistant", "Plan of Attack"),- makeMsgWithId("a4", "assistant", "Next step"),- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(3); // user + 2 unique assistant msgs- expect(result.map((m) => m.id)).toEqual(["u1", "a1", "a2"]);- });-- it("keeps identical assistant replies to different user prompts", () => {- const msgs = [- makeMsgWithId("u1", "user", "What is 2+2?"),- makeMsgWithId("a1", "assistant", "4"),- makeMsgWithId("u2", "user", "What is 1+3?"),- makeMsgWithId("a2", "assistant", "4"),- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(4);- });-- it("keeps second answer when same question is asked twice in one session", () => {- // Regression: scoping by user message TEXT instead of ID would treat both- // turns as the same context and drop the second identical assistant reply.- const msgs = [- makeMsgWithId("u1", "user", "What is 2+2?"),- makeMsgWithId("a1", "assistant", "4"),- makeMsgWithId("u2", "user", "What is 2+2?"), // same question, different ID- makeMsgWithId("a2", "assistant", "4"), // same answer — must be kept- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(4);- expect(result.map((m) => m.id)).toEqual(["u1", "a1", "u2", "a2"]);- });-- it("removes adjacent assistant duplicates", () => {- const msgs = [- makeMsgWithId("u1", "user", "hello"),- makeMsgWithId("a1", "assistant", "hi there"),- makeMsgWithId("a2", "assistant", "hi there"),- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(2);- });-- it("handles empty message list", () => {- expect(deduplicateMessages([])).toEqual([]);- });-- it("passes through unique messages unchanged", () => {- const msgs = [- makeMsgWithId("u1", "user", "question 1"),- makeMsgWithId("a1", "assistant", "answer 1"),- makeMsgWithId("u2", "user", "question 2"),- makeMsgWithId("a2", "assistant", "answer 2"),- ];- expect(deduplicateMessages(msgs)).toHaveLength(4);- });-- it("does not create false positives for text parts that contain the separator", () => {- // "a|b" + "c" and "a" + "b|c" previously collided when joined with "|"- const msgs: UIMessage[] = [- makeMsgWithId("u1", "user", "hello"),- {- id: "a1",- role: "assistant",- parts: [- { type: "text", text: "a|b" },- { type: "text", text: "c" },- ],- },- {- id: "a2",- role: "assistant",- parts: [- { type: "text", text: "a" },- { type: "text", text: "b|c" },- ],- },- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(3); // both assistant messages should be kept- });-- it("deduplicates by toolCallId for tool-call parts", () => {- const msgs: UIMessage[] = [- makeMsgWithId("u1", "user", "run tool"),- {- id: "a1",- role: "assistant",- parts: [- {- type: "dynamic-tool",- toolCallId: "tc-1",- toolName: "test",- state: "input-available",- input: {},- },- ],- },- {- id: "a2",- role: "assistant",- parts: [- {- type: "dynamic-tool",- toolCallId: "tc-1",- toolName: "test",- state: "input-available",- input: {},- },- ],- },- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(2); // user + first tool call- });-- it("passes through assistant messages with empty parts without deduplicating them", () => {- // contentFingerprint === "[]" when parts is empty; the guard skips fingerprint- // tracking so these messages are never incorrectly deduplicated against each other.- const msgs: UIMessage[] = [- makeMsgWithId("u1", "user", "hello"),- { id: "a1", role: "assistant", parts: [] },- { id: "a2", role: "assistant", parts: [] },- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(3); // both empty-parts messages are kept- });-- it("does not collapse structurally different no-text parts to the same fingerprint", () => {- // Parts lacking both 'text' and 'toolCallId' (e.g. step-start) previously- // all mapped to "" causing false-positive deduplication. Now JSON.stringify(p)- // is used as the fallback so distinct part shapes produce distinct fingerprints.- const msgs: UIMessage[] = [- makeMsgWithId("u1", "user", "hello"),- {- id: "a1",- role: "assistant",- parts: [{ type: "step-start" }],- },- {- id: "a2",- role: "assistant",- parts: [{ type: "step-start" }],- },- ];- const result = deduplicateMessages(msgs);- expect(result).toHaveLength(2); // duplicate step-start messages are deduped- });-});--describe("shouldDebounceReconnect", () => {- const WINDOW_MS = 1_500;-- it("returns null for the first reconnect (lastResumeAt === 0)", () => {- expect(shouldDebounceReconnect(0, 10_000, WINDOW_MS)).toBeNull();- });-- it("returns null for a negative lastResumeAt sentinel", () => {- // Defensive: a negative value is still treated as "no reconnect yet".- expect(shouldDebounceReconnect(-1, 10_000, WINDOW_MS)).toBeNull();- });-- it("returns the remaining delay when now is inside the window", () => {- // 500ms since the last resume — the caller must wait another 1000ms- // before the storm cap reopens.- const remaining = shouldDebounceReconnect(1_000, 1_500, WINDOW_MS);- expect(remaining).toBe(1_000);- });-- it("coalesces a reconnect that arrives immediately after the previous resume", () => {- // now === lastResumeAt → sinceLastResume === 0, so the full window remains.- const remaining = shouldDebounceReconnect(5_000, 5_000, WINDOW_MS);- expect(remaining).toBe(WINDOW_MS);- });-- it("returns null when exactly on the window boundary", () => {- // sinceLastResume === windowMs is NOT inside the window — the next- // reconnect should fire immediately.- expect(shouldDebounceReconnect(1_000, 2_500, WINDOW_MS)).toBeNull();- });-- it("returns null when the window has elapsed", () => {- expect(shouldDebounceReconnect(1_000, 5_000, WINDOW_MS)).toBeNull();- });-- it("returns a small remaining delay at the far edge of the window", () => {- // 1ms before the window closes → 1ms left.- const remaining = shouldDebounceReconnect(1_000, 2_499, WINDOW_MS);- expect(remaining).toBe(1);- });-- it("collapses a burst of reconnects into one debounced scheduling", () => {- // Simulates the browser tab-throttle storm: three reconnect calls fire- // within a single second after the last resume. Only the first slot- // would actually run; subsequent calls must always be coalesced.- const lastResumeAt = 10_000;- const firstCallRemaining = shouldDebounceReconnect(- lastResumeAt,- 10_100,- WINDOW_MS,- );- const secondCallRemaining = shouldDebounceReconnect(- lastResumeAt,- 10_200,- WINDOW_MS,- );- const thirdCallRemaining = shouldDebounceReconnect(- lastResumeAt,- 10_300,- WINDOW_MS,- );- expect(firstCallRemaining).toBe(1_400);- expect(secondCallRemaining).toBe(1_300);- expect(thirdCallRemaining).toBe(1_200);- });-- it("allows a reconnect to fire immediately once the window has passed", () => {- // After the window expires, a retry that came in earlier can now fire- // rather than stalling the loop. Guards against the regression that- // motivated the coalesce-instead-of-drop fix.- const lastResumeAt = 10_000;- expect(- shouldDebounceReconnect(lastResumeAt, 10_500, WINDOW_MS),- ).not.toBeNull();- expect(shouldDebounceReconnect(lastResumeAt, 11_500, WINDOW_MS)).toBeNull();- });-- it("honours a custom windowMs value", () => {- // Shouldn't hard-code 1500 anywhere: the helper is generic over the- // window.- expect(shouldDebounceReconnect(1_000, 1_500, 2_000)).toBe(1_500);- expect(shouldDebounceReconnect(1_000, 3_500, 2_000)).toBeNull();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/store.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/store.test.tsdeleted file mode 100644index 71683d65cb..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/store.test.ts+++ /dev/null@@ -1,216 +0,0 @@-import { beforeEach, describe, expect, it } from "vitest";-import type { ArtifactRef } from "./store";-import { useCopilotUIStore } from "./store";--function makeArtifact(id: string, title = `file-${id}`): ArtifactRef {- return {- id,- title,- mimeType: "text/plain",- sourceUrl: `/api/proxy/api/workspace/files/${id}/download`,- origin: "agent",- };-}--function resetStore() {- useCopilotUIStore.setState({- artifactPanel: {- isOpen: false,- isMinimized: false,- isMaximized: false,- width: 600,- activeArtifact: null,- history: [],- },- });-}--describe("artifactPanel store actions", () => {- beforeEach(resetStore);-- it("openArtifact opens the panel and sets the active artifact", () => {- const a = makeArtifact("a");- useCopilotUIStore.getState().openArtifact(a);- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(true);- expect(s.isMinimized).toBe(false);- expect(s.activeArtifact?.id).toBe("a");- expect(s.history).toEqual([]);- });-- it("openArtifact pushes the previous artifact onto history", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(b);- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.activeArtifact?.id).toBe("b");- expect(s.history.map((h) => h.id)).toEqual(["a"]);- });-- it("openArtifact does NOT push history when re-opening the same artifact", () => {- const a = makeArtifact("a");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(a);- expect(useCopilotUIStore.getState().artifactPanel.history).toEqual([]);- });-- it("openArtifact pops the top of history when returning to it (A→B→A)", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(b);- useCopilotUIStore.getState().openArtifact(a); // ping-pong- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.activeArtifact?.id).toBe("a");- // History was [a]; returning to a should pop, not push.- expect(s.history).toEqual([]);- });-- it("goBackArtifact pops the last entry and becomes active", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(b);- useCopilotUIStore.getState().goBackArtifact();- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.activeArtifact?.id).toBe("a");- expect(s.history).toEqual([]);- });-- it("goBackArtifact is a no-op when history is empty", () => {- const a = makeArtifact("a");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().goBackArtifact();- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.activeArtifact?.id).toBe("a");- });-- it("closeArtifactPanel keeps activeArtifact (for exit animation) and clears history", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(b);- useCopilotUIStore.getState().closeArtifactPanel();- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.isMinimized).toBe(false);- expect(s.activeArtifact?.id).toBe("b");- expect(s.history).toEqual([]);- });-- it("openArtifact does not resurrect a previously closed artifact into history", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().closeArtifactPanel();- useCopilotUIStore.getState().openArtifact(b);-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(true);- expect(s.activeArtifact?.id).toBe("b");- expect(s.history).toEqual([]);- });-- it("openArtifact ignores non-previewable artifacts", () => {- const binary = {- ...makeArtifact("bin", "artifact.bin"),- mimeType: "application/octet-stream",- };-- useCopilotUIStore.getState().openArtifact(binary);-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.activeArtifact).toBeNull();- expect(s.history).toEqual([]);- });-- it("resetArtifactPanel clears active artifact and history", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(b);- useCopilotUIStore.getState().maximizeArtifactPanel();-- useCopilotUIStore.getState().resetArtifactPanel();-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.isMinimized).toBe(false);- expect(s.isMaximized).toBe(false);- expect(s.activeArtifact).toBeNull();- expect(s.history).toEqual([]);- });-- it("minimize/restore toggles isMinimized without touching activeArtifact", () => {- const a = makeArtifact("a");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().minimizeArtifactPanel();- expect(useCopilotUIStore.getState().artifactPanel.isMinimized).toBe(true);- useCopilotUIStore.getState().restoreArtifactPanel();- expect(useCopilotUIStore.getState().artifactPanel.isMinimized).toBe(false);- expect(useCopilotUIStore.getState().artifactPanel.activeArtifact?.id).toBe(- "a",- );- });-- it("maximize sets isMaximized and clears isMinimized", () => {- const a = makeArtifact("a");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().minimizeArtifactPanel();- useCopilotUIStore.getState().maximizeArtifactPanel();- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isMaximized).toBe(true);- expect(s.isMinimized).toBe(false);- });-- it("restoreArtifactPanel clears both isMinimized and isMaximized", () => {- const a = makeArtifact("a");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().maximizeArtifactPanel();- useCopilotUIStore.getState().restoreArtifactPanel();- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isMaximized).toBe(false);- expect(s.isMinimized).toBe(false);- });-- it("setArtifactPanelWidth updates width and clears isMaximized", () => {- useCopilotUIStore.getState().maximizeArtifactPanel();- useCopilotUIStore.getState().setArtifactPanelWidth(720);- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.width).toBe(720);- expect(s.isMaximized).toBe(false);- });-- it("history is capped at 25 entries (MAX_HISTORY)", () => {- // Open 27 artifacts sequentially (A0..A26). History should never exceed 25.- for (let i = 0; i < 27; i++) {- useCopilotUIStore.getState().openArtifact(makeArtifact(`a${i}`));- }- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.activeArtifact?.id).toBe("a26");- expect(s.history.length).toBe(25);- // The oldest entry (a0) should have been dropped; a1 is the earliest surviving.- expect(s.history[0].id).toBe("a1");- expect(s.history[24].id).toBe("a25");- });-- it("clearCopilotLocalData resets artifact panel to default", () => {- const a = makeArtifact("a");- const b = makeArtifact("b");- useCopilotUIStore.getState().openArtifact(a);- useCopilotUIStore.getState().openArtifact(b);- useCopilotUIStore.getState().maximizeArtifactPanel();-- useCopilotUIStore.getState().clearCopilotLocalData();-- const s = useCopilotUIStore.getState().artifactPanel;- expect(s.isOpen).toBe(false);- expect(s.isMinimized).toBe(false);- expect(s.isMaximized).toBe(false);- expect(s.activeArtifact).toBeNull();- expect(s.history).toEqual([]);- expect(s.width).toBe(600); // DEFAULT_PANEL_WIDTH- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/__tests__/helpers.test.tssimilarity index 99%rename from autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/helpers.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/__tests__/helpers.test.tsindex 62a47cbdab..959b51deab 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/__tests__/helpers.test.ts@@ -1,6 +1,6 @@import type { RJSFSchema } from "@rjsf/utils";import { describe, expect, it } from "vitest";-import { buildInputSchema, extractDefaults, isFormValid } from "./helpers";+import { buildInputSchema, extractDefaults, isFormValid } from "../helpers";describe("buildInputSchema", () => {it("returns null for falsy input", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/titleForStatus.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.tssimilarity index 94%rename from autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/titleForStatus.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.tsindex bdceb287b3..daaa21c1ed 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/titleForStatus.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { titleForStatus } from "./ExecutionStartedCard";+import { titleForStatus } from "../ExecutionStartedCard";describe("titleForStatus", () => {it.each([diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/__tests__/clarifying-questions.test.tssimilarity index 98%rename from autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.test.tsrename to autogpt_platform/frontend/src/app/(platform)/copilot/tools/__tests__/clarifying-questions.test.tsindex 6a2e4b9541..301397297b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/clarifying-questions.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/__tests__/clarifying-questions.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import {buildClarificationAnswersMessage,normalizeClarifyingQuestions,-} from "./clarifying-questions";+} from "../clarifying-questions";describe("normalizeClarifyingQuestions", () => {it("returns normalized questions with trimmed lowercase keywords", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/helpers.test.tssimilarity index 99%rename from autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.tsrename to autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/helpers.test.tsindex 34d8f3c2cf..16179ba8b1 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/helpers.test.ts@@ -7,7 +7,7 @@ import {getTierLabel,TIERS,TIER_ORDER,-} from "./helpers";+} from "../helpers";describe("formatCost", () => {it("returns 'Free' for any tier with cost = 0", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/__tests__/helpers.test.tssimilarity index 94%rename from autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/helpers.test.tsrename to autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/__tests__/helpers.test.tsindex 01b804ba1e..3a3b0f26be 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/__tests__/helpers.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from "vitest";-import { formatLastUsed, maskAPIKey } from "./helpers";+import { formatLastUsed, maskAPIKey } from "../helpers";describe("maskAPIKey", () => {test("joins head, a fixed mask, and tail", () => {diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.tssimilarity index 99%rename from autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.tsrename to autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.tsindex 0801e35936..3590de8ca7 100644--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.ts+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.ts@@ -6,7 +6,7 @@ import {getWorkspaceDownloadErrorMessage,fetchWorkspaceDownloadOnce,fetchWorkspaceDownloadWithRetry,-} from "./route.helpers";+} from "../route.helpers";describe("isWorkspaceDownloadRequest", () => {const VALID_UUID = "550e8400-e29b-41d4-a716-446655440000";diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsxnew file mode 100644index 0000000000..0902954b3e--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx@@ -0,0 +1,142 @@+import {+ render,+ screen,+ cleanup,+ fireEvent,+ waitFor,+} from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";+import { CredentialsInput } from "../CredentialsInput";++vi.mock("@/hooks/useCredentials", () => ({ default: vi.fn() }));+vi.mock("@/lib/autogpt-server-api/context", () => ({+ useBackendAPI: vi.fn(),+ BackendAPIProvider: ({ children }: { children: React.ReactNode }) => children,+}));+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: vi.fn(),+ useToast: () => ({ toast: vi.fn(), dismiss: vi.fn(), toasts: [] }),+}));+vi.mock("@/lib/oauth-popup", () => ({+ openOAuthPopup: vi.fn(),+ OAUTH_ERROR_WINDOW_CLOSED: "Sign-in window was closed",+ OAUTH_ERROR_FLOW_CANCELED: "OAuth flow was canceled",+ OAUTH_ERROR_FLOW_TIMED_OUT: "OAuth flow timed out",+}));+vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({+ postV2InitiateOauthLoginForAnMcpServer: vi.fn(),+}));++import useCredentials from "@/hooks/useCredentials";+import { useBackendAPI } from "@/lib/autogpt-server-api/context";+import { openOAuthPopup } from "@/lib/oauth-popup";++const mockUseCredentials = useCredentials as unknown as ReturnType<+ typeof vi.fn+>;+const mockUseBackendAPI = useBackendAPI as unknown as ReturnType<typeof vi.fn>;+const mockOpenOAuthPopup = openOAuthPopup as unknown as ReturnType<+ typeof vi.fn+>;++const baseSchema: BlockIOCredentialsSubSchema = {+ credentials_provider: ["google"],+ credentials_types: ["oauth2"],+ credentials_scopes: ["drive.file", "drive.metadata"],+} as BlockIOCredentialsSubSchema;++type CredentialsReturn = ReturnType<typeof useCredentials>;+type BackendAPI = ReturnType<typeof useBackendAPI>;++function makeCredentialsReturn(overrides: Partial<CredentialsReturn> = {}) {+ return {+ provider: "google",+ providerName: "Google",+ savedCredentials: [],+ upgradeableCredentials: [],+ supportsApiKey: false,+ supportsOAuth2: true,+ supportsUserPassword: false,+ supportsHostScoped: false,+ isLoading: false,+ isSystemProvider: false,+ schema: baseSchema,+ oAuthCallback: vi.fn().mockResolvedValue({+ id: "new-cred",+ type: "oauth2",+ title: "Connected Google",+ provider: "google",+ scopes: ["drive.file", "drive.metadata"],+ }),+ mcpOAuthCallback: vi.fn(),+ createAPIKeyCredentials: vi.fn(),+ createUserPasswordCredentials: vi.fn(),+ createHostScopedCredentials: vi.fn(),+ deleteCredentials: vi.fn(),+ discriminatorValue: undefined,+ ...overrides,+ };+}++function makeBackendAPI(overrides: Partial<BackendAPI> = {}) {+ return {+ oAuthLogin: vi.fn().mockResolvedValue({+ login_url: "https://accounts.google.com/o/oauth2/auth",+ state_token: "state-xyz",+ }),+ onWebSocketMessage: vi.fn().mockReturnValue(() => {}),+ connectWebSocket: vi.fn().mockResolvedValue(undefined),+ sendWebSocketMessage: vi.fn(),+ ...overrides,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ mockUseBackendAPI.mockReturnValue(makeBackendAPI());+});++afterEach(() => {+ cleanup();+});++describe("CredentialsInput – OAuth flow", () => {+ it("clicking the Add account button calls oAuthLogin without a credentialID", async () => {+ const oAuthLoginMock = vi.fn().mockResolvedValue({+ login_url: "https://accounts.google.com/o/oauth2/auth",+ state_token: "state-xyz",+ });+ mockUseBackendAPI.mockReturnValue(+ makeBackendAPI({ oAuthLogin: oAuthLoginMock }),+ );++ mockUseCredentials.mockReturnValue(makeCredentialsReturn());++ mockOpenOAuthPopup.mockReturnValue({+ promise: Promise.resolve({ code: "code-2", state: "state-xyz" }),+ cleanup: { abort: vi.fn() },+ });++ render(+ <CredentialsInput+ schema={baseSchema}+ onSelectCredentials={vi.fn()}+ showTitle={false}+ />,+ );++ const addAccountButton = await screen.findByRole("button", {+ name: /add account/i,+ });+ fireEvent.click(addAccountButton);++ await waitFor(() => {+ expect(oAuthLoginMock).toHaveBeenCalledWith(+ "google",+ ["drive.file", "drive.metadata"],+ undefined,+ );+ });+ });+});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.tsindex bb68980ac1..487e63d3d3 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts@@ -11,6 +11,8 @@ import {processCredentialDeletion,findExistingHostCredentials,hasExistingHostCredential,+ OAUTH_TIMEOUT_MS,+ MASKED_KEY_LENGTH,resolveActionTarget,headerPairsToRecord,addHeaderPairToList,@@ -19,23 +21,26 @@ import {} from "../helpers";describe("countSupportedTypes", () => {- it("returns 0 when nothing is supported", () => {+ it("returns 0 when no types are supported", () => {expect(countSupportedTypes(false, false, false, false)).toBe(0);});- it("returns 1 for a single supported type", () => {+ it("returns 1 when only one type is supported", () => {expect(countSupportedTypes(true, false, false, false)).toBe(1);expect(countSupportedTypes(false, true, false, false)).toBe(1);+ expect(countSupportedTypes(false, false, true, false)).toBe(1);+ expect(countSupportedTypes(false, false, false, true)).toBe(1);});- it("returns count of all true flags", () => {+ it("returns correct count for multiple types", () => {+ expect(countSupportedTypes(true, true, false, false)).toBe(2);+ expect(countSupportedTypes(true, true, true, false)).toBe(3);expect(countSupportedTypes(true, true, true, true)).toBe(4);- expect(countSupportedTypes(true, false, true, false)).toBe(2);});});describe("getSupportedTypes", () => {- it("returns empty array when nothing supported", () => {+ it("returns empty array when no types are supported", () => {expect(getSupportedTypes(false, false, false, false)).toEqual([]);});@@ -43,118 +48,157 @@ describe("getSupportedTypes", () => {expect(getSupportedTypes(true, false, false, false)).toEqual(["oauth2"]);});- it("returns all supported types in order", () => {- expect(getSupportedTypes(true, true, true, true)).toEqual([- "oauth2",- "api_key",+ it("returns api_key when supportsApiKey is true", () => {+ expect(getSupportedTypes(false, true, false, false)).toEqual(["api_key"]);+ });++ it("returns user_password when supportsUserPassword is true", () => {+ expect(getSupportedTypes(false, false, true, false)).toEqual(["user_password",+ ]);+ });++ it("returns host_scoped when supportsHostScoped is true", () => {+ expect(getSupportedTypes(false, false, false, true)).toEqual(["host_scoped",]);});- it("returns only the enabled types", () => {- expect(getSupportedTypes(false, true, false, true)).toEqual([+ it("returns all types in order when all are supported", () => {+ expect(getSupportedTypes(true, true, true, true)).toEqual([+ "oauth2","api_key",+ "user_password","host_scoped",]);});});describe("getCredentialTypeLabel", () => {- it("returns 'OAuth' for oauth2", () => {+ it("returns OAuth for oauth2", () => {expect(getCredentialTypeLabel("oauth2")).toBe("OAuth");});- it("returns 'API Key' for api_key", () => {+ it("returns API Key for api_key", () => {expect(getCredentialTypeLabel("api_key")).toBe("API Key");});- it("returns 'Password' for user_password", () => {+ it("returns Password for user_password", () => {expect(getCredentialTypeLabel("user_password")).toBe("Password");});- it("returns 'Headers' for host_scoped", () => {+ it("returns Headers for host_scoped", () => {expect(getCredentialTypeLabel("host_scoped")).toBe("Headers");});});describe("getActionButtonText", () => {- it("returns generic text for multiple types without existing", () => {- expect(getActionButtonText(true, true, false, false, false)).toBe(- "Add credential",- );- });+ describe("when multiple types are supported", () => {+ it("returns generic text without existing credentials", () => {+ expect(getActionButtonText(true, true, false, false, false)).toBe(+ "Add credential",+ );+ });- it("returns generic text for multiple types with existing", () => {- expect(getActionButtonText(true, true, false, false, true)).toBe(- "Add another credential",- );+ it("returns generic text with existing credentials", () => {+ expect(getActionButtonText(true, true, false, false, true)).toBe(+ "Add another credential",+ );+ });});- it("returns specific text for single OAuth2 without existing", () => {- expect(getActionButtonText(true, false, false, false, false)).toBe(- "Add account",- );- });+ describe("when only OAuth2 is supported", () => {+ it("returns 'Add account' without existing credentials", () => {+ expect(getActionButtonText(true, false, false, false, false)).toBe(+ "Add account",+ );+ });- it("returns specific text for single OAuth2 with existing", () => {- expect(getActionButtonText(true, false, false, false, true)).toBe(- "Connect another account",- );+ it("returns 'Connect another account' with existing credentials", () => {+ expect(getActionButtonText(true, false, false, false, true)).toBe(+ "Connect another account",+ );+ });});- it("returns API key text for single API key", () => {- expect(getActionButtonText(false, true, false, false, false)).toBe(- "Add API key",- );- expect(getActionButtonText(false, true, false, false, true)).toBe(- "Use a new API key",- );+ describe("when only API key is supported", () => {+ it("returns 'Add API key' without existing credentials", () => {+ expect(getActionButtonText(false, true, false, false, false)).toBe(+ "Add API key",+ );+ });++ it("returns 'Use a new API key' with existing credentials", () => {+ expect(getActionButtonText(false, true, false, false, true)).toBe(+ "Use a new API key",+ );+ });});- it("returns password text for single user_password", () => {- expect(getActionButtonText(false, false, true, false, false)).toBe(- "Add username and password",- );- expect(getActionButtonText(false, false, true, false, true)).toBe(- "Add a new username and password",- );+ describe("when only user_password is supported", () => {+ it("returns 'Add username and password' without existing credentials", () => {+ expect(getActionButtonText(false, false, true, false, false)).toBe(+ "Add username and password",+ );+ });++ it("returns 'Add a new username and password' with existing credentials", () => {+ expect(getActionButtonText(false, false, true, false, true)).toBe(+ "Add a new username and password",+ );+ });});- it("returns headers text for single host_scoped", () => {- expect(getActionButtonText(false, false, false, true, false)).toBe(- "Add headers",- );- expect(getActionButtonText(false, false, false, true, true)).toBe(- "Update headers",- );+ describe("when only host_scoped is supported", () => {+ it("returns 'Add headers' without existing credentials", () => {+ expect(getActionButtonText(false, false, false, true, false)).toBe(+ "Add headers",+ );+ });++ it("returns 'Update headers' with existing credentials", () => {+ expect(getActionButtonText(false, false, false, true, true)).toBe(+ "Update headers",+ );+ });});- it("returns fallback text when no type is supported", () => {- expect(getActionButtonText(false, false, false, false, false)).toBe(- "Add credentials",- );- expect(getActionButtonText(false, false, false, false, true)).toBe(- "Add new credentials",- );+ describe("when no types are supported", () => {+ it("returns 'Add credentials' without existing credentials", () => {+ expect(getActionButtonText(false, false, false, false, false)).toBe(+ "Add credentials",+ );+ });++ it("returns 'Add new credentials' with existing credentials", () => {+ expect(getActionButtonText(false, false, false, false, true)).toBe(+ "Add new credentials",+ );+ });});});describe("getCredentialDisplayName", () => {it("returns title when present", () => {- expect(getCredentialDisplayName({ title: "My API Key" }, "Google")).toBe(- "My API Key",+ expect(+ getCredentialDisplayName({ title: "My Key", username: "user" }, "GitHub"),+ ).toBe("My Key");+ });++ it("falls back to username when title is missing", () => {+ expect(getCredentialDisplayName({ username: "jdoe" }, "GitHub")).toBe(+ "jdoe",);});- it("returns username when title is missing", () => {- expect(- getCredentialDisplayName({ username: "[email protected]" }, "Google"),- ).toBe("[email protected]");+ it("falls back to display name when both title and username are missing", () => {+ expect(getCredentialDisplayName({}, "GitHub")).toBe("Your GitHub account");});- it("returns fallback when both are missing", () => {- expect(getCredentialDisplayName({}, "Google")).toBe("Your Google account");+ it("falls back when title is empty string", () => {+ expect(getCredentialDisplayName({ title: "" }, "GitHub")).toBe(+ "Your GitHub account",+ );});});@@ -167,73 +211,125 @@ describe("isSystemCredential", () => {expect(isSystemCredential({ is_system: false })).toBe(false);});+ it("returns false when title is null", () => {+ expect(isSystemCredential({ title: null })).toBe(false);+ });++ it("returns false when title is absent", () => {+ expect(isSystemCredential({})).toBe(false);+ });+it("returns true when title contains 'system'", () => {- expect(isSystemCredential({ title: "System Default" })).toBe(true);+ expect(isSystemCredential({ title: "System API Key" })).toBe(true);});- it("returns true when title starts with 'use credits for'", () => {- expect(isSystemCredential({ title: "Use Credits for OpenAI" })).toBe(true);+ it("returns true when title contains 'system' case-insensitively", () => {+ expect(isSystemCredential({ title: "SYSTEM key" })).toBe(true);});- it("returns true when title contains 'use credits'", () => {- expect(isSystemCredential({ title: "Please use credits" })).toBe(true);+ it("returns true when title starts with 'Use credits for'", () => {+ expect(isSystemCredential({ title: "Use credits for OpenAI" })).toBe(true);});- it("returns false for regular credential", () => {- expect(isSystemCredential({ title: "My API Key" })).toBe(false);+ it("returns true when title starts with 'use credits for' case-insensitively", () => {+ expect(isSystemCredential({ title: "use credits for Anthropic" })).toBe(+ true,+ );});- it("returns false when title is null", () => {- expect(isSystemCredential({ title: null })).toBe(false);+ it("returns true when title contains 'use credits'", () => {+ expect(isSystemCredential({ title: "Please use credits here" })).toBe(true);+ });++ it("returns false for a normal credential title", () => {+ expect(isSystemCredential({ title: "My Personal Key" })).toBe(false);});});describe("filterSystemCredentials", () => {- it("removes system credentials", () => {- const creds = [- { title: "My Key", is_system: false },- { title: "System Default", is_system: true },- { title: "Other Key" },+ it("returns empty array for empty input", () => {+ expect(filterSystemCredentials([])).toEqual([]);+ });++ it("filters out system credentials", () => {+ const credentials = [+ { title: "My Key" },+ { title: "System Key" },+ { title: "Use credits for OpenAI" },+ { title: "Personal Token" },];- expect(filterSystemCredentials(creds)).toEqual([- { title: "My Key", is_system: false },- { title: "Other Key" },- ]);+ const result = filterSystemCredentials(credentials);+ expect(result).toEqual([{ title: "My Key" }, { title: "Personal Token" }]);});- it("returns empty array when all are system", () => {- expect(filterSystemCredentials([{ is_system: true }])).toEqual([]);+ it("filters out credentials with is_system flag", () => {+ const credentials = [+ { title: "Normal", is_system: false },+ { title: "Hidden", is_system: true },+ ];+ const result = filterSystemCredentials(credentials);+ expect(result).toEqual([{ title: "Normal", is_system: false }]);});});describe("getSystemCredentials", () => {+ it("returns empty array for empty input", () => {+ expect(getSystemCredentials([])).toEqual([]);+ });+it("returns only system credentials", () => {- const creds = [- { title: "My Key", is_system: false },- { title: "System Default", is_system: true },+ const credentials = [+ { title: "My Key" },+ { title: "System Key" },+ { title: "Use credits for OpenAI" },+ { title: "Personal Token" },];- expect(getSystemCredentials(creds)).toEqual([- { title: "System Default", is_system: true },+ const result = getSystemCredentials(credentials);+ expect(result).toEqual([+ { title: "System Key" },+ { title: "Use credits for OpenAI" },]);});++ it("returns credentials with is_system flag", () => {+ const credentials = [+ { title: "Normal", is_system: false },+ { title: "Hidden", is_system: true },+ ];+ const result = getSystemCredentials(credentials);+ expect(result).toEqual([{ title: "Hidden", is_system: true }]);+ });+});++describe("constants", () => {+ it("OAUTH_TIMEOUT_MS is 5 minutes", () => {+ expect(OAUTH_TIMEOUT_MS).toBe(300000);+ });++ it("MASKED_KEY_LENGTH is 15", () => {+ expect(MASKED_KEY_LENGTH).toBe(15);+ });});describe("processCredentialDeletion", () => {const cred = { id: "cred-1", title: "My Key" };- it("clears state on successful deletion", async () => {+ it("returns cleared state on successful deletion", async () => {const deleteFn = vi.fn().mockResolvedValue({ deleted: true });const state = await processCredentialDeletion(cred,- "other",+ "other-id",deleteFn,false,);++ expect(deleteFn).toHaveBeenCalledWith("cred-1", false);expect(state.credentialToDelete).toBeNull();+ expect(state.warningMessage).toBeNull();expect(state.shouldUnselectCurrent).toBe(false);});- it("flags shouldUnselectCurrent when selected credential is deleted", async () => {+ it("sets shouldUnselectCurrent when deleting the selected credential", async () => {const deleteFn = vi.fn().mockResolvedValue({ deleted: true });const state = await processCredentialDeletion(cred,@@ -241,14 +337,16 @@ describe("processCredentialDeletion", () => {deleteFn,false,);+expect(state.shouldUnselectCurrent).toBe(true);+ expect(state.credentialToDelete).toBeNull();});- it("returns warning when confirmation needed", async () => {+ it("returns warning state when confirmation is needed", async () => {const deleteFn = vi.fn().mockResolvedValue({deleted: false,need_confirmation: true,- message: "In use",+ message: "Used by 3 agents",});const state = await processCredentialDeletion(cred,@@ -256,11 +354,13 @@ describe("processCredentialDeletion", () => {deleteFn,false,);- expect(state.warningMessage).toBe("In use");++ expect(state.warningMessage).toBe("Used by 3 agents");expect(state.credentialToDelete).toBe(cred);+ expect(state.shouldUnselectCurrent).toBe(false);});- it("uses fallback warning when message is empty", async () => {+ it("uses default warning message when none provided", async () => {const deleteFn = vi.fn().mockResolvedValue({deleted: false,need_confirmation: true,@@ -272,45 +372,82 @@ describe("processCredentialDeletion", () => {deleteFn,false,);+expect(state.warningMessage).toBe("This credential is in use. Force delete?",);});- it("passes force=true to the delete function", async () => {+ it("passes force flag to delete function", async () => {const deleteFn = vi.fn().mockResolvedValue({ deleted: true });await processCredentialDeletion(cred, undefined, deleteFn, true);+expect(deleteFn).toHaveBeenCalledWith("cred-1", true);});++ it("returns unchanged state for unknown result shape", async () => {+ const deleteFn = vi.fn().mockResolvedValue({ deleted: false });+ const state = await processCredentialDeletion(+ cred,+ undefined,+ deleteFn,+ false,+ );++ expect(state.warningMessage).toBeNull();+ expect(state.credentialToDelete).toBe(cred);+ expect(state.shouldUnselectCurrent).toBe(false);+ });});describe("findExistingHostCredentials", () => {- const creds = [- { id: "1", type: "host_scoped", host: "a.com" },- { id: "2", type: "api_key" },- { id: "3", type: "host_scoped", host: "b.com" },+ const credentials = [+ { id: "1", type: "host_scoped", host: "api.example.com" },+ { id: "2", type: "host_scoped", host: "api.other.com" },+ { id: "3", type: "api_key" },+ { id: "4", type: "host_scoped", host: "api.example.com" },];- it("returns matching host_scoped credentials", () => {- expect(findExistingHostCredentials(creds, "a.com")).toEqual([- { id: "1", type: "host_scoped", host: "a.com" },- ]);+ it("finds credentials matching the given host", () => {+ const result = findExistingHostCredentials(credentials, "api.example.com");+ expect(result).toHaveLength(2);+ expect(result[0].id).toBe("1");+ expect(result[1].id).toBe("4");+ });++ it("returns empty array when no match", () => {+ expect(findExistingHostCredentials(credentials, "unknown.com")).toEqual([]);+ });++ it("ignores non-host_scoped credentials", () => {+ const result = findExistingHostCredentials(credentials, "api.other.com");+ expect(result).toHaveLength(1);+ expect(result[0].id).toBe("2");});- it("returns empty when no match", () => {- expect(findExistingHostCredentials(creds, "c.com")).toEqual([]);+ it("returns empty array for empty credentials list", () => {+ expect(findExistingHostCredentials([], "any.com")).toEqual([]);});});describe("hasExistingHostCredential", () => {- const creds = [{ type: "host_scoped", host: "x.com" }, { type: "api_key" }];+ const credentials = [+ { type: "host_scoped", host: "api.example.com" },+ { type: "api_key" },+ ];++ it("returns true when a host_scoped credential exists for the host", () => {+ expect(hasExistingHostCredential(credentials, "api.example.com")).toBe(+ true,+ );+ });- it("returns true for existing host", () => {- expect(hasExistingHostCredential(creds, "x.com")).toBe(true);+ it("returns false when no matching host_scoped credential exists", () => {+ expect(hasExistingHostCredential(credentials, "other.com")).toBe(false);});- it("returns false for non-existing host", () => {- expect(hasExistingHostCredential(creds, "y.com")).toBe(false);+ it("returns false for empty credentials list", () => {+ expect(hasExistingHostCredential([], "any.com")).toBe(false);});});@@ -346,104 +483,72 @@ describe("resolveActionTarget", () => {it("returns null when nothing is supported", () => {expect(resolveActionTarget(false, false, false, false, false)).toBeNull();});-- it("prefers oauth over api_key when not multiple types", () => {- expect(resolveActionTarget(false, true, true, false, false)).toBe("oauth");- });});describe("headerPairsToRecord", () => {- it("converts pairs to record filtering empty entries", () => {+ it("converts non-empty pairs to record", () => {const pairs = [{ key: "Authorization", value: "Bearer token" },{ key: "", value: "ignored" },{ key: "X-Key", value: "" },- { key: " Accept ", value: " application/json " },];expect(headerPairsToRecord(pairs)).toEqual({Authorization: "Bearer token",- Accept: "application/json",});});- it("returns empty object for empty pairs", () => {- expect(headerPairsToRecord([])).toEqual({});+ it("trims keys and values", () => {+ expect(+ headerPairsToRecord([{ key: " Accept ", value: " text/html " }]),+ ).toEqual({ Accept: "text/html" });});- it("returns empty object when all pairs are empty", () => {- expect(headerPairsToRecord([{ key: "", value: "" }])).toEqual({});+ it("returns empty object for empty pairs", () => {+ expect(headerPairsToRecord([])).toEqual({});});});describe("addHeaderPairToList", () => {- it("adds a new empty pair to the list", () => {- const pairs = [{ key: "a", value: "b" }];- const result = addHeaderPairToList(pairs);+ it("appends an empty pair", () => {+ const result = addHeaderPairToList([{ key: "a", value: "b" }]);expect(result).toHaveLength(2);expect(result[1]).toEqual({ key: "", value: "" });});-- it("does not mutate the original array", () => {- const pairs = [{ key: "a", value: "b" }];- const result = addHeaderPairToList(pairs);- expect(pairs).toHaveLength(1);- expect(result).not.toBe(pairs);- });});describe("removeHeaderPairFromList", () => {- it("removes the pair at the given index", () => {+ it("removes the pair at index", () => {const pairs = [{ key: "a", value: "1" },{ key: "b", value: "2" },- { key: "c", value: "3" },];- const result = removeHeaderPairFromList(pairs, 1);- expect(result).toEqual([- { key: "a", value: "1" },- { key: "c", value: "3" },+ expect(removeHeaderPairFromList(pairs, 0)).toEqual([+ { key: "b", value: "2" },]);});- it("does not remove when only one pair remains", () => {+ it("does not remove the last pair", () => {const pairs = [{ key: "a", value: "1" }];- const result = removeHeaderPairFromList(pairs, 0);- expect(result).toHaveLength(1);- expect(result).toBe(pairs);- });-- it("does not mutate the original array", () => {- const pairs = [- { key: "a", value: "1" },- { key: "b", value: "2" },- ];- removeHeaderPairFromList(pairs, 0);- expect(pairs).toHaveLength(2);+ expect(removeHeaderPairFromList(pairs, 0)).toBe(pairs);});});describe("updateHeaderPairInList", () => {- it("updates the key of a pair at the given index", () => {- const pairs = [- { key: "a", value: "1" },- { key: "b", value: "2" },- ];- const result = updateHeaderPairInList(pairs, 0, "key", "updated");- expect(result[0]).toEqual({ key: "updated", value: "1" });- expect(result[1]).toEqual({ key: "b", value: "2" });+ it("updates key at the given index", () => {+ const pairs = [{ key: "a", value: "1" }];+ const result = updateHeaderPairInList(pairs, 0, "key", "b");+ expect(result[0]).toEqual({ key: "b", value: "1" });});- it("updates the value of a pair at the given index", () => {+ it("updates value at the given index", () => {const pairs = [{ key: "a", value: "1" }];- const result = updateHeaderPairInList(pairs, 0, "value", "new-val");- expect(result[0]).toEqual({ key: "a", value: "new-val" });+ const result = updateHeaderPairInList(pairs, 0, "value", "2");+ expect(result[0]).toEqual({ key: "a", value: "2" });});- it("does not mutate the original array or pair objects", () => {+ it("does not mutate originals", () => {const pairs = [{ key: "a", value: "1" }];- const result = updateHeaderPairInList(pairs, 0, "key", "b");+ updateHeaderPairInList(pairs, 0, "key", "b");expect(pairs[0].key).toBe("a");- expect(result).not.toBe(pairs);- expect(result[0]).not.toBe(pairs[0]);});});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/useCredentialsInput.test.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/useCredentialsInput.test.tsdeleted file mode 100644index d604daf2b5..0000000000--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/useCredentialsInput.test.ts+++ /dev/null@@ -1,220 +0,0 @@-import { renderHook, act } from "@testing-library/react";-import { describe, expect, it, vi, beforeEach } from "vitest";-import type {- BlockIOCredentialsSubSchema,- CredentialsMetaResponse,-} from "@/lib/autogpt-server-api";--vi.mock("@/hooks/useCredentials", () => ({ default: vi.fn() }));-vi.mock("@/lib/autogpt-server-api/context", () => ({- useBackendAPI: vi.fn(),-}));-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: vi.fn(),-}));-vi.mock("@/lib/oauth-popup", () => ({- openOAuthPopup: vi.fn(),- OAUTH_ERROR_WINDOW_CLOSED: "Sign-in window was closed",- OAUTH_ERROR_FLOW_CANCELED: "OAuth flow was canceled",- OAUTH_ERROR_FLOW_TIMED_OUT: "OAuth flow timed out",-}));-vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({- postV2InitiateOauthLoginForAnMcpServer: vi.fn(),-}));--import useCredentials from "@/hooks/useCredentials";-import { useBackendAPI } from "@/lib/autogpt-server-api/context";-import { openOAuthPopup } from "@/lib/oauth-popup";-import { useCredentialsInput } from "../useCredentialsInput";--const mockUseCredentials = useCredentials as unknown as ReturnType<- typeof vi.fn->;-const mockUseBackendAPI = useBackendAPI as unknown as ReturnType<typeof vi.fn>;-const mockOpenOAuthPopup = openOAuthPopup as unknown as ReturnType<- typeof vi.fn->;--function makeCred(- partial: Partial<CredentialsMetaResponse>,-): CredentialsMetaResponse {- return {- id: "cred-id",- provider: "google",- type: "oauth2",- title: "Test",- scopes: [],- ...partial,- } as CredentialsMetaResponse;-}--const baseSchema: BlockIOCredentialsSubSchema = {- credentials_provider: ["google"],- credentials_types: ["oauth2"],- credentials_scopes: ["drive.file", "drive.metadata"],-} as BlockIOCredentialsSubSchema;--function makeCredentialsReturn(overrides: Record<string, any> = {}) {- return {- provider: "google",- providerName: "Google",- savedCredentials: [],- upgradeableCredentials: [],- supportsApiKey: false,- supportsOAuth2: true,- supportsUserPassword: false,- supportsHostScoped: false,- isLoading: false,- isSystemProvider: false,- schema: baseSchema,- oAuthCallback: vi.fn().mockResolvedValue(makeCred({ id: "new-cred" })),- mcpOAuthCallback: vi.fn(),- createAPIKeyCredentials: vi.fn(),- createUserPasswordCredentials: vi.fn(),- createHostScopedCredentials: vi.fn(),- deleteCredentials: vi.fn(),- discriminatorValue: undefined,- ...overrides,- };-}--beforeEach(() => {- vi.clearAllMocks();- mockUseBackendAPI.mockReturnValue({- oAuthLogin: vi.fn().mockResolvedValue({- login_url: "https://accounts.google.com/o/oauth2/auth",- state_token: "state-123",- }),- });-});--describe("useCredentialsInput – upgradeableCredentials", () => {- it("exposes userUpgradeableCredentials filtered from upgradeableCredentials", () => {- const upgradeable = makeCred({- id: "narrow",- title: "Narrow Cred",- scopes: ["drive.file"],- });- const systemUpgradeable = makeCred({- id: "sys",- title: "Use credits for Google",- scopes: ["drive.file"],- is_system: true,- });-- mockUseCredentials.mockReturnValue(- makeCredentialsReturn({- savedCredentials: [],- upgradeableCredentials: [upgradeable, systemUpgradeable],- }),- );-- const onSelect = vi.fn();- const { result } = renderHook(() =>- useCredentialsInput({- schema: baseSchema,- onSelectCredential: onSelect,- }),- );-- expect(result.current.isLoading).toBe(false);- if (result.current.isLoading) return;-- // System credentials should be filtered out- expect(result.current.userUpgradeableCredentials).toHaveLength(1);- expect(result.current.userUpgradeableCredentials![0].id).toBe("narrow");- });-});--describe("useCredentialsInput – handleScopeUpgrade", () => {- it("passes credentialID through executeOAuthFlow to oAuthLogin", async () => {- const oAuthLoginMock = vi.fn().mockResolvedValue({- login_url: "https://accounts.google.com/o/oauth2/auth",- state_token: "state-abc",- });- mockUseBackendAPI.mockReturnValue({ oAuthLogin: oAuthLoginMock });-- const oAuthCallback = vi.fn().mockResolvedValue(- makeCred({- id: "upgraded-cred",- scopes: ["drive.file", "drive.metadata"],- }),- );-- mockUseCredentials.mockReturnValue(- makeCredentialsReturn({ oAuthCallback }),- );-- mockOpenOAuthPopup.mockReturnValue({- promise: Promise.resolve({ code: "auth-code", state: "state-abc" }),- cleanup: { abort: vi.fn() },- });-- const onSelect = vi.fn();- const { result } = renderHook(() =>- useCredentialsInput({- schema: baseSchema,- onSelectCredential: onSelect,- }),- );-- expect(result.current.isLoading).toBe(false);- if (result.current.isLoading) return;-- await act(async () => {- await result.current.handleScopeUpgrade!("existing-cred-id");- });-- expect(oAuthLoginMock).toHaveBeenCalledWith(- "google",- ["drive.file", "drive.metadata"],- "existing-cred-id",- );- });-- it("handleOAuthLogin calls executeOAuthFlow without credentialID", async () => {- const oAuthLoginMock = vi.fn().mockResolvedValue({- login_url: "https://accounts.google.com/o/oauth2/auth",- state_token: "state-xyz",- });- mockUseBackendAPI.mockReturnValue({ oAuthLogin: oAuthLoginMock });-- const oAuthCallback = vi.fn().mockResolvedValue(- makeCred({- id: "new-cred",- scopes: ["drive.file", "drive.metadata"],- }),- );-- mockUseCredentials.mockReturnValue(- makeCredentialsReturn({ oAuthCallback }),- );-- mockOpenOAuthPopup.mockReturnValue({- promise: Promise.resolve({ code: "code-2", state: "state-xyz" }),- cleanup: { abort: vi.fn() },- });-- const onSelect = vi.fn();- const { result } = renderHook(() =>- useCredentialsInput({- schema: baseSchema,- onSelectCredential: onSelect,- }),- );-- expect(result.current.isLoading).toBe(false);- if (result.current.isLoading) return;-- await act(async () => {- await result.current.handleOAuthLogin!();- });-- // credentialID should be undefined (not passed)- expect(oAuthLoginMock).toHaveBeenCalledWith(- "google",- ["drive.file", "drive.metadata"],- undefined,- );- });-});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.test.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.test.tsdeleted file mode 100644index bc9b46142b..0000000000--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.test.ts+++ /dev/null@@ -1,554 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import {- countSupportedTypes,- getSupportedTypes,- getCredentialTypeLabel,- getActionButtonText,- getCredentialDisplayName,- isSystemCredential,- filterSystemCredentials,- getSystemCredentials,- processCredentialDeletion,- findExistingHostCredentials,- hasExistingHostCredential,- OAUTH_TIMEOUT_MS,- MASKED_KEY_LENGTH,- resolveActionTarget,- headerPairsToRecord,- addHeaderPairToList,- removeHeaderPairFromList,- updateHeaderPairInList,-} from "./helpers";--describe("countSupportedTypes", () => {- it("returns 0 when no types are supported", () => {- expect(countSupportedTypes(false, false, false, false)).toBe(0);- });-- it("returns 1 when only one type is supported", () => {- expect(countSupportedTypes(true, false, false, false)).toBe(1);- expect(countSupportedTypes(false, true, false, false)).toBe(1);- expect(countSupportedTypes(false, false, true, false)).toBe(1);- expect(countSupportedTypes(false, false, false, true)).toBe(1);- });-- it("returns correct count for multiple types", () => {- expect(countSupportedTypes(true, true, false, false)).toBe(2);- expect(countSupportedTypes(true, true, true, false)).toBe(3);- expect(countSupportedTypes(true, true, true, true)).toBe(4);- });-});--describe("getSupportedTypes", () => {- it("returns empty array when no types are supported", () => {- expect(getSupportedTypes(false, false, false, false)).toEqual([]);- });-- it("returns oauth2 when supportsOAuth2 is true", () => {- expect(getSupportedTypes(true, false, false, false)).toEqual(["oauth2"]);- });-- it("returns api_key when supportsApiKey is true", () => {- expect(getSupportedTypes(false, true, false, false)).toEqual(["api_key"]);- });-- it("returns user_password when supportsUserPassword is true", () => {- expect(getSupportedTypes(false, false, true, false)).toEqual([- "user_password",- ]);- });-- it("returns host_scoped when supportsHostScoped is true", () => {- expect(getSupportedTypes(false, false, false, true)).toEqual([- "host_scoped",- ]);- });-- it("returns all types in order when all are supported", () => {- expect(getSupportedTypes(true, true, true, true)).toEqual([- "oauth2",- "api_key",- "user_password",- "host_scoped",- ]);- });-});--describe("getCredentialTypeLabel", () => {- it("returns OAuth for oauth2", () => {- expect(getCredentialTypeLabel("oauth2")).toBe("OAuth");- });-- it("returns API Key for api_key", () => {- expect(getCredentialTypeLabel("api_key")).toBe("API Key");- });-- it("returns Password for user_password", () => {- expect(getCredentialTypeLabel("user_password")).toBe("Password");- });-- it("returns Headers for host_scoped", () => {- expect(getCredentialTypeLabel("host_scoped")).toBe("Headers");- });-});--describe("getActionButtonText", () => {- describe("when multiple types are supported", () => {- it("returns generic text without existing credentials", () => {- expect(getActionButtonText(true, true, false, false, false)).toBe(- "Add credential",- );- });-- it("returns generic text with existing credentials", () => {- expect(getActionButtonText(true, true, false, false, true)).toBe(- "Add another credential",- );- });- });-- describe("when only OAuth2 is supported", () => {- it("returns 'Add account' without existing credentials", () => {- expect(getActionButtonText(true, false, false, false, false)).toBe(- "Add account",- );- });-- it("returns 'Connect another account' with existing credentials", () => {- expect(getActionButtonText(true, false, false, false, true)).toBe(- "Connect another account",- );- });- });-- describe("when only API key is supported", () => {- it("returns 'Add API key' without existing credentials", () => {- expect(getActionButtonText(false, true, false, false, false)).toBe(- "Add API key",- );- });-- it("returns 'Use a new API key' with existing credentials", () => {- expect(getActionButtonText(false, true, false, false, true)).toBe(- "Use a new API key",- );- });- });-- describe("when only user_password is supported", () => {- it("returns 'Add username and password' without existing credentials", () => {- expect(getActionButtonText(false, false, true, false, false)).toBe(- "Add username and password",- );- });-- it("returns 'Add a new username and password' with existing credentials", () => {- expect(getActionButtonText(false, false, true, false, true)).toBe(- "Add a new username and password",- );- });- });-- describe("when only host_scoped is supported", () => {- it("returns 'Add headers' without existing credentials", () => {- expect(getActionButtonText(false, false, false, true, false)).toBe(- "Add headers",- );- });-- it("returns 'Update headers' with existing credentials", () => {- expect(getActionButtonText(false, false, false, true, true)).toBe(- "Update headers",- );- });- });-- describe("when no types are supported", () => {- it("returns 'Add credentials' without existing credentials", () => {- expect(getActionButtonText(false, false, false, false, false)).toBe(- "Add credentials",- );- });-- it("returns 'Add new credentials' with existing credentials", () => {- expect(getActionButtonText(false, false, false, false, true)).toBe(- "Add new credentials",- );- });- });-});--describe("getCredentialDisplayName", () => {- it("returns title when present", () => {- expect(- getCredentialDisplayName({ title: "My Key", username: "user" }, "GitHub"),- ).toBe("My Key");- });-- it("falls back to username when title is missing", () => {- expect(getCredentialDisplayName({ username: "jdoe" }, "GitHub")).toBe(- "jdoe",- );- });-- it("falls back to display name when both title and username are missing", () => {- expect(getCredentialDisplayName({}, "GitHub")).toBe("Your GitHub account");- });-- it("falls back when title is empty string", () => {- expect(getCredentialDisplayName({ title: "" }, "GitHub")).toBe(- "Your GitHub account",- );- });-});--describe("isSystemCredential", () => {- it("returns true when is_system is true", () => {- expect(isSystemCredential({ is_system: true })).toBe(true);- });-- it("returns false when is_system is false and no title", () => {- expect(isSystemCredential({ is_system: false })).toBe(false);- });-- it("returns false when title is null", () => {- expect(isSystemCredential({ title: null })).toBe(false);- });-- it("returns false when title is absent", () => {- expect(isSystemCredential({})).toBe(false);- });-- it("returns true when title contains 'system'", () => {- expect(isSystemCredential({ title: "System API Key" })).toBe(true);- });-- it("returns true when title contains 'system' case-insensitively", () => {- expect(isSystemCredential({ title: "SYSTEM key" })).toBe(true);- });-- it("returns true when title starts with 'Use credits for'", () => {- expect(isSystemCredential({ title: "Use credits for OpenAI" })).toBe(true);- });-- it("returns true when title starts with 'use credits for' case-insensitively", () => {- expect(isSystemCredential({ title: "use credits for Anthropic" })).toBe(- true,- );- });-- it("returns true when title contains 'use credits'", () => {- expect(isSystemCredential({ title: "Please use credits here" })).toBe(true);- });-- it("returns false for a normal credential title", () => {- expect(isSystemCredential({ title: "My Personal Key" })).toBe(false);- });-});--describe("filterSystemCredentials", () => {- it("returns empty array for empty input", () => {- expect(filterSystemCredentials([])).toEqual([]);- });-- it("filters out system credentials", () => {- const credentials = [- { title: "My Key" },- { title: "System Key" },- { title: "Use credits for OpenAI" },- { title: "Personal Token" },- ];- const result = filterSystemCredentials(credentials);- expect(result).toEqual([{ title: "My Key" }, { title: "Personal Token" }]);- });-- it("filters out credentials with is_system flag", () => {- const credentials = [- { title: "Normal", is_system: false },- { title: "Hidden", is_system: true },- ];- const result = filterSystemCredentials(credentials);- expect(result).toEqual([{ title: "Normal", is_system: false }]);- });-});--describe("getSystemCredentials", () => {- it("returns empty array for empty input", () => {- expect(getSystemCredentials([])).toEqual([]);- });-- it("returns only system credentials", () => {- const credentials = [- { title: "My Key" },- { title: "System Key" },- { title: "Use credits for OpenAI" },- { title: "Personal Token" },- ];- const result = getSystemCredentials(credentials);- expect(result).toEqual([- { title: "System Key" },- { title: "Use credits for OpenAI" },- ]);- });-- it("returns credentials with is_system flag", () => {- const credentials = [- { title: "Normal", is_system: false },- { title: "Hidden", is_system: true },- ];- const result = getSystemCredentials(credentials);- expect(result).toEqual([{ title: "Hidden", is_system: true }]);- });-});--describe("constants", () => {- it("OAUTH_TIMEOUT_MS is 5 minutes", () => {- expect(OAUTH_TIMEOUT_MS).toBe(300000);- });-- it("MASKED_KEY_LENGTH is 15", () => {- expect(MASKED_KEY_LENGTH).toBe(15);- });-});--describe("processCredentialDeletion", () => {- const cred = { id: "cred-1", title: "My Key" };-- it("returns cleared state on successful deletion", async () => {- const deleteFn = vi.fn().mockResolvedValue({ deleted: true });- const state = await processCredentialDeletion(- cred,- "other-id",- deleteFn,- false,- );-- expect(deleteFn).toHaveBeenCalledWith("cred-1", false);- expect(state.credentialToDelete).toBeNull();- expect(state.warningMessage).toBeNull();- expect(state.shouldUnselectCurrent).toBe(false);- });-- it("sets shouldUnselectCurrent when deleting the selected credential", async () => {- const deleteFn = vi.fn().mockResolvedValue({ deleted: true });- const state = await processCredentialDeletion(- cred,- "cred-1",- deleteFn,- false,- );-- expect(state.shouldUnselectCurrent).toBe(true);- expect(state.credentialToDelete).toBeNull();- });-- it("returns warning state when confirmation is needed", async () => {- const deleteFn = vi.fn().mockResolvedValue({- deleted: false,- need_confirmation: true,- message: "Used by 3 agents",- });- const state = await processCredentialDeletion(- cred,- undefined,- deleteFn,- false,- );-- expect(state.warningMessage).toBe("Used by 3 agents");- expect(state.credentialToDelete).toBe(cred);- expect(state.shouldUnselectCurrent).toBe(false);- });-- it("uses default warning message when none provided", async () => {- const deleteFn = vi.fn().mockResolvedValue({- deleted: false,- need_confirmation: true,- message: "",- });- const state = await processCredentialDeletion(- cred,- undefined,- deleteFn,- false,- );-- expect(state.warningMessage).toBe(- "This credential is in use. Force delete?",- );- });-- it("passes force flag to delete function", async () => {- const deleteFn = vi.fn().mockResolvedValue({ deleted: true });- await processCredentialDeletion(cred, undefined, deleteFn, true);-- expect(deleteFn).toHaveBeenCalledWith("cred-1", true);- });-- it("returns unchanged state for unknown result shape", async () => {- const deleteFn = vi.fn().mockResolvedValue({ deleted: false });- const state = await processCredentialDeletion(- cred,- undefined,- deleteFn,- false,- );-- expect(state.warningMessage).toBeNull();- expect(state.credentialToDelete).toBe(cred);- expect(state.shouldUnselectCurrent).toBe(false);- });-});--describe("findExistingHostCredentials", () => {- const credentials = [- { id: "1", type: "host_scoped", host: "api.example.com" },- { id: "2", type: "host_scoped", host: "api.other.com" },- { id: "3", type: "api_key" },- { id: "4", type: "host_scoped", host: "api.example.com" },- ];-- it("finds credentials matching the given host", () => {- const result = findExistingHostCredentials(credentials, "api.example.com");- expect(result).toHaveLength(2);- expect(result[0].id).toBe("1");- expect(result[1].id).toBe("4");- });-- it("returns empty array when no match", () => {- expect(findExistingHostCredentials(credentials, "unknown.com")).toEqual([]);- });-- it("ignores non-host_scoped credentials", () => {- const result = findExistingHostCredentials(credentials, "api.other.com");- expect(result).toHaveLength(1);- expect(result[0].id).toBe("2");- });-- it("returns empty array for empty credentials list", () => {- expect(findExistingHostCredentials([], "any.com")).toEqual([]);- });-});--describe("hasExistingHostCredential", () => {- const credentials = [- { type: "host_scoped", host: "api.example.com" },- { type: "api_key" },- ];-- it("returns true when a host_scoped credential exists for the host", () => {- expect(hasExistingHostCredential(credentials, "api.example.com")).toBe(- true,- );- });-- it("returns false when no matching host_scoped credential exists", () => {- expect(hasExistingHostCredential(credentials, "other.com")).toBe(false);- });-- it("returns false for empty credentials list", () => {- expect(hasExistingHostCredential([], "any.com")).toBe(false);- });-});--describe("resolveActionTarget", () => {- it("returns type_selector when hasMultipleCredentialTypes is true", () => {- expect(resolveActionTarget(true, true, true, false, false)).toBe(- "type_selector",- );- });-- it("returns oauth when only OAuth2 is supported", () => {- expect(resolveActionTarget(false, true, false, false, false)).toBe("oauth");- });-- it("returns api_key when only API key is supported", () => {- expect(resolveActionTarget(false, false, true, false, false)).toBe(- "api_key",- );- });-- it("returns user_password when only user_password is supported", () => {- expect(resolveActionTarget(false, false, false, true, false)).toBe(- "user_password",- );- });-- it("returns host_scoped when only host_scoped is supported", () => {- expect(resolveActionTarget(false, false, false, false, true)).toBe(- "host_scoped",- );- });-- it("returns null when nothing is supported", () => {- expect(resolveActionTarget(false, false, false, false, false)).toBeNull();- });-});--describe("headerPairsToRecord", () => {- it("converts non-empty pairs to record", () => {- const pairs = [- { key: "Authorization", value: "Bearer token" },- { key: "", value: "ignored" },- { key: "X-Key", value: "" },- ];- expect(headerPairsToRecord(pairs)).toEqual({- Authorization: "Bearer token",- });- });-- it("trims keys and values", () => {- expect(- headerPairsToRecord([{ key: " Accept ", value: " text/html " }]),- ).toEqual({ Accept: "text/html" });- });-- it("returns empty object for empty pairs", () => {- expect(headerPairsToRecord([])).toEqual({});- });-});--describe("addHeaderPairToList", () => {- it("appends an empty pair", () => {- const result = addHeaderPairToList([{ key: "a", value: "b" }]);- expect(result).toHaveLength(2);- expect(result[1]).toEqual({ key: "", value: "" });- });-});--describe("removeHeaderPairFromList", () => {- it("removes the pair at index", () => {- const pairs = [- { key: "a", value: "1" },- { key: "b", value: "2" },- ];- expect(removeHeaderPairFromList(pairs, 0)).toEqual([- { key: "b", value: "2" },- ]);- });-- it("does not remove the last pair", () => {- const pairs = [{ key: "a", value: "1" }];- expect(removeHeaderPairFromList(pairs, 0)).toBe(pairs);- });-});--describe("updateHeaderPairInList", () => {- it("updates key at the given index", () => {- const pairs = [{ key: "a", value: "1" }];- const result = updateHeaderPairInList(pairs, 0, "key", "b");- expect(result[0]).toEqual({ key: "b", value: "1" });- });-- it("updates value at the given index", () => {- const pairs = [{ key: "a", value: "1" }];- const result = updateHeaderPairInList(pairs, 0, "value", "2");- expect(result[0]).toEqual({ key: "a", value: "2" });- });-- it("does not mutate originals", () => {- const pairs = [{ key: "a", value: "1" }];- updateHeaderPairInList(pairs, 0, "key", "b");- expect(pairs[0].key).toBe("a");- });-});diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/useGoogleDrivePicker.test.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/GoogleDrivePicker.test.tsxsimilarity index 57%rename from autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/useGoogleDrivePicker.test.tsrename to autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/GoogleDrivePicker.test.tsxindex bf31d6ab46..89a378f0b7 100644--- a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/useGoogleDrivePicker.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/GoogleDrivePicker.test.tsx@@ -1,5 +1,10 @@-import { renderHook, act } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";vi.mock("@/hooks/useCredentials", () => ({ default: vi.fn() }));vi.mock("@/components/molecules/Toast/use-toast", () => ({@@ -13,7 +18,12 @@ vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({postV1GetPickerToken: vi.fn(),}));vi.mock("@/app/api/helpers", () => ({- okData: vi.fn((resp: any) => (resp?.status === 200 ? resp.data : undefined)),+ okData: vi.fn((resp: { status?: number; data?: unknown } | undefined) =>+ resp?.status === 200 ? resp.data : undefined,+ ),+}));+vi.mock("@/components/contextual/CredentialsInput/CredentialsInput", () => ({+ CredentialsInput: () => <div data-testid="credentials-input" />,}));import useCredentials from "@/hooks/useCredentials";@@ -22,8 +32,8 @@ import {getGetV1GetSpecificCredentialByIdQueryOptions,postV1GetPickerToken,} from "@/app/api/__generated__/endpoints/integrations/integrations";-import { useGoogleDrivePicker } from "../useGoogleDrivePicker";import type { CredentialsMetaResponse } from "@/lib/autogpt-server-api";+import { GoogleDrivePicker } from "../GoogleDrivePicker";const mockUseCredentials = useCredentials as unknown as ReturnType<typeof vi.fn@@ -50,13 +60,6 @@ function makeCred(} as CredentialsMetaResponse;}-// Minimal react-query QueryClient mock-const mockFetchQuery = vi.fn();-vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ fetchQuery: mockFetchQuery }),-}));--// Mock Google globals for ensureLoaded + buildAndShowPickerfunction setupGoogleGlobals() {const setOAuthToken = vi.fn();const setDeveloperKey = vi.fn();@@ -66,44 +69,47 @@ function setupGoogleGlobals() {const addView = vi.fn();const build = vi.fn().mockReturnValue({ setVisible: vi.fn() });- // Use a class so `new PickerBuilder()` works properly in vitest 4.xclass MockPickerBuilder {- setOAuthToken = (...args: any[]) => {+ setOAuthToken = (...args: unknown[]) => {setOAuthToken(...args);return this;};- setDeveloperKey = (...args: any[]) => {+ setDeveloperKey = (...args: unknown[]) => {setDeveloperKey(...args);return this;};- setAppId = (...args: any[]) => {+ setAppId = (...args: unknown[]) => {setAppId(...args);return this;};- setCallback = (...args: any[]) => {+ setCallback = (...args: unknown[]) => {setCallback(...args);return this;};- enableFeature = (...args: any[]) => {+ enableFeature = (...args: unknown[]) => {enableFeature(...args);return this;};- addView = (...args: any[]) => {+ addView = (...args: unknown[]) => {addView(...args);return this;};- build = (...args: any[]) => build(...args);+ build = (...args: unknown[]) => build(...args);}class MockDocsView {setMode = vi.fn();- constructor(_viewId?: any) {}+ constructor(_viewId?: unknown) {}}- (window as any).gapi = {+ const mockedWindow = window as unknown as {+ gapi?: unknown;+ google?: unknown;+ };+ mockedWindow.gapi = {load: (_name: string, opts: { callback: () => void }) => opts.callback(),};- (window as any).google = {+ mockedWindow.google = {accounts: {oauth2: {initTokenClient: vi.fn().mockReturnValue({@@ -141,22 +147,47 @@ const toastMock = vi.fn();beforeEach(() => {vi.clearAllMocks();mockUseToast.mockReturnValue({ toast: toastMock });- mockGetQueryOptions.mockReturnValue({ queryKey: ["cred"], queryFn: vi.fn() });+ mockGetQueryOptions.mockReturnValue({+ queryKey: ["cred"],+ queryFn: () => Promise.resolve(undefined),+ });});afterEach(() => {- delete (window as any).gapi;- delete (window as any).google;+ const mockedWindow = window as unknown as {+ gapi?: unknown;+ google?: unknown;+ };+ delete mockedWindow.gapi;+ delete mockedWindow.google;});-describe("useGoogleDrivePicker – openPicker saved-credential flow", () => {- it("shows insufficient scopes toast when credential lacks required scopes", async () => {+function renderPicker(+ overrides: Partial<Parameters<typeof GoogleDrivePicker>[0]> = {},+) {+ const onPicked = vi.fn();+ const onCanceled = vi.fn();+ const onError = vi.fn();+ const utils = render(+ <GoogleDrivePicker+ scopes={["drive.file", "drive.metadata"]}+ developerKey="dev-key"+ clientId="client-id"+ appId="app-id"+ onPicked={onPicked}+ onCanceled={onCanceled}+ onError={onError}+ {...overrides}+ />,+ );+ return { ...utils, onPicked, onCanceled, onError };+}++describe("GoogleDrivePicker – click-to-open flow", () => {+ it("shows insufficient scopes toast and calls onError when credential lacks required scopes", async () => {const { build } = setupGoogleGlobals();- const savedCred = makeCred({- id: "narrow-cred",- scopes: ["drive.file"],- });+ const savedCred = makeCred({ id: "narrow-cred", scopes: ["drive.file"] });mockUseCredentials.mockReturnValue({provider: "google",@@ -171,44 +202,32 @@ describe("useGoogleDrivePicker – openPicker saved-credential flow", () => {isSystemProvider: false,});- // The credential returned by fetchQuery lacks the required scopes- mockFetchQuery.mockResolvedValue({- status: 200,- data: {- id: "narrow-cred",- type: "oauth2",- scopes: ["drive.file"],- },+ mockGetQueryOptions.mockReturnValue({+ queryKey: ["cred", "narrow-cred"],+ queryFn: () =>+ Promise.resolve({+ status: 200,+ data: { id: "narrow-cred", type: "oauth2", scopes: ["drive.file"] },+ }),});- const onError = vi.fn();- const onPicked = vi.fn();- const onCanceled = vi.fn();-- const { result } = renderHook(() =>- useGoogleDrivePicker({- scopes: ["drive.file", "drive.metadata"],- developerKey: "dev-key",- clientId: "client-id",- appId: "app-id",- onPicked,- onCanceled,- onError,- }),- );-- await act(async () => {- await result.current.handleOpenPicker();+ const { onError } = renderPicker();++ const button = await screen.findByRole("button", {+ name: /choose file\(s\) from google drive/i,+ });+ fireEvent.click(button);++ await waitFor(() => {+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Insufficient Permissions",+ variant: "destructive",+ }),+ );});- expect(toastMock).toHaveBeenCalledWith(- expect.objectContaining({- title: "Insufficient Permissions",- variant: "destructive",- }),- );expect(onError).toHaveBeenCalledWith(expect.any(Error));- // Picker should NOT have been builtexpect(build).not.toHaveBeenCalled();});@@ -233,51 +252,40 @@ describe("useGoogleDrivePicker – openPicker saved-credential flow", () => {isSystemProvider: false,});- // fetchQuery returns oauth2 credential with all scopes- mockFetchQuery.mockResolvedValue({- status: 200,- data: {- id: "full-cred",- type: "oauth2",- scopes: ["drive.file", "drive.metadata"],- },+ mockGetQueryOptions.mockReturnValue({+ queryKey: ["cred", "full-cred"],+ queryFn: () =>+ Promise.resolve({+ status: 200,+ data: {+ id: "full-cred",+ type: "oauth2",+ scopes: ["drive.file", "drive.metadata"],+ },+ }),});- // Mock picker token endpointmockPostPickerToken.mockResolvedValue({status: 200,data: { access_token: "ya29.picker-token" },});- const onError = vi.fn();- const onPicked = vi.fn();- const onCanceled = vi.fn();-- const { result } = renderHook(() =>- useGoogleDrivePicker({- scopes: ["drive.file", "drive.metadata"],- developerKey: "dev-key",- clientId: "client-id",- appId: "app-id",- onPicked,- onCanceled,- onError,- }),- );-- await act(async () => {- await result.current.handleOpenPicker();+ const { onError } = renderPicker();++ const button = await screen.findByRole("button", {+ name: /choose file\(s\) from google drive/i,});+ fireEvent.click(button);- // Should have fetched a picker token- expect(mockPostPickerToken).toHaveBeenCalledWith("google", "full-cred");- // Picker should have been built with the token+ await waitFor(() => {+ expect(mockPostPickerToken).toHaveBeenCalledWith("google", "full-cred");+ });expect(build).toHaveBeenCalled();expect(setOAuthToken).toHaveBeenCalledWith("ya29.picker-token");expect(onError).not.toHaveBeenCalled();});- it("calls onError when credential is not oauth2", async () => {+ it("calls onError when stored credential is not oauth2", async () => {setupGoogleGlobals();const savedCred = makeCred({@@ -299,35 +307,28 @@ describe("useGoogleDrivePicker – openPicker saved-credential flow", () => {isSystemProvider: false,});- mockFetchQuery.mockResolvedValue({- status: 200,- data: { id: "api-key-cred", type: "api_key" },+ mockGetQueryOptions.mockReturnValue({+ queryKey: ["cred", "api-key-cred"],+ queryFn: () =>+ Promise.resolve({+ status: 200,+ data: { id: "api-key-cred", type: "api_key" },+ }),});- const onError = vi.fn();- const onPicked = vi.fn();- const onCanceled = vi.fn();-- const { result } = renderHook(() =>- useGoogleDrivePicker({- scopes: ["drive.file"],- developerKey: "dev-key",- clientId: "client-id",- appId: "app-id",- onPicked,- onCanceled,- onError,- }),- );-- await act(async () => {- await result.current.handleOpenPicker();+ const { onError } = renderPicker({ scopes: ["drive.file"] });++ const button = await screen.findByRole("button", {+ name: /choose file\(s\) from google drive/i,});+ fireEvent.click(button);- expect(onError).toHaveBeenCalledWith(- expect.objectContaining({- message: expect.stringContaining("Failed to retrieve"),- }),- );+ await waitFor(() => {+ expect(onError).toHaveBeenCalledWith(+ expect.objectContaining({+ message: expect.stringContaining("Failed to retrieve"),+ }),+ );+ });});});diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/AudioRenderer.test.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/AudioRenderer.test.tssimilarity index 97%rename from autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/AudioRenderer.test.tsrename to autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/AudioRenderer.test.tsindex 9e650a1d12..150c14ad0e 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/AudioRenderer.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/AudioRenderer.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { audioRenderer } from "./AudioRenderer";+import { audioRenderer } from "../AudioRenderer";describe("AudioRenderer canRender", () => {it("detects audio file URLs by extension", () => {diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/CSVRenderer.test.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/CSVRenderer.test.tssimilarity index 98%rename from autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/CSVRenderer.test.tsrename to autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/CSVRenderer.test.tsindex 5576c54064..0667b3e51e 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/CSVRenderer.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/CSVRenderer.test.ts@@ -1,7 +1,7 @@import { render, screen } from "@testing-library/react";import type React from "react";import { describe, expect, it } from "vitest";-import { csvRenderer } from "./CSVRenderer";+import { csvRenderer } from "../CSVRenderer";function downloadText(value: string, filename = "t.csv"): string {const dl = csvRenderer.getDownloadContent?.(value, { filename });diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.test.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/HTMLRenderer.test.tsxsimilarity index 97%rename from autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.test.tsxrename to autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/HTMLRenderer.test.tsxindex 2e6408ebf4..e45b74ddd1 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/HTMLRenderer.test.tsx@@ -1,6 +1,6 @@import { cleanup, render } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";-import { htmlRenderer } from "./HTMLRenderer";+import { htmlRenderer } from "../HTMLRenderer";describe("HTMLRenderer", () => {afterEach(() => {diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/LinkRenderer.test.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/LinkRenderer.test.tssimilarity index 96%rename from autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/LinkRenderer.test.tsrename to autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/LinkRenderer.test.tsindex da80fdb945..8c180a0f61 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/LinkRenderer.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/LinkRenderer.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { linkRenderer } from "./LinkRenderer";+import { linkRenderer } from "../LinkRenderer";describe("LinkRenderer canRender", () => {it("detects plain HTTP URLs", () => {diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.test.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/VideoRenderer.test.tssimilarity index 97%rename from autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.test.tsrename to autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/VideoRenderer.test.tsindex 9b7d3bb6ea..3d36a568e4 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/VideoRenderer.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { videoRenderer } from "./VideoRenderer";+import { videoRenderer } from "../VideoRenderer";describe("VideoRenderer canRender", () => {it("detects direct video file URLs", () => {diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/WorkspaceFileRenderer.test.tssimilarity index 98%rename from autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.tsrename to autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/WorkspaceFileRenderer.test.tsindex 2def8d7268..8635f4f91b 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.ts+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/WorkspaceFileRenderer.test.ts@@ -5,7 +5,7 @@ import {isWorkspaceURI,buildWorkspaceURI,} from "@/lib/workspace-uri";-import { workspaceFileRenderer } from "./WorkspaceFileRenderer";+import { workspaceFileRenderer } from "../WorkspaceFileRenderer";describe("parseWorkspaceURI", () => {it("parses a full workspace URI with mime type", () => {diff --git a/autogpt_platform/frontend/src/hooks/useCredentials.test.ts b/autogpt_platform/frontend/src/hooks/__tests__/classifyCredentials.test.tssimilarity index 63%rename from autogpt_platform/frontend/src/hooks/useCredentials.test.tsrename to autogpt_platform/frontend/src/hooks/__tests__/classifyCredentials.test.tsindex c015949a9b..9cc10a120d 100644--- a/autogpt_platform/frontend/src/hooks/useCredentials.test.ts+++ b/autogpt_platform/frontend/src/hooks/__tests__/classifyCredentials.test.ts@@ -1,16 +1,9 @@import { describe, expect, it } from "vitest";-import { renderHook } from "@testing-library/react";-import React from "react";-import { classifyCredentials } from "./useCredentials";-import useCredentials from "./useCredentials";+import { classifyCredentials } from "../useCredentials";import type {BlockIOCredentialsSubSchema,CredentialsMetaResponse,} from "@/lib/autogpt-server-api";-import {- CredentialsProvidersContext,- type CredentialsProvidersContextType,-} from "@/providers/agent-credentials/credentials-provider";function makeSchema(partial: Partial<BlockIOCredentialsSubSchema> = {},@@ -171,90 +164,3 @@ describe("classifyCredentials", () => {expect(upgradeableCredentials).toEqual([]);});});--function makeProviderMap(- saved: CredentialsMetaResponse[],-): CredentialsProvidersContextType {- return {- google: {- provider: "google",- providerName: "Google",- savedCredentials: saved,- isSystemProvider: false,- oAuthCallback: async () => makeCred({}),- mcpOAuthCallback: async () => makeCred({}),- createAPIKeyCredentials: async () => makeCred({}),- createUserPasswordCredentials: async () => makeCred({}),- createHostScopedCredentials: async () => makeCred({}),- deleteCredentials: async () => ({ deleted: true, revoked: true }),- },- };-}--describe("useCredentials (hook)", () => {- it("returns upgradeableCredentials for OAuth2 creds missing scopes", () => {- const schema = makeSchema({- credentials_provider: ["google"],- credentials_types: ["oauth2"],- credentials_scopes: ["drive.file", "drive.metadata"],- });-- const full = makeCred({- id: "full",- scopes: ["drive.file", "drive.metadata"],- });- const narrow = makeCred({ id: "narrow", scopes: ["drive.file"] });- const providers = makeProviderMap([full, narrow]);-- function Wrapper({ children }: { children: React.ReactNode }) {- return React.createElement(- CredentialsProvidersContext.Provider,- { value: providers },- children,- );- }-- const { result } = renderHook(() => useCredentials(schema), {- wrapper: Wrapper,- });-- expect(result.current).not.toBeNull();- const data = result.current!;- expect(data.isLoading).toBe(false);- if (data.isLoading) return;-- expect(data.savedCredentials.map((c) => c.id)).toEqual(["full"]);- expect(data.upgradeableCredentials.map((c) => c.id)).toEqual(["narrow"]);- });-- it("returns empty upgradeableCredentials when all scopes match", () => {- const schema = makeSchema({- credentials_provider: ["google"],- credentials_types: ["oauth2"],- credentials_scopes: ["drive.file"],- });-- const cred = makeCred({ id: "ok", scopes: ["drive.file", "drive.meta"] });- const providers = makeProviderMap([cred]);-- function Wrapper({ children }: { children: React.ReactNode }) {- return React.createElement(- CredentialsProvidersContext.Provider,- { value: providers },- children,- );- }-- const { result } = renderHook(() => useCredentials(schema), {- wrapper: Wrapper,- });-- expect(result.current).not.toBeNull();- const data = result.current!;- expect(data.isLoading).toBe(false);- if (data.isLoading) return;-- expect(data.savedCredentials.map((c) => c.id)).toEqual(["ok"]);- expect(data.upgradeableCredentials).toEqual([]);- });-});diff --git a/autogpt_platform/frontend/src/lib/utils.test.ts b/autogpt_platform/frontend/src/lib/__tests__/utils.test.tssimilarity index 98%rename from autogpt_platform/frontend/src/lib/utils.test.tsrename to autogpt_platform/frontend/src/lib/__tests__/utils.test.tsindex 62742ac574..e7497c18fb 100644--- a/autogpt_platform/frontend/src/lib/utils.test.ts+++ b/autogpt_platform/frontend/src/lib/__tests__/utils.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from "vitest";-import { setNestedProperty } from "./utils";+import { setNestedProperty } from "../utils";const testCases = [{diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.tssimilarity index 97%rename from autogpt_platform/frontend/src/lib/autogpt-server-api/client.test.tsrename to autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.tsindex 5baa78e4c0..524064f6e1 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.test.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/client.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import BackendAPI, { buildOAuthLoginQuery } from "./client";+import BackendAPI, { buildOAuthLoginQuery } from "../client";describe("BackendAPI.oAuthLogin", () => {it("passes credentialID through to buildOAuthLoginQuery", async () => {diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.tssimilarity index 98%rename from autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.test.tsrename to autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.tsindex 0d8ea6e3dd..562e493819 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.test.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/helpers.test.ts@@ -12,7 +12,7 @@ vi.mock("@/services/environment", () => ({},}));-import { buildUrlWithQuery, createRequestHeaders } from "./helpers";+import { buildUrlWithQuery, createRequestHeaders } from "../helpers";import {API_KEY_HEADER_NAME,IMPERSONATION_HEADER_NAME,diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.test.ts b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.tssimilarity index 99%rename from autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.test.tsrename to autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.tsindex ee31e4a976..7f986789ed 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.test.ts+++ b/autogpt_platform/frontend/src/providers/agent-credentials/__tests__/credentials-provider.test.ts@@ -6,7 +6,7 @@ import type {import {upsertProviderCredentials,type CredentialsProvidersContextType,-} from "./credentials-provider";+} from "../credentials-provider";function makeCred(partial: Partial<CredentialsMetaResponse>,diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsx b/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsxnew file mode 100644index 0000000000..529c7817a0--- /dev/null+++ b/autogpt_platform/frontend/src/services/push-notifications/__tests__/PushNotificationProvider.test.tsx@@ -0,0 +1,473 @@+import { render, waitFor } from "@/tests/integrations/test-utils";+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import { PushNotificationProvider } from "../PushNotificationProvider";++const { pathnameMock, searchParamsMock } = vi.hoisted(() => ({+ pathnameMock: vi.fn(() => "/copilot"),+ searchParamsMock: vi.fn(() => new URLSearchParams("sessionId=A")),+}));++vi.mock("next/navigation", () => ({+ usePathname: () => pathnameMock(),+ useSearchParams: () => searchParamsMock(),+ useRouter: () => ({+ push: vi.fn(),+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ useParams: () => ({}),+}));++const mockUser = { id: "user-1", email: "[email protected]" };+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: vi.fn(() => ({ user: mockUser })),+}));++const { notificationsEnabledMock } = vi.hoisted(() => ({+ notificationsEnabledMock: vi.fn(() => true),+}));+vi.mock("@/app/(platform)/copilot/store", () => ({+ useCopilotUIStore: (+ selector: (s: { isNotificationsEnabled: boolean }) => unknown,+ ) => selector({ isNotificationsEnabled: notificationsEnabledMock() }),+}));++const mockIsPushSupported = vi.fn(() => true);+const mockRegisterServiceWorker = vi.fn();+const mockSubscribeToPush = vi.fn();+const mockUnsubscribeFromPush = vi.fn();+vi.mock("../registration", () => ({+ isPushSupported: () => mockIsPushSupported(),+ registerServiceWorker: () => mockRegisterServiceWorker(),+ subscribeToPush: (...args: [unknown, unknown]) =>+ mockSubscribeToPush(...args),+ unsubscribeFromPush: (reg: unknown) => mockUnsubscribeFromPush(reg),+}));++const mockFetchVapidPublicKey = vi.fn();+const mockSendSubscriptionToServer = vi.fn();+const mockRemoveSubscriptionFromServer = vi.fn();+vi.mock("../api", () => ({+ fetchVapidPublicKey: () => mockFetchVapidPublicKey(),+ sendSubscriptionToServer: (sub: unknown) => mockSendSubscriptionToServer(sub),+ removeSubscriptionFromServer: (endpoint: string) =>+ mockRemoveSubscriptionFromServer(endpoint),+}));++const mockSubscription = { endpoint: "https://push.example.com/sub/1" };+const mockRegistration = {+ pushManager: {+ getSubscription: vi.fn(),+ },+};++const mockPostMessage = vi.fn();+const swListeners: Record<string, Array<(e?: unknown) => void>> = {};+const swMessageListeners: Array<(e: MessageEvent) => void> = [];++function installServiceWorker() {+ Object.defineProperty(navigator, "serviceWorker", {+ value: {+ controller: { postMessage: mockPostMessage },+ register: vi.fn(),+ getRegistration: vi.fn().mockResolvedValue(mockRegistration),+ ready: Promise.resolve(mockRegistration),+ addEventListener: (name: string, fn: (e?: unknown) => void) => {+ if (name === "message") {+ swMessageListeners.push(fn as (e: MessageEvent) => void);+ return;+ }+ if (!swListeners[name]) swListeners[name] = [];+ swListeners[name].push(fn);+ },+ removeEventListener: (name: string, fn: (e?: unknown) => void) => {+ if (name === "message") {+ const idx = swMessageListeners.indexOf(+ fn as (e: MessageEvent) => void,+ );+ if (idx !== -1) swMessageListeners.splice(idx, 1);+ return;+ }+ const list = swListeners[name];+ if (!list) return;+ const idx = list.indexOf(fn);+ if (idx !== -1) list.splice(idx, 1);+ },+ },+ configurable: true,+ writable: true,+ });+}++function uninstallServiceWorker() {+ // Fully remove the property so both `"serviceWorker" in navigator` and+ // truthy checks short-circuit, matching the "API unavailable" branch.+ delete (navigator as unknown as { serviceWorker?: unknown }).serviceWorker;+}++const originalNotificationDescriptor = Object.getOwnPropertyDescriptor(+ globalThis,+ "Notification",+);+const originalServiceWorkerDescriptor = Object.getOwnPropertyDescriptor(+ navigator,+ "serviceWorker",+);+const originalVapidPublicKey = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;++function restoreProperty(+ target: object,+ key: string,+ descriptor: PropertyDescriptor | undefined,+) {+ if (descriptor) {+ Object.defineProperty(target, key, descriptor);+ return;+ }+ delete (target as Record<string, unknown>)[key];+}++describe("PushNotificationProvider", () => {+ beforeEach(async () => {+ vi.clearAllMocks();+ Object.keys(swListeners).forEach((k) => delete swListeners[k]);+ swMessageListeners.length = 0;++ pathnameMock.mockReturnValue("/copilot");+ searchParamsMock.mockReturnValue(new URLSearchParams("sessionId=A"));+ notificationsEnabledMock.mockReturnValue(true);++ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ vi.mocked(useSupabase).mockReturnValue({+ user: mockUser,+ } as ReturnType<typeof useSupabase>);++ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "granted" },+ configurable: true,+ writable: true,+ });++ installServiceWorker();+ mockRegistration.pushManager.getSubscription = vi+ .fn()+ .mockResolvedValue(mockSubscription);+ mockIsPushSupported.mockReturnValue(true);+ mockRegisterServiceWorker.mockResolvedValue(mockRegistration);+ mockSubscribeToPush.mockResolvedValue(mockSubscription);+ mockFetchVapidPublicKey.mockResolvedValue("vapid-key-123");+ mockSendSubscriptionToServer.mockResolvedValue(true);+ mockRemoveSubscriptionFromServer.mockResolvedValue(true);+ mockUnsubscribeFromPush.mockResolvedValue(true);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ afterAll(() => {+ // Tests in this file mutate three module-scoped globals — `Notification`,+ // `navigator.serviceWorker`, and `process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY`.+ // beforeEach re-stubs them between tests inside this file, but without an+ // afterAll the mutations leak to any other test file scheduled into the+ // same Vitest worker.+ restoreProperty(globalThis, "Notification", originalNotificationDescriptor);+ restoreProperty(+ navigator,+ "serviceWorker",+ originalServiceWorkerDescriptor,+ );+ if (originalVapidPublicKey === undefined) {+ delete process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;+ } else {+ process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY = originalVapidPublicKey;+ }+ });++ describe("push subscription registration", () => {+ it("registers push subscription when all conditions are met", async () => {+ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockSendSubscriptionToServer).toHaveBeenCalledWith(+ mockSubscription,+ );+ });+ });++ // Skip-path tests use `mockPostMessage` as a deterministic "mount effects+ // flushed" anchor before asserting that the push-registration helpers were+ // NOT called. The URL reporter posts on mount regardless of push-support /+ // permission / auth / VAPID state, so it gives a reliable signal that the+ // provider's effects have run — without it, `expect(...).not.toHaveBeenCalled()`+ // can pass before the effect that would have called the mock fires.+ it("skips when push is not supported", async () => {+ mockIsPushSupported.mockReturnValue(false);++ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockPostMessage).toHaveBeenCalled();+ });+ expect(mockRegisterServiceWorker).not.toHaveBeenCalled();+ });++ it("skips when Notification permission is not granted", async () => {+ Object.defineProperty(globalThis, "Notification", {+ value: { permission: "default" },+ configurable: true,+ writable: true,+ });++ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockPostMessage).toHaveBeenCalled();+ });+ expect(mockRegisterServiceWorker).not.toHaveBeenCalled();+ });++ it("skips when no user is authenticated", async () => {+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ vi.mocked(useSupabase).mockReturnValue({+ user: null,+ } as ReturnType<typeof useSupabase>);++ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockPostMessage).toHaveBeenCalled();+ });+ expect(mockIsPushSupported).not.toHaveBeenCalled();+ });++ it("skips when service worker registration fails", async () => {+ mockRegisterServiceWorker.mockResolvedValue(null);++ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockRegisterServiceWorker).toHaveBeenCalled();+ });+ expect(mockSubscribeToPush).not.toHaveBeenCalled();+ });++ it("skips when VAPID key is not available", async () => {+ mockFetchVapidPublicKey.mockResolvedValue(null);+ delete process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;++ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockFetchVapidPublicKey).toHaveBeenCalled();+ });+ expect(mockSubscribeToPush).not.toHaveBeenCalled();+ });++ it("skips when push subscription fails", async () => {+ mockSubscribeToPush.mockResolvedValue(null);++ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockSubscribeToPush).toHaveBeenCalled();+ });+ expect(mockSendSubscriptionToServer).not.toHaveBeenCalled();+ });++ it("renews the subscription when PUSH_SUBSCRIPTION_CHANGED arrives", async () => {+ render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockSendSubscriptionToServer).toHaveBeenCalledWith(+ mockSubscription,+ );+ });+ expect(swMessageListeners.length).toBeGreaterThan(0);++ mockSubscribeToPush.mockClear();+ mockSendSubscriptionToServer.mockClear();++ swMessageListeners.forEach((fn) =>+ fn(+ new MessageEvent("message", {+ data: { type: "PUSH_SUBSCRIPTION_CHANGED" },+ }),+ ),+ );++ await waitFor(() => {+ expect(mockSubscribeToPush).toHaveBeenCalled();+ });+ expect(mockSendSubscriptionToServer).toHaveBeenCalledWith(+ mockSubscription,+ );+ });++ it("unsubscribes on logout after having been authenticated", async () => {+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ const { rerender } = render(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockSendSubscriptionToServer).toHaveBeenCalled();+ });++ vi.mocked(useSupabase).mockReturnValue({+ user: null,+ } as ReturnType<typeof useSupabase>);+ rerender(<PushNotificationProvider />);++ await waitFor(() => {+ expect(mockRemoveSubscriptionFromServer).toHaveBeenCalledWith(+ mockSubscription.endpoint,+ );+ });+ expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockRegistration);+ });++ it("does not call teardown when user is null from the start", async () => {+ const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");+ vi.mocked(useSupabase).mockReturnValue({+ user: null,+ } as ReturnType<typeof useSupabase>);++ render(<PushNotificationProvider />);++ // Wait for the provider's mount-time side effects (URL reporter + SW+ // listener registration) to flush before asserting absence of teardown.+ await waitFor(() => {+ expect(mockPostMessage).toHaveBeenCalled();+ });+ expect(mockRemoveSubscriptionFromServer).not.toHaveBeenCalled();+ expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();+ });+ });++ describe("client URL reporting", () => {+ it("posts the current URL on mount", () => {+ render(<PushNotificationProvider />);++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot?sessionId=A",+ });+ });++ it("includes the pathname only when there are no query params", () => {+ searchParamsMock.mockReturnValue(new URLSearchParams());++ render(<PushNotificationProvider />);++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot",+ });+ });++ it("re-posts when pathname changes", () => {+ const { rerender } = render(<PushNotificationProvider />);+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot?sessionId=A",+ });++ pathnameMock.mockReturnValue("/library");+ searchParamsMock.mockReturnValue(new URLSearchParams());+ rerender(<PushNotificationProvider />);++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/library",+ });+ });++ it("re-posts the URL when the SW controller changes", async () => {+ render(<PushNotificationProvider />);+ mockPostMessage.mockClear();++ swListeners.controllerchange?.forEach((fn) => fn());++ await waitFor(() => {+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "CLIENT_URL",+ url: "/copilot?sessionId=A",+ });+ });+ });+ });++ describe("notifications-enabled reporting", () => {+ it("posts the toggle value on mount when enabled", () => {+ notificationsEnabledMock.mockReturnValue(true);++ render(<PushNotificationProvider />);++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: true,+ });+ });++ it("posts the toggle value on mount when disabled", () => {+ notificationsEnabledMock.mockReturnValue(false);++ render(<PushNotificationProvider />);++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: false,+ });+ });++ it("re-posts when the toggle flips", () => {+ notificationsEnabledMock.mockReturnValue(true);+ const { rerender } = render(<PushNotificationProvider />);+ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: true,+ });++ notificationsEnabledMock.mockReturnValue(false);+ rerender(<PushNotificationProvider />);++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: false,+ });+ });++ it("re-posts the toggle on SW controllerchange", () => {+ notificationsEnabledMock.mockReturnValue(false);+ render(<PushNotificationProvider />);+ mockPostMessage.mockClear();++ swListeners.controllerchange?.forEach((fn) => fn());++ expect(mockPostMessage).toHaveBeenCalledWith({+ type: "NOTIFICATIONS_ENABLED",+ value: false,+ });+ });+ });++ describe("when serviceWorker API is unavailable", () => {+ it("does not post any URL or toggle messages", () => {+ uninstallServiceWorker();++ render(<PushNotificationProvider />);++ expect(mockPostMessage).not.toHaveBeenCalled();+ });+ });+});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/usePushNotifications.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/usePushNotifications.test.tsdeleted file mode 100644index ebf68e028a..0000000000--- a/autogpt_platform/frontend/src/services/push-notifications/__tests__/usePushNotifications.test.ts+++ /dev/null@@ -1,200 +0,0 @@-import { renderHook, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { usePushNotifications } from "../usePushNotifications";--const mockUser = { id: "user-1", email: "[email protected]" };--vi.mock("@/lib/supabase/hooks/useSupabase", () => ({- useSupabase: vi.fn(() => ({ user: mockUser })),-}));--const mockIsPushSupported = vi.fn(() => true);-const mockRegisterServiceWorker = vi.fn();-const mockSubscribeToPush = vi.fn();-const mockUnsubscribeFromPush = vi.fn();--vi.mock("../registration", () => ({- isPushSupported: () => mockIsPushSupported(),- registerServiceWorker: () => mockRegisterServiceWorker(),- subscribeToPush: (...args: [unknown, unknown]) =>- mockSubscribeToPush(...args),- unsubscribeFromPush: (reg: unknown) => mockUnsubscribeFromPush(reg),-}));--const mockFetchVapidPublicKey = vi.fn();-const mockSendSubscriptionToServer = vi.fn();-const mockRemoveSubscriptionFromServer = vi.fn();--vi.mock("../api", () => ({- fetchVapidPublicKey: () => mockFetchVapidPublicKey(),- sendSubscriptionToServer: (sub: unknown) => mockSendSubscriptionToServer(sub),- removeSubscriptionFromServer: (endpoint: string) =>- mockRemoveSubscriptionFromServer(endpoint),-}));--describe("usePushNotifications", () => {- const mockRegistration = {- pushManager: {- getSubscription: vi.fn(),- },- };- const mockSubscription = { endpoint: "https://push.example.com/sub/1" };-- beforeEach(async () => {- vi.clearAllMocks();- const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");- vi.mocked(useSupabase).mockReturnValue({- user: mockUser,- } as ReturnType<typeof useSupabase>);- Object.defineProperty(globalThis, "Notification", {- value: { permission: "granted" },- configurable: true,- writable: true,- });- Object.defineProperty(navigator, "serviceWorker", {- value: {- register: vi.fn(),- getRegistration: vi.fn().mockResolvedValue(mockRegistration),- ready: Promise.resolve(mockRegistration),- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- },- configurable: true,- });- mockRegistration.pushManager.getSubscription = vi- .fn()- .mockResolvedValue(mockSubscription);- mockIsPushSupported.mockReturnValue(true);- mockRegisterServiceWorker.mockResolvedValue(mockRegistration);- mockSubscribeToPush.mockResolvedValue(mockSubscription);- mockFetchVapidPublicKey.mockResolvedValue("vapid-key-123");- mockSendSubscriptionToServer.mockResolvedValue(true);- mockRemoveSubscriptionFromServer.mockResolvedValue(true);- mockUnsubscribeFromPush.mockResolvedValue(true);- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it("registers push subscription when all conditions are met", async () => {- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockSendSubscriptionToServer).toHaveBeenCalledWith(- mockSubscription,- );- });- });-- it("skips when push is not supported", async () => {- mockIsPushSupported.mockReturnValue(false);-- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockRegisterServiceWorker).not.toHaveBeenCalled();- });- });-- it("skips when Notification permission is not granted", async () => {- Object.defineProperty(globalThis, "Notification", {- value: { permission: "default" },- configurable: true,- writable: true,- });-- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockRegisterServiceWorker).not.toHaveBeenCalled();- });- });-- it("skips when no user is authenticated", async () => {- const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");- vi.mocked(useSupabase).mockReturnValue({- user: null,- } as ReturnType<typeof useSupabase>);-- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockIsPushSupported).not.toHaveBeenCalled();- });- });-- it("skips when service worker registration fails", async () => {- mockRegisterServiceWorker.mockResolvedValue(null);-- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockSubscribeToPush).not.toHaveBeenCalled();- });- });-- it("skips when VAPID key is not available", async () => {- mockFetchVapidPublicKey.mockResolvedValue(null);- delete process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;-- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockSubscribeToPush).not.toHaveBeenCalled();- });- });-- it("skips when push subscription fails", async () => {- mockSubscribeToPush.mockResolvedValue(null);-- renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockSendSubscriptionToServer).not.toHaveBeenCalled();- });- });-- it("listens for PUSH_SUBSCRIPTION_CHANGED messages", () => {- renderHook(() => usePushNotifications());-- expect(navigator.serviceWorker.addEventListener).toHaveBeenCalledWith(- "message",- expect.any(Function),- );- });-- it("unsubscribes on logout after having been authenticated", async () => {- const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");- const { rerender } = renderHook(() => usePushNotifications());-- await waitFor(() => {- expect(mockSendSubscriptionToServer).toHaveBeenCalled();- });-- vi.mocked(useSupabase).mockReturnValue({- user: null,- } as ReturnType<typeof useSupabase>);- rerender();-- await waitFor(() => {- expect(mockRemoveSubscriptionFromServer).toHaveBeenCalledWith(- mockSubscription.endpoint,- );- });- expect(mockUnsubscribeFromPush).toHaveBeenCalledWith(mockRegistration);- });-- it("does not call teardown when user is null from the start", async () => {- const { useSupabase } = await import("@/lib/supabase/hooks/useSupabase");- vi.mocked(useSupabase).mockReturnValue({- user: null,- } as ReturnType<typeof useSupabase>);-- renderHook(() => usePushNotifications());-- await new Promise((resolve) => setTimeout(resolve, 10));- expect(mockRemoveSubscriptionFromServer).not.toHaveBeenCalled();- expect(mockUnsubscribeFromPush).not.toHaveBeenCalled();- });-});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportClientUrl.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportClientUrl.test.tsdeleted file mode 100644index 4308fe4f8c..0000000000--- a/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportClientUrl.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import { renderHook, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useReportClientUrl } from "../useReportClientUrl";--const mockPathname = vi.fn(() => "/copilot");-const mockSearchParams = vi.fn(() => new URLSearchParams("sessionId=A"));--vi.mock("next/navigation", () => ({- usePathname: () => mockPathname(),- useSearchParams: () => mockSearchParams(),-}));--const mockPostMessage = vi.fn();-const swListeners: Record<string, ((e?: unknown) => void) | undefined> = {};--beforeEach(() => {- vi.clearAllMocks();- mockPathname.mockReturnValue("/copilot");- mockSearchParams.mockReturnValue(new URLSearchParams("sessionId=A"));- Object.defineProperty(navigator, "serviceWorker", {- value: {- controller: { postMessage: mockPostMessage },- addEventListener: (name: string, fn: () => void) => {- swListeners[name] = fn;- },- removeEventListener: (name: string) => {- swListeners[name] = undefined;- },- },- configurable: true,- });-});--afterEach(() => {- vi.restoreAllMocks();-});--describe("useReportClientUrl", () => {- it("posts the current URL on mount", () => {- renderHook(() => useReportClientUrl());- expect(mockPostMessage).toHaveBeenCalledWith({- type: "CLIENT_URL",- url: "/copilot?sessionId=A",- });- });-- it("includes the pathname only when there are no query params", () => {- mockSearchParams.mockReturnValue(new URLSearchParams());- renderHook(() => useReportClientUrl());- expect(mockPostMessage).toHaveBeenCalledWith({- type: "CLIENT_URL",- url: "/copilot",- });- });-- it("re-posts when pathname changes", () => {- const { rerender } = renderHook(() => useReportClientUrl());- expect(mockPostMessage).toHaveBeenLastCalledWith({- type: "CLIENT_URL",- url: "/copilot?sessionId=A",- });-- mockPathname.mockReturnValue("/library");- mockSearchParams.mockReturnValue(new URLSearchParams());- rerender();-- expect(mockPostMessage).toHaveBeenLastCalledWith({- type: "CLIENT_URL",- url: "/library",- });- });-- it("re-posts when the SW controller changes", async () => {- renderHook(() => useReportClientUrl());- mockPostMessage.mockClear();-- swListeners.controllerchange?.();-- await waitFor(() => {- expect(mockPostMessage).toHaveBeenCalledWith({- type: "CLIENT_URL",- url: "/copilot?sessionId=A",- });- });- });-- it("does nothing when serviceWorker API is unavailable", () => {- Object.defineProperty(navigator, "serviceWorker", {- value: undefined,- configurable: true,- });- renderHook(() => useReportClientUrl());- expect(mockPostMessage).not.toHaveBeenCalled();- });-});diff --git a/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportNotificationsEnabled.test.ts b/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportNotificationsEnabled.test.tsdeleted file mode 100644index 1c2f62b6c5..0000000000--- a/autogpt_platform/frontend/src/services/push-notifications/__tests__/useReportNotificationsEnabled.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { renderHook } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useReportNotificationsEnabled } from "../useReportNotificationsEnabled";--const mockGetState = vi.fn(() => true);-vi.mock("@/app/(platform)/copilot/store", () => ({- useCopilotUIStore: (- selector: (s: { isNotificationsEnabled: boolean }) => unknown,- ) => selector({ isNotificationsEnabled: mockGetState() }),-}));--const mockPostMessage = vi.fn();-const swListeners: Record<string, ((e?: unknown) => void) | undefined> = {};--beforeEach(() => {- vi.clearAllMocks();- Object.defineProperty(navigator, "serviceWorker", {- value: {- controller: { postMessage: mockPostMessage },- addEventListener: (name: string, fn: () => void) => {- swListeners[name] = fn;- },- removeEventListener: (name: string) => {- swListeners[name] = undefined;- },- },- configurable: true,- });-});--afterEach(() => {- vi.restoreAllMocks();-});--describe("useReportNotificationsEnabled", () => {- it("posts the toggle value on mount when enabled", () => {- mockGetState.mockReturnValue(true);- renderHook(() => useReportNotificationsEnabled());- expect(mockPostMessage).toHaveBeenCalledWith({- type: "NOTIFICATIONS_ENABLED",- value: true,- });- });-- it("posts the toggle value on mount when disabled", () => {- mockGetState.mockReturnValue(false);- renderHook(() => useReportNotificationsEnabled());- expect(mockPostMessage).toHaveBeenCalledWith({- type: "NOTIFICATIONS_ENABLED",- value: false,- });- });-- it("re-posts when the toggle flips", () => {- mockGetState.mockReturnValue(true);- const { rerender } = renderHook(() => useReportNotificationsEnabled());- expect(mockPostMessage).toHaveBeenLastCalledWith({- type: "NOTIFICATIONS_ENABLED",- value: true,- });-- mockGetState.mockReturnValue(false);- rerender();-- expect(mockPostMessage).toHaveBeenLastCalledWith({- type: "NOTIFICATIONS_ENABLED",- value: false,- });- });-- it("re-posts on SW controllerchange", () => {- mockGetState.mockReturnValue(false);- renderHook(() => useReportNotificationsEnabled());- mockPostMessage.mockClear();-- swListeners.controllerchange?.();-- expect(mockPostMessage).toHaveBeenCalledWith({- type: "NOTIFICATIONS_ENABLED",- value: false,- });- });-- it("does nothing when serviceWorker API is unavailable", () => {- Object.defineProperty(navigator, "serviceWorker", {- value: undefined,- configurable: true,- });- renderHook(() => useReportNotificationsEnabled());- expect(mockPostMessage).not.toHaveBeenCalled();- });-});diff --git a/autogpt_platform/frontend/src/types/auth.test.ts b/autogpt_platform/frontend/src/types/__tests__/auth.test.tssimilarity index 96%rename from autogpt_platform/frontend/src/types/auth.test.tsrename to autogpt_platform/frontend/src/types/__tests__/auth.test.tsindex ef5c0b38e1..db5cb661fa 100644--- a/autogpt_platform/frontend/src/types/auth.test.ts+++ b/autogpt_platform/frontend/src/types/__tests__/auth.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from "vitest";-import { signupFormSchema } from "./auth";+import { signupFormSchema } from "../auth";describe("signupFormSchema", () => {test("rejects invalid signup input", () => {