Skip to content

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

fix(copilot/frontend): align ModelToggleButton styling + add execution ID filter to platform cost page (#12793)

Zamil Majdy56864aea8777
diff --git a/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes.py b/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes.py
index 70e7772790..048c4ae07e 100644
--- a/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes.py
+++ b/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes.py
@@ -43,6 +43,7 @@ async def get_cost_dashboard(
model: str | None = Query(None),
block_name: str | None = Query(None),
tracking_type: str | None = Query(None),
+ graph_exec_id: str | None = Query(None),
):
logger.info("Admin %s fetching platform cost dashboard", admin_user_id)
return await get_platform_cost_dashboard(
@@ -53,6 +54,7 @@ async def get_cost_dashboard(
model=model,
block_name=block_name,
tracking_type=tracking_type,
+ graph_exec_id=graph_exec_id,
)
@@ -72,6 +74,7 @@ async def get_cost_logs(
model: str | None = Query(None),
block_name: str | None = Query(None),
tracking_type: str | None = Query(None),
+ graph_exec_id: str | None = Query(None),
):
logger.info("Admin %s fetching platform cost logs", admin_user_id)
logs, total = await get_platform_cost_logs(
@@ -84,6 +87,7 @@ async def get_cost_logs(
model=model,
block_name=block_name,
tracking_type=tracking_type,
+ graph_exec_id=graph_exec_id,
)
total_pages = (total + page_size - 1) // page_size
return PlatformCostLogsResponse(
@@ -117,6 +121,7 @@ async def export_cost_logs(
model: str | None = Query(None),
block_name: str | None = Query(None),
tracking_type: str | None = Query(None),
+ graph_exec_id: str | None = Query(None),
):
logger.info("Admin %s exporting platform cost logs", admin_user_id)
logs, truncated = await get_platform_cost_logs_for_export(
@@ -127,6 +132,7 @@ async def export_cost_logs(
model=model,
block_name=block_name,
tracking_type=tracking_type,
+ graph_exec_id=graph_exec_id,
)
return PlatformCostExportResponse(
logs=logs,
diff --git a/autogpt_platform/backend/backend/data/platform_cost.py b/autogpt_platform/backend/backend/data/platform_cost.py
index aa539bc66b..ac5329c799 100644
--- a/autogpt_platform/backend/backend/data/platform_cost.py
+++ b/autogpt_platform/backend/backend/data/platform_cost.py
@@ -215,6 +215,7 @@ def _build_prisma_where(
model: str | None = None,
block_name: str | None = None,
tracking_type: str | None = None,
+ graph_exec_id: str | None = None,
) -> PlatformCostLogWhereInput:
"""Build a Prisma WhereInput for PlatformCostLog filters."""
where: PlatformCostLogWhereInput = {}
@@ -242,6 +243,9 @@ def _build_prisma_where(
if tracking_type:
where["trackingType"] = tracking_type
+ if graph_exec_id:
+ where["graphExecId"] = graph_exec_id
+
return where
@@ -253,6 +257,7 @@ def _build_raw_where(
model: str | None = None,
block_name: str | None = None,
tracking_type: str | None = None,
+ graph_exec_id: str | None = None,
) -> tuple[str, list]:
"""Build a parameterised WHERE clause for raw SQL queries.
@@ -302,6 +307,11 @@ def _build_raw_where(
params.append(block_name)
idx += 1
+ if graph_exec_id is not None:
+ clauses.append(f'"graphExecId" = ${idx}')
+ params.append(graph_exec_id)
+ idx += 1
+
return (" AND ".join(clauses), params)
@@ -314,6 +324,7 @@ async def get_platform_cost_dashboard(
model: str | None = None,
block_name: str | None = None,
tracking_type: str | None = None,
+ graph_exec_id: str | None = None,
) -> PlatformCostDashboard:
"""Aggregate platform cost logs for the admin dashboard.
@@ -330,7 +341,7 @@ async def get_platform_cost_dashboard(
start = datetime.now(timezone.utc) - timedelta(days=DEFAULT_DASHBOARD_DAYS)
where = _build_prisma_where(
- start, end, provider, user_id, model, block_name, tracking_type
+ start, end, provider, user_id, model, block_name, tracking_type, graph_exec_id
)
# For per-user tracking-type breakdown we intentionally omit the
@@ -338,7 +349,14 @@ async def get_platform_cost_dashboard(
# This ensures cost_bearing_request_count is correct even when the caller
# is filtering the main view by a different tracking_type.
where_no_tracking_type = _build_prisma_where(
- start, end, provider, user_id, model, block_name, tracking_type=None
+ start,
+ end,
+ provider,
+ user_id,
+ model,
+ block_name,
+ tracking_type=None,
+ graph_exec_id=graph_exec_id,
)
sum_fields = {
@@ -358,7 +376,14 @@ async def get_platform_cost_dashboard(
# "cost_usd" — percentile and histogram queries only make sense on
# cost-denominated rows, regardless of what the caller is filtering.
raw_where, raw_params = _build_raw_where(
- start, end, provider, user_id, model, block_name, tracking_type=None
+ start,
+ end,
+ provider,
+ user_id,
+ model,
+ block_name,
+ tracking_type=None,
+ graph_exec_id=graph_exec_id,
)
# Queries that always run regardless of tracking_type filter.
@@ -647,12 +672,13 @@ async def get_platform_cost_logs(
model: str | None = None,
block_name: str | None = None,
tracking_type: str | None = None,
+ graph_exec_id: str | None = None,
) -> tuple[list[CostLogRow], int]:
if start is None:
start = datetime.now(tz=timezone.utc) - timedelta(days=DEFAULT_DASHBOARD_DAYS)
where = _build_prisma_where(
- start, end, provider, user_id, model, block_name, tracking_type
+ start, end, provider, user_id, model, block_name, tracking_type, graph_exec_id
)
offset = (page - 1) * page_size
@@ -702,6 +728,7 @@ async def get_platform_cost_logs_for_export(
model: str | None = None,
block_name: str | None = None,
tracking_type: str | None = None,
+ graph_exec_id: str | None = None,
) -> tuple[list[CostLogRow], bool]:
"""Return all matching rows up to EXPORT_MAX_ROWS.
@@ -712,7 +739,7 @@ async def get_platform_cost_logs_for_export(
start = datetime.now(tz=timezone.utc) - timedelta(days=DEFAULT_DASHBOARD_DAYS)
where = _build_prisma_where(
- start, end, provider, user_id, model, block_name, tracking_type
+ start, end, provider, user_id, model, block_name, tracking_type, graph_exec_id
)
rows = await PrismaLog.prisma().find_many(
diff --git a/autogpt_platform/backend/backend/data/platform_cost_test.py b/autogpt_platform/backend/backend/data/platform_cost_test.py
index ad15fb425b..5bfe68e1cc 100644
--- a/autogpt_platform/backend/backend/data/platform_cost_test.py
+++ b/autogpt_platform/backend/backend/data/platform_cost_test.py
@@ -195,6 +195,14 @@ class TestBuildPrismaWhere:
where = _build_prisma_where(None, None, None, None, tracking_type="tokens")
assert where["trackingType"] == "tokens"
+ def test_graph_exec_id_filter(self):
+ where = _build_prisma_where(None, None, None, None, graph_exec_id="exec-123")
+ assert where["graphExecId"] == "exec-123"
+
+ def test_graph_exec_id_none_not_included(self):
+ where = _build_prisma_where(None, None, None, None, graph_exec_id=None)
+ assert "graphExecId" not in where
+
class TestBuildRawWhere:
def test_end_filter(self):
@@ -235,6 +243,15 @@ class TestBuildRawWhere:
sql, params = _build_raw_where(None, None, None, None, tracking_type="tokens")
assert params[0] == "tokens"
+ def test_graph_exec_id_filter(self):
+ sql, params = _build_raw_where(None, None, None, None, graph_exec_id="exec-abc")
+ assert '"graphExecId" = $' in sql
+ assert "exec-abc" in params
+
+ def test_graph_exec_id_not_included_when_none(self):
+ sql, params = _build_raw_where(None, None, None, None)
+ assert "graphExecId" not in sql
+
def _make_entry(**overrides: object) -> PlatformCostEntry:
return PlatformCostEntry.model_validate(
@@ -688,6 +705,37 @@ class TestGetPlatformCostDashboard:
provider_call_where = mock_actions.group_by.call_args_list[0][1]["where"]
assert "trackingType" in provider_call_where
+ @pytest.mark.asyncio
+ async def test_graph_exec_id_filter_passed_to_queries(self):
+ """graph_exec_id must be forwarded to both prisma and raw SQL queries."""
+ mock_actions = MagicMock()
+ mock_actions.group_by = AsyncMock(side_effect=[[], [], [], [], []])
+ mock_actions.find_many = AsyncMock(return_value=[])
+ raw_mock = AsyncMock(side_effect=[[], []])
+
+ with (
+ patch(
+ "backend.data.platform_cost.PrismaLog.prisma",
+ return_value=mock_actions,
+ ),
+ patch(
+ "backend.data.platform_cost.PrismaUser.prisma",
+ return_value=mock_actions,
+ ),
+ patch(
+ "backend.data.platform_cost.query_raw_with_schema",
+ raw_mock,
+ ),
+ ):
+ await get_platform_cost_dashboard(graph_exec_id="exec-xyz")
+
+ # Prisma groupBy where must include graphExecId
+ first_call_where = mock_actions.group_by.call_args_list[0][1]["where"]
+ assert first_call_where.get("graphExecId") == "exec-xyz"
+ # Raw SQL params must include the exec id
+ raw_params = raw_mock.call_args_list[0][0][1:]
+ assert "exec-xyz" in raw_params
+
def _make_prisma_log_row(
i: int = 0,
@@ -787,6 +835,21 @@ class TestGetPlatformCostLogs:
# start provided — should appear in the where filter
assert "createdAt" in where
+ @pytest.mark.asyncio
+ async def test_graph_exec_id_filter(self):
+ mock_actions = MagicMock()
+ mock_actions.count = AsyncMock(return_value=0)
+ mock_actions.find_many = AsyncMock(return_value=[])
+
+ with patch(
+ "backend.data.platform_cost.PrismaLog.prisma",
+ return_value=mock_actions,
+ ):
+ logs, total = await get_platform_cost_logs(graph_exec_id="exec-abc")
+
+ where = mock_actions.count.call_args[1]["where"]
+ assert where.get("graphExecId") == "exec-abc"
+
class TestGetPlatformCostLogsForExport:
@pytest.mark.asyncio
@@ -872,6 +935,24 @@ class TestGetPlatformCostLogsForExport:
assert logs[0].cache_read_tokens == 50
assert logs[0].cache_creation_tokens == 25
+ @pytest.mark.asyncio
+ async def test_graph_exec_id_filter(self):
+ mock_actions = MagicMock()
+ mock_actions.find_many = AsyncMock(return_value=[])
+
+ with patch(
+ "backend.data.platform_cost.PrismaLog.prisma",
+ return_value=mock_actions,
+ ):
+ logs, truncated = await get_platform_cost_logs_for_export(
+ graph_exec_id="exec-xyz"
+ )
+
+ where = mock_actions.find_many.call_args[1]["where"]
+ assert where.get("graphExecId") == "exec-xyz"
+ assert logs == []
+ assert truncated is False
+
@pytest.mark.asyncio
async def test_explicit_start_skips_default(self):
start = datetime(2026, 1, 1, tzinfo=timezone.utc)
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/__tests__/PlatformCostContent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/__tests__/PlatformCostContent.test.tsx
index bde8507b37..8808f1280d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/__tests__/PlatformCostContent.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/__tests__/PlatformCostContent.test.tsx
@@ -3,6 +3,7 @@ import {
screen,
cleanup,
waitFor,
+ fireEvent,
} from "@/tests/integrations/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { PlatformCostContent } from "../components/PlatformCostContent";
@@ -351,6 +352,95 @@ describe("PlatformCostContent", () => {
expect(screen.getByText("Apply")).toBeDefined();
});
+ it("renders execution ID filter input", async () => {
+ mockUseGetDashboard.mockReturnValue({
+ data: emptyDashboard,
+ isLoading: false,
+ });
+ mockUseGetLogs.mockReturnValue({ data: emptyLogs, isLoading: false });
+ renderComponent();
+ await waitFor(() =>
+ expect(document.querySelector(".animate-pulse")).toBeNull(),
+ );
+ expect(screen.getByText("Execution ID")).toBeDefined();
+ expect(screen.getByPlaceholderText("Filter by execution")).toBeDefined();
+ });
+
+ it("pre-fills execution ID filter from searchParams", async () => {
+ mockUseGetDashboard.mockReturnValue({
+ data: emptyDashboard,
+ isLoading: false,
+ });
+ mockUseGetLogs.mockReturnValue({ data: emptyLogs, isLoading: false });
+ renderComponent({ graph_exec_id: "exec-123" });
+ await waitFor(() =>
+ expect(document.querySelector(".animate-pulse")).toBeNull(),
+ );
+ const input = screen.getByPlaceholderText(
+ "Filter by execution",
+ ) as HTMLInputElement;
+ expect(input.value).toBe("exec-123");
+ });
+
+ it("clears execution ID input on Clear click", async () => {
+ mockUseGetDashboard.mockReturnValue({
+ data: emptyDashboard,
+ isLoading: false,
+ });
+ mockUseGetLogs.mockReturnValue({ data: emptyLogs, isLoading: false });
+ renderComponent({ graph_exec_id: "exec-123" });
+ await waitFor(() =>
+ expect(document.querySelector(".animate-pulse")).toBeNull(),
+ );
+ fireEvent.click(screen.getByText("Clear"));
+ const input = screen.getByPlaceholderText(
+ "Filter by execution",
+ ) as HTMLInputElement;
+ expect(input.value).toBe("");
+ });
+
+ it("passes execution ID to filter on Apply click", async () => {
+ mockUseGetDashboard.mockReturnValue({
+ data: emptyDashboard,
+ isLoading: false,
+ });
+ mockUseGetLogs.mockReturnValue({ data: emptyLogs, isLoading: false });
+ renderComponent();
+ await waitFor(() =>
+ expect(document.querySelector(".animate-pulse")).toBeNull(),
+ );
+ const input = screen.getByPlaceholderText(
+ "Filter by execution",
+ ) as HTMLInputElement;
+ fireEvent.change(input, { target: { value: "exec-abc" } });
+ expect(input.value).toBe("exec-abc");
+ fireEvent.click(screen.getByText("Apply"));
+ // After apply, the input still holds the typed value
+ expect(input.value).toBe("exec-abc");
+ });
+
+ it("copies execution ID to clipboard on cell click in logs tab", async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });
+ mockUseGetDashboard.mockReturnValue({
+ data: dashboardWithData,
+ isLoading: false,
+ });
+ mockUseGetLogs.mockReturnValue({
+ data: logsWithData,
+ isLoading: false,
+ });
+ renderComponent({ tab: "logs" });
+ await waitFor(() =>
+ expect(document.querySelector(".animate-pulse")).toBeNull(),
+ );
+ // The exec ID cell shows first 8 chars of "gx-123"
+ const execIdCell = screen.getByText("gx-123".slice(0, 8));
+ fireEvent.click(execIdCell);
+ expect(writeText).toHaveBeenCalledWith("gx-123");
+ vi.unstubAllGlobals();
+ });
+
it("renders by-user tab when specified", async () => {
mockUseGetDashboard.mockReturnValue({
data: dashboardWithData,
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/LogsTable.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/LogsTable.tsx
index 056eef06b8..3d8af1d61d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/LogsTable.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/LogsTable.tsx
@@ -118,7 +118,24 @@ function LogsTable({
? formatDuration(Number(log.duration))
: "-"}
</td>
- <td className="px-3 py-2 text-xs text-muted-foreground">
+ <td
+ className={[
+ "px-3 py-2 text-xs text-muted-foreground",
+ log.graph_exec_id ? "cursor-pointer" : "",
+ ].join(" ")}
+ title={
+ log.graph_exec_id ? String(log.graph_exec_id) : undefined
+ }
+ onClick={
+ log.graph_exec_id
+ ? () => {
+ navigator.clipboard
+ .writeText(String(log.graph_exec_id))
+ .catch(() => {});
+ }
+ : undefined
+ }
+ >
{log.graph_exec_id
? String(log.graph_exec_id).slice(0, 8)
: "-"}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/PlatformCostContent.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/PlatformCostContent.tsx
index ce0329af19..28d11f6c3c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/PlatformCostContent.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/PlatformCostContent.tsx
@@ -19,6 +19,7 @@ interface Props {
model?: string;
block_name?: string;
tracking_type?: string;
+ graph_exec_id?: string;
page?: string;
tab?: string;
};
@@ -47,6 +48,8 @@ export function PlatformCostContent({ searchParams }: Props) {
setBlockInput,
typeInput,
setTypeInput,
+ executionIDInput,
+ setExecutionIDInput,
rateOverrides,
handleRateOverride,
updateUrl,
@@ -235,6 +238,22 @@ export function PlatformCostContent({ searchParams }: Props) {
onChange={(e) => setTypeInput(e.target.value)}
/>
</div>
+ <div className="flex flex-col gap-1">
+ <label
+ htmlFor="execution-id-filter"
+ className="text-sm text-muted-foreground"
+ >
+ Execution ID
+ </label>
+ <input
+ id="execution-id-filter"
+ type="text"
+ placeholder="Filter by execution"
+ className="rounded border px-3 py-1.5 text-sm"
+ value={executionIDInput}
+ onChange={(e) => setExecutionIDInput(e.target.value)}
+ />
+ </div>
<button
onClick={handleFilter}
className="rounded bg-primary px-4 py-1.5 text-sm text-primary-foreground hover:bg-primary/90"
@@ -250,6 +269,7 @@ export function PlatformCostContent({ searchParams }: Props) {
setModelInput("");
setBlockInput("");
setTypeInput("");
+ setExecutionIDInput("");
updateUrl({
start: "",
end: "",
@@ -258,6 +278,7 @@ export function PlatformCostContent({ searchParams }: Props) {
model: "",
block_name: "",
tracking_type: "",
+ graph_exec_id: "",
page: "1",
});
}}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/usePlatformCostContent.ts b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/usePlatformCostContent.ts
index 7b3f92036d..833f5c80a8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/usePlatformCostContent.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/components/usePlatformCostContent.ts
@@ -23,6 +23,7 @@ interface InitialSearchParams {
model?: string;
block_name?: string;
tracking_type?: string;
+ graph_exec_id?: string;
page?: string;
tab?: string;
}
@@ -43,6 +44,8 @@ export function usePlatformCostContent(searchParams: InitialSearchParams) {
urlParams.get("block_name") || searchParams.block_name || "";
const typeFilter =
urlParams.get("tracking_type") || searchParams.tracking_type || "";
+ const executionIDFilter =
+ urlParams.get("graph_exec_id") || searchParams.graph_exec_id || "";
const [startInput, setStartInput] = useState(toLocalInput(startDate));
const [endInput, setEndInput] = useState(toLocalInput(endDate));
@@ -51,6 +54,7 @@ export function usePlatformCostContent(searchParams: InitialSearchParams) {
const [modelInput, setModelInput] = useState(modelFilter);
const [blockInput, setBlockInput] = useState(blockFilter);
const [typeInput, setTypeInput] = useState(typeFilter);
+ const [executionIDInput, setExecutionIDInput] = useState(executionIDFilter);
const [rateOverrides, setRateOverrides] = useState<Record<string, number>>(
{},
);
@@ -67,6 +71,7 @@ export function usePlatformCostContent(searchParams: InitialSearchParams) {
model: modelFilter || undefined,
block_name: blockFilter || undefined,
tracking_type: typeFilter || undefined,
+ graph_exec_id: executionIDFilter || undefined,
};
const {
@@ -115,6 +120,7 @@ export function usePlatformCostContent(searchParams: InitialSearchParams) {
model: modelInput,
block_name: blockInput,
tracking_type: typeInput,
+ graph_exec_id: executionIDInput,
page: "1",
});
}
@@ -185,6 +191,8 @@ export function usePlatformCostContent(searchParams: InitialSearchParams) {
setBlockInput,
typeInput,
setTypeInput,
+ executionIDInput,
+ setExecutionIDInput,
rateOverrides,
handleRateOverride,
updateUrl,
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/page.tsx
index 2481982522..a4bdda1e6a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/platform-costs/page.tsx
@@ -7,6 +7,10 @@ type SearchParams = {
end?: string;
provider?: string;
user_id?: string;
+ model?: string;
+ block_name?: string;
+ tracking_type?: string;
+ graph_exec_id?: string;
page?: string;
tab?: string;
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
index 03838a26ba..88f70c75d8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
@@ -113,8 +113,8 @@ export function CopilotPage() {
// Rate limit reset
rateLimitMessage,
dismissRateLimit,
- // Dry run dev toggle
- isDryRun,
+ // Dry run session state
+ sessionDryRun,
} = useCopilotPage();
const {
@@ -176,10 +176,15 @@ export function CopilotPage() {
>
{isMobile && <MobileHeader onOpenDrawer={handleOpenDrawer} />}
<NotificationBanner />
- {isDryRun && (
+ {/* Test mode banner: only shown when the CURRENT session is confirmed to be
+ a dry_run session via its immutable metadata. Never shown based on the
+ global isDryRun store preference alone — that only predicts future sessions
+ and would mislead users browsing non-dry-run sessions while the toggle is on.
+ The DryRunToggleButton (visible on new chats) already communicates the preference. */}
+ {sessionId && sessionDryRun && (
<div className="flex items-center justify-center gap-1.5 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-800">
<Flask size={13} weight="bold" />
- Test mode — new sessions use dry_run=true
+ Test mode — this session runs agents as simulation
</div>
)}
{/* Drop overlay */}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx
new file mode 100644
index 0000000000..71791b5694
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx
@@ -0,0 +1,168 @@
+import { render, screen, cleanup } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { CopilotPage } from "../CopilotPage";
+
+// Mock child components that are complex and not under test here
+vi.mock("../components/ChatContainer/ChatContainer", () => ({
+ ChatContainer: () => <div data-testid="chat-container" />,
+}));
+vi.mock("../components/ChatSidebar/ChatSidebar", () => ({
+ ChatSidebar: () => <div data-testid="chat-sidebar" />,
+}));
+vi.mock("../components/DeleteChatDialog/DeleteChatDialog", () => ({
+ DeleteChatDialog: () => null,
+}));
+vi.mock("../components/MobileDrawer/MobileDrawer", () => ({
+ MobileDrawer: () => null,
+}));
+vi.mock("../components/MobileHeader/MobileHeader", () => ({
+ MobileHeader: () => null,
+}));
+vi.mock("../components/NotificationBanner/NotificationBanner", () => ({
+ NotificationBanner: () => null,
+}));
+vi.mock("../components/NotificationDialog/NotificationDialog", () => ({
+ NotificationDialog: () => null,
+}));
+vi.mock("../components/RateLimitResetDialog/RateLimitResetDialog", () => ({
+ RateLimitResetDialog: () => null,
+}));
+vi.mock("../components/ScaleLoader/ScaleLoader", () => ({
+ ScaleLoader: () => <div data-testid="scale-loader" />,
+}));
+vi.mock("../components/ArtifactPanel/ArtifactPanel", () => ({
+ ArtifactPanel: () => null,
+}));
+vi.mock("@/components/ui/sidebar", () => ({
+ SidebarProvider: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+}));
+
+// Mock hooks that hit the network
+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({
+ useGetV2GetCopilotUsage: () => ({
+ data: undefined,
+ isSuccess: false,
+ isError: false,
+ }),
+}));
+vi.mock("@/hooks/useCredits", () => ({
+ default: () => ({ credits: null, fetchCredits: vi.fn() }),
+}));
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",
+ ARTIFACTS: "ARTIFACTS",
+ CHAT_MODE_OPTION: "CHAT_MODE_OPTION",
+ },
+ useGetFlag: () => false,
+}));
+
+// Build the base mock return value for useCopilotPage
+const basePageState = {
+ sessionId: null as string | null,
+ messages: [],
+ status: "ready" as const,
+ error: undefined,
+ stop: vi.fn(),
+ isReconnecting: false,
+ isSyncing: false,
+ createSession: vi.fn(),
+ onSend: vi.fn(),
+ isLoadingSession: false,
+ isSessionError: false,
+ isCreatingSession: false,
+ isUploadingFiles: false,
+ isUserLoading: false,
+ isLoggedIn: true,
+ hasMoreMessages: false,
+ isLoadingMore: false,
+ loadMore: vi.fn(),
+ isMobile: false,
+ isDrawerOpen: false,
+ sessions: [],
+ isLoadingSessions: false,
+ handleOpenDrawer: vi.fn(),
+ handleCloseDrawer: vi.fn(),
+ handleDrawerOpenChange: vi.fn(),
+ handleSelectSession: vi.fn(),
+ handleNewChat: vi.fn(),
+ sessionToDelete: null,
+ isDeleting: false,
+ handleConfirmDelete: vi.fn(),
+ handleCancelDelete: vi.fn(),
+ historicalDurations: {},
+ rateLimitMessage: null,
+ dismissRateLimit: vi.fn(),
+ isDryRun: false,
+ sessionDryRun: false,
+};
+
+const mockUseCopilotPage = vi.fn(() => basePageState);
+
+vi.mock("../useCopilotPage", () => ({
+ useCopilotPage: () => mockUseCopilotPage(),
+}));
+
+afterEach(() => {
+ cleanup();
+ mockUseCopilotPage.mockReset();
+ mockUseCopilotPage.mockImplementation(() => basePageState);
+});
+
+describe("CopilotPage test-mode banner", () => {
+ it("does not show test-mode banner when there is no active session", () => {
+ render(<CopilotPage />);
+ expect(
+ screen.queryByText(/test mode.*this session runs agents/i),
+ ).toBeNull();
+ });
+
+ it("does not show test-mode banner when session exists but sessionDryRun is false", () => {
+ mockUseCopilotPage.mockReturnValue({
+ ...basePageState,
+ sessionId: "session-abc",
+ sessionDryRun: false,
+ });
+ render(<CopilotPage />);
+ expect(
+ screen.queryByText(/test mode.*this session runs agents/i),
+ ).toBeNull();
+ });
+
+ it("shows test-mode banner when session exists and sessionDryRun is true", () => {
+ mockUseCopilotPage.mockReturnValue({
+ ...basePageState,
+ sessionId: "session-abc",
+ sessionDryRun: true,
+ });
+ render(<CopilotPage />);
+ expect(
+ screen.getByText(/test mode.*this session runs agents/i),
+ ).toBeDefined();
+ });
+
+ it("does not show test-mode banner when sessionDryRun is true but no sessionId", () => {
+ mockUseCopilotPage.mockReturnValue({
+ ...basePageState,
+ sessionId: null,
+ sessionDryRun: true,
+ });
+ render(<CopilotPage />);
+ expect(
+ screen.queryByText(/test mode.*this session runs agents/i),
+ ).toBeNull();
+ });
+
+ it("shows loading spinner when user is loading", () => {
+ mockUseCopilotPage.mockReturnValue({
+ ...basePageState,
+ isUserLoading: true,
+ isLoggedIn: false,
+ });
+ render(<CopilotPage />);
+ expect(screen.getByTestId("scale-loader")).toBeDefined();
+ expect(screen.queryByTestId("chat-container")).toBeNull();
+ });
+});
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.ts
index 9580ef349a..a6e837c70e 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,6 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";
-import { getCopilotAuthHeaders, getSendSuppressionReason } from "../helpers";
+import {
+ getCopilotAuthHeaders,
+ getSendSuppressionReason,
+ resolveSessionDryRun,
+} from "../helpers";
import type { UIMessage } from "ai";
vi.mock("@/lib/supabase/actions", () => ({
@@ -17,6 +21,42 @@ import { getSystemHeaders } from "@/lib/impersonation";
const mockGetWebSocketToken = vi.mocked(getWebSocketToken);
const mockGetSystemHeaders = vi.mocked(getSystemHeaders);
+describe("resolveSessionDryRun", () => {
+ it("returns false when queryData is null", () => {
+ expect(resolveSessionDryRun(null)).toBe(false);
+ });
+
+ it("returns false when queryData is undefined", () => {
+ expect(resolveSessionDryRun(undefined)).toBe(false);
+ });
+
+ it("returns false when status is not 200", () => {
+ expect(resolveSessionDryRun({ status: 404 })).toBe(false);
+ });
+
+ it("returns false when status is 200 but metadata.dry_run is false", () => {
+ expect(
+ resolveSessionDryRun({
+ status: 200,
+ data: { metadata: { dry_run: false } },
+ }),
+ ).toBe(false);
+ });
+
+ it("returns false when status is 200 but metadata is missing", () => {
+ expect(resolveSessionDryRun({ status: 200, data: {} })).toBe(false);
+ });
+
+ it("returns true when status is 200 and metadata.dry_run is true", () => {
+ expect(
+ resolveSessionDryRun({
+ status: 200,
+ data: { metadata: { dry_run: true } },
+ }),
+ ).toBe(true);
+ });
+});
+
describe("getCopilotAuthHeaders", () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
index b6fedb722e..44f59fcc39 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
@@ -218,6 +218,9 @@ export function ChatInput({
onFilesSelected={handleFilesSelected}
disabled={isBusy}
/>
+ {/* Mode and model are per-message settings sent with each stream request,
+ so they can be freely changed between turns in an existing session.
+ Hide only while actively streaming (too late to change for that turn). */}
{showModeToggle && !isStreaming && (
<ModeToggleButton
mode={copilotChatMode}
@@ -230,11 +233,13 @@ export function ChatInput({
onToggle={handleToggleModel}
/>
)}
- {showDryRunToggle && (!hasSession || isDryRun) && (
+ {/* DryRun button only on new chats: once a session exists its
+ dry_run flag is locked and should be read from session metadata
+ (sessionDryRun in useCopilotPage), not toggled here. The banner
+ in CopilotPage.tsx reflects the actual session state. */}
+ {showDryRunToggle && !hasSession && (
<DryRunToggleButton
isDryRun={isDryRun}
- isStreaming={isStreaming}
- readOnly={hasSession}
onToggle={handleToggleDryRun}
/>
)}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx
index ddcf8489ce..b5a94a3bea 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
@@ -23,6 +23,8 @@ vi.mock("@/app/(platform)/copilot/store", () => ({
setCopilotChatMode: mockSetCopilotChatMode,
copilotLlmModel: mockCopilotLlmModel,
setCopilotLlmModel: mockSetCopilotLlmModel,
+ isDryRun: false,
+ setIsDryRun: vi.fn(),
initialPrompt: null,
setInitialPrompt: vi.fn(),
}),
@@ -166,6 +168,15 @@ describe("ChatInput mode toggle", () => {
expect(screen.queryByLabelText(/switch to/i)).toBeNull();
});
+ it("shows mode toggle when hasSession is true and not streaming", () => {
+ // Mode is per-message — can be changed between turns even in an existing session.
+ mockFlagValue = true;
+ render(<ChatInput onSend={mockOnSend} hasSession />);
+ expect(
+ screen.queryByLabelText(/switch to (fast|extended thinking) mode/i),
+ ).not.toBeNull();
+ });
+
it("exposes aria-pressed=true in extended_thinking mode", () => {
mockFlagValue = true;
mockCopilotMode = "extended_thinking";
@@ -235,6 +246,30 @@ describe("ChatInput model toggle", () => {
).toBeNull();
});
+ it("shows model toggle when hasSession is true and not streaming", () => {
+ // Model is per-message — can be changed between turns even in an existing session.
+ mockFlagValue = true;
+ render(<ChatInput onSend={mockOnSend} hasSession />);
+ expect(
+ screen.queryByLabelText(/switch to (advanced|standard) model/i),
+ ).not.toBeNull();
+ });
+
+ it("hides dry-run toggle when hasSession is true", () => {
+ // DryRun button is only for new chats — once a session exists its dry_run
+ // flag is immutable and shown via the CopilotPage banner, not this button.
+ mockFlagValue = true;
+ render(<ChatInput onSend={mockOnSend} hasSession />);
+ expect(screen.queryByLabelText(/test mode/i)).toBeNull();
+ expect(screen.queryByLabelText(/enable test mode/i)).toBeNull();
+ });
+
+ it("shows dry-run toggle when no session", () => {
+ mockFlagValue = true;
+ render(<ChatInput onSend={mockOnSend} />);
+ expect(screen.getByLabelText(/test mode|enable test mode/i)).toBeTruthy();
+ });
+
it("shows a toast when switching to advanced", async () => {
const { toast } = await import("@/components/molecules/Toast/use-toast");
mockFlagValue = true;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx
index 297cd04d8e..36c84d6826 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx
@@ -3,42 +3,34 @@
import { cn } from "@/lib/utils";
import { Flask } from "@phosphor-icons/react";
+// This button is only rendered on NEW chats (no active session).
+// Once a session exists, it is hidden — the session's dry_run flag is
+// immutable and reflected in the banner in CopilotPage.tsx instead.
+// Do NOT add readOnly/hasSession handling here; hide it at the call site.
interface Props {
isDryRun: boolean;
- isStreaming: boolean;
- readOnly?: boolean;
onToggle: () => void;
}
-export function DryRunToggleButton({
- isDryRun,
- isStreaming,
- readOnly = false,
- onToggle,
-}: Props) {
- const isDisabled = isStreaming || readOnly;
+export function DryRunToggleButton({ isDryRun, onToggle }: Props) {
return (
<button
type="button"
aria-pressed={isDryRun}
- disabled={isDisabled}
- onClick={readOnly ? undefined : onToggle}
+ onClick={onToggle}
className={cn(
"inline-flex min-h-11 min-w-11 items-center justify-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",
isDryRun
? "bg-amber-100 text-amber-900 hover:bg-amber-200"
: "text-neutral-500 hover:bg-neutral-100 hover:text-neutral-700",
- isDisabled && "cursor-default opacity-70",
)}
- aria-label={isDryRun ? "Test mode active" : "Enable Test mode"}
+ aria-label={
+ isDryRun ? "Test mode active — click to disable" : "Enable Test mode"
+ }
title={
- readOnly
- ? "Test mode active for this session"
- : isStreaming
- ? "Cannot change mode while streaming"
- : isDryRun
- ? "Test mode ON — click to disable"
- : "Enable Test mode — agents will run as dry-run"
+ isDryRun
+ ? "Test mode ON — new chats run agents as simulation (click to disable)"
+ : "Enable Test mode — new chats will run agents as simulation"
}
>
<Flask size={14} />
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsx
new file mode 100644
index 0000000000..d8920c8749
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsx
@@ -0,0 +1,41 @@
+import { render, screen, fireEvent, cleanup } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DryRunToggleButton } from "../DryRunToggleButton";
+
+afterEach(cleanup);
+
+// DryRunToggleButton only appears on new chats (no active session).
+// It has no readOnly/isStreaming props — those scenarios are handled by hiding
+// the button entirely at the ChatInput level when hasSession is true.
+describe("DryRunToggleButton", () => {
+ it("shows Test label when isDryRun is true", () => {
+ render(<DryRunToggleButton isDryRun={true} onToggle={vi.fn()} />);
+ expect(screen.getByText("Test")).toBeTruthy();
+ });
+
+ it("shows no text label when isDryRun is false", () => {
+ render(<DryRunToggleButton isDryRun={false} onToggle={vi.fn()} />);
+ expect(screen.queryByText("Test")).toBeNull();
+ });
+
+ it("calls onToggle when clicked", () => {
+ const onToggle = vi.fn();
+ render(<DryRunToggleButton isDryRun={false} onToggle={onToggle} />);
+ fireEvent.click(screen.getByRole("button"));
+ expect(onToggle).toHaveBeenCalledTimes(1);
+ });
+
+ it("sets aria-pressed=true when isDryRun is true", () => {
+ render(<DryRunToggleButton isDryRun={true} onToggle={vi.fn()} />);
+ expect(screen.getByRole("button").getAttribute("aria-pressed")).toBe(
+ "true",
+ );
+ });
+
+ it("sets aria-pressed=false when isDryRun is false", () => {
+ render(<DryRunToggleButton isDryRun={false} onToggle={vi.fn()} />);
+ expect(screen.getByRole("button").getAttribute("aria-pressed")).toBe(
+ "false",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx
index a77cb5b6f4..a17e702f1a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx
@@ -5,8 +5,9 @@ import { ModelToggleButton } from "../ModelToggleButton";
afterEach(cleanup);
describe("ModelToggleButton", () => {
- it("shows no label when model is standard", () => {
+ it("shows no text label when model is standard", () => {
render(<ModelToggleButton model="standard" onToggle={vi.fn()} />);
+ expect(screen.queryByText("Standard")).toBeNull();
expect(screen.queryByText("Advanced")).toBeNull();
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
index 34e2bea51a..b1d87a25d2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
@@ -52,6 +52,24 @@ export function parseSessionIDs(raw: string | null | undefined): Set<string> {
}
}
+/**
+ * Resolve the actual dry_run value for a session from the raw API response.
+ * Returns true only when the session response is a 200 with metadata.dry_run === true.
+ * Returns false for missing/non-200 responses so callers never show a stale
+ * preference value when the real session state is unknown.
+ */
+export function resolveSessionDryRun(queryData: unknown): boolean {
+ if (
+ queryData == null ||
+ typeof queryData !== "object" ||
+ !("status" in queryData) ||
+ (queryData as { status: unknown }).status !== 200
+ )
+ return false;
+ const d = queryData as { data?: { metadata?: { dry_run?: unknown } } };
+ return d.data?.metadata?.dry_run === true;
+}
+
/**
* Check whether a refetchSession result indicates the backend still has an
* active SSE stream for this session.
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index 1d34a99145..b5a02620c2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -10,6 +10,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { parseAsString, useQueryState } from "nuqs";
import { useEffect, useMemo, useRef } from "react";
import { convertChatSessionMessagesToUiMessages } from "./helpers/convertChatSessionToUiMessages";
+import { resolveSessionDryRun } from "./helpers";
interface UseChatSessionOptions {
dryRun?: boolean;
@@ -163,6 +164,18 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {
? ((sessionQuery.data.data.messages ?? []) as unknown[])
: [];
+ // The actual dry_run value stored in the session's metadata, read directly
+ // from the API response. This reflects what the session was ACTUALLY created
+ // with — not the user's current UI preference (isDryRun store).
+ //
+ // Design intent: the global isDryRun store is only used when creating NEW
+ // sessions. Once a session exists, its dry_run flag is immutable and should
+ // be read from here rather than from the store, which may have changed.
+ const sessionDryRun = useMemo(
+ () => resolveSessionDryRun(sessionQuery.data),
+ [sessionQuery.data],
+ );
+
return {
sessionId,
setSessionId,
@@ -177,5 +190,6 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {
createSession,
isCreatingSession,
refetchSession: sessionQuery.refetch,
+ sessionDryRun,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
index 01302c9f81..9e118c2bbc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -61,6 +61,7 @@ export function useCopilotPage() {
createSession,
isCreatingSession,
refetchSession,
+ sessionDryRun,
} = useChatSession({ dryRun: isDryRun });
const {
@@ -418,6 +419,11 @@ export function useCopilotPage() {
rateLimitMessage,
dismissRateLimit,
// Dry run dev toggle
+ // isDryRun = global preference for NEW sessions (from localStorage).
+ // sessionDryRun = actual dry_run value of the CURRENT session (from API).
+ // Use isDryRun to configure future sessions; use sessionDryRun to display
+ // the current session's simulation state (banner, indicators).
isDryRun,
+ sessionDryRun,
};
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index f93caabbb1..e5ad3bf296 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -82,6 +82,15 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Tracking Type"
}
+ },
+ {
+ "name": "graph_exec_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Exec Id"
+ }
}
],
"responses": {
@@ -207,6 +216,15 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Tracking Type"
}
+ },
+ {
+ "name": "graph_exec_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Exec Id"
+ }
}
],
"responses": {
@@ -309,6 +327,15 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Tracking Type"
}
+ },
+ {
+ "name": "graph_exec_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Exec Id"
+ }
}
],
"responses": {