AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(frontend/copilot): the in-chat Paused card for turns that land at a limit (#15401)
Nicholas Tindle68fad513f60f
diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.pyindex c06fa499c1..a2f7e847e6 100644--- a/autogpt_platform/backend/backend/blocks/autopilot.py+++ b/autogpt_platform/backend/backend/blocks/autopilot.py@@ -28,6 +28,7 @@ from backend.copilot.constants import (AUTOPILOT_BLOCK_TOOL_NAME,PER_TURN_SPEND_FLOOR_USD,)+from backend.copilot.credit_billing import credits_can_pay_block_turnsfrom backend.copilot.permissions import (DISABLED_LEGACY_TOOL_NAMES,CopilotPermissions,@@ -747,6 +748,8 @@ def _out_of_budget_message(pause: "TurnPause") -> str:"and your credit balance doesn't cover a run (it needs at least "f"${PER_TURN_SPEND_FLOOR_USD:.2f}). Add credits at {credits_url} to ""run it on credits."+ if credits_can_pay_block_turns()+ else f"Out of AutoPilot budget: {allowance} AutoPilot allowance is used up.")if pause.resets_at is None:return message@@ -928,8 +931,11 @@ async def _enqueue_for_recovery(# executor being a separate process.# TODO(#14244-f5): revisit together with run_agent's tree reset.envelope=root_envelope(recovery_turn_id, session_id=session_id),- # Still the block's turn: it may run on credits as the first did.+ # Still the block's turn: it may run on credits as the first did,+ # paid from the same tenancy.tool_name=_AUTOPILOT_TOOL_NAME,+ organization_id=session.organization_id,+ team_id=session.team_id,),timeout=10,)diff --git a/autogpt_platform/backend/backend/blocks/autopilot_refusal_test.py b/autogpt_platform/backend/backend/blocks/autopilot_refusal_test.pyindex 369e294582..fc1286e883 100644--- a/autogpt_platform/backend/backend/blocks/autopilot_refusal_test.py+++ b/autogpt_platform/backend/backend/blocks/autopilot_refusal_test.py@@ -110,6 +110,9 @@ def frontend(mocker):settings = MagicMock()settings.config.frontend_base_url = "https://platform.agpt.co/"mocker.patch("backend.blocks.autopilot.Settings", return_value=settings)+ mocker.patch(+ "backend.blocks.autopilot.credits_can_pay_block_turns", return_value=True+ )@pytest.mark.asyncio@@ -136,12 +139,31 @@ async def test_a_spent_trial_says_its_allowance_is_used_up(frontend):)+async def test_where_credits_cant_pay_the_refusal_doesnt_send_the_user_to_top_up(+ frontend, mocker+):+ # Credits off, or no engine to cap a credit-billed turn: credits never pay.+ mocker.patch(+ "backend.blocks.autopilot.credits_can_pay_block_turns", return_value=False+ )+ with _refused_for_budget(_OUT_OF_TODAY):+ with pytest.raises(AutoPilotOutOfBudgetError) as raised:+ await _execute()+ assert str(raised.value) == (+ "Out of AutoPilot budget: your plan's AutoPilot allowance is used up. "+ "The allowance resets 2026-10-12 00:00 UTC."+ )++@pytest.mark.asyncioasync def test_a_recovery_run_is_still_the_blocks_turn():"""So it may run on the credit balance as the first run could."""session = MagicMock()session.metadata.llm_auth_provider = "platform"session.metadata.llm_credential_id = None+ session.organization_id = "org-1"+ session.team_id = "team-1"enqueue = AsyncMock()with (@@ -154,6 +176,9 @@ async def test_a_recovery_run_is_still_the_blocks_turn():enqueue.assert_awaited_once()assert enqueue.await_args.kwargs["tool_name"] == "autopilot_block"+ # Billed to the same wallet: the organization's in an organization's run.+ kwargs = enqueue.await_args.kwargs+ assert (kwargs["organization_id"], kwargs["team_id"]) == ("org-1", "team-1")@pytest.mark.asynciodiff --git a/autogpt_platform/backend/backend/copilot/credit_billing.py b/autogpt_platform/backend/backend/copilot/credit_billing.pyindex d52a75924f..fc2abfe084 100644--- a/autogpt_platform/backend/backend/copilot/credit_billing.py+++ b/autogpt_platform/backend/backend/copilot/credit_billing.py@@ -205,7 +205,7 @@ async def bill_to_credits("""if user_id is None or tool_name != AUTOPILOT_BLOCK_TOOL_NAME:return None- if not settings.config.enable_credit or not config.thinking_available:+ if not credits_can_pay_block_turns():return Nonetry:balance = await _balance(user_id, organization_id)@@ -224,6 +224,12 @@ async def bill_to_credits()+def credits_can_pay_block_turns() -> bool:+ """Whether a block turn past the allowance can run on credits here: credits+ are on, and the SDK engine that caps a turn's spend can run."""+ return settings.config.enable_credit and config.thinking_available++async def _balance(user_id: str, organization_id: str | None) -> int:if organization_id:return await credit_db().get_org_credits(org_id=organization_id)diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 1491b5be44..65fec252c4 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -2971,7 +2971,9 @@ class Scheduler(AppService):if job is None:return Falsejob.remove()- self._delete_schedule_index_row(job_id)+ # Its index row stays: a row with no job is skipped on read, while the+ # chat's next turn at reset reuses this id, so deleting the row could+ # hide a job set again meanwhile from the chat's listing.self._invalidate_jobs_cache()logger.info(f"Removed {kind}-at-reset job for session {session_id[:12]}")return Truediff --git a/autogpt_platform/backend/backend/executor/scheduler_at_reset_test.py b/autogpt_platform/backend/backend/executor/scheduler_at_reset_test.pyindex e269b7286b..c91223f3e8 100644--- a/autogpt_platform/backend/backend/executor/scheduler_at_reset_test.py+++ b/autogpt_platform/backend/backend/executor/scheduler_at_reset_test.py@@ -183,8 +183,9 @@ def test_setting_it_again_replaces_the_earlier_job(live_scheduler):assert jobs[0].next_run_time == first + timedelta(days=1)-def test_cancel_drops_the_jobs_schedule_index_row(live_scheduler):- # Otherwise the schedule list shows it until the next reconcile.+def test_cancel_leaves_the_jobs_schedule_index_row(live_scheduler):+ # A row with no job is skipped on read, while the chat's next turn at reset+ # reuses the id: deleting the row could hide a job set again meanwhile.live_scheduler._schedule_index = MagicMock()live_scheduler.add_copilot_turn_schedule(user_id=USER,@@ -197,9 +198,7 @@ def test_cancel_drops_the_jobs_schedule_index_row(live_scheduler):)assert live_scheduler.cancel_at_reset_turn(USER, SESSION, "resume") is True- live_scheduler._schedule_index.delete_many.assert_called_once_with(- [at_reset_schedule_id("resume", SESSION)]- )+ live_scheduler._schedule_index.delete_many.assert_not_called()def test_cancel_removes_only_the_owners_job_and_is_idempotent(live_scheduler):diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsxindex ca0ca71010..65523eae33 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx@@ -568,3 +568,85 @@ function settledStatus(path: StreamPath) {? getTurnRuntime(TEST_SESSION_ID).getSnapshot().phase: getOrCreateCopilotChatRuntime(TEST_SESSION_ID).chat.status;}++describe.each(STREAM_PATHS)(+ "AutoPilot reopened on the %s path — a failure stored on the chat",+ (path) => {+ beforeEach(() => {+ streamPath.runtime = path === "stream runtime";+ });++ function failedChat(kind: string) {+ return [+ {+ id: "row-0",+ role: "user",+ content: "Summarize my inbox.",+ sequence: 0,+ },+ {+ id: "row-1",+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] The connection refused this turn.",+ sequence: 1,+ metadata: {+ provider_failure: {+ kind,+ message: "The connection refused this turn.",+ authProvider: "codex",+ credentialId: "cred-1",+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: kind === "auth_expired",+ },+ },+ },+ ];+ }++ // Still on the connection that failed, so the failure is still live.+ const onThatConnection = {+ dry_run: false,+ builder_graph_id: null,+ llm_auth_provider: "codex",+ llm_credential_id: "cred-1",+ } as const;++ beforeEach(() => {+ server.use(getGetV2ListChatConnectionsMockHandler200({ offers: [] }));+ });++ it("reopens the continue-elsewhere dialog for a spent quota", async () => {+ renderHost({+ sessionOverride: {+ messages: failedChat("usage_limit"),+ metadata: onThatConnection,+ },+ });++ expect(+ await screen.findByText(/hit this connection's limit/i, undefined, {+ timeout: 5000,+ }),+ ).toBeDefined();+ }, 15_000);++ it("leaves it closed for a failure that is not a limit", async () => {+ renderHost({+ sessionOverride: {+ messages: failedChat("auth_expired"),+ metadata: onThatConnection,+ },+ });++ await screen.findByText("Summarize my inbox.", undefined, {+ timeout: 5000,+ });+ await expect(+ screen.findByText(/hit this connection's limit/i, undefined, {+ timeout: 1500,+ }),+ ).rejects.toThrow();+ }, 15_000);+ },+);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 823da724cb..7fbb4586c7 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@@ -9,6 +9,7 @@ import {formatNotificationTitle,getCopilotAuthHeaders,getSendSuppressionReason,+ hasVisibleAssistantContent,parseSessionIDs,isEngineSwitchPart,resolveSessionDryRun,@@ -56,6 +57,34 @@ describe("formatNotificationTitle", () => {});});+describe("hasVisibleAssistantContent", () => {+ function assistant(parts: UIMessage["parts"]): UIMessage[] {+ return [{ id: "a1", role: "assistant", parts }];+ }++ it("counts a Paused card, the only thing a turn refused before it ran shows", () => {+ expect(+ hasVisibleAssistantContent(+ assistant([+ { type: "data-status", data: { message: "Picking it up…" } },+ { type: "data-turn-paused", data: { reason: "daily" } },+ ]),+ ),+ ).toBe(true);+ });++ it("does not count bookkeeping alone", () => {+ expect(+ hasVisibleAssistantContent(+ assistant([+ { type: "step-start" },+ { type: "data-status", data: { message: "Picking it up…" } },+ ]),+ ),+ ).toBe(false);+ });+});+describe("COPILOT_COMPLETION_NOTIFICATION", () => {it("matches the copy hardcoded in public/push-sw.js", () => {expect(COPILOT_COMPLETION_NOTIFICATION).toEqual({diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paused-card.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paused-card.test.tsxnew file mode 100644index 0000000000..c1ead66f05--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/paused-card.test.tsx@@ -0,0 +1,317 @@+import { screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { getGetV2GetSessionMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";+import { server } from "@/mocks/mock-server";+import {+ assistantTextChunks,+ streamSseResponse,+} from "@/tests/integrations/copilot-sse";++import { resetCopilotChatRegistry } from "../copilotChatRegistry";+import { useCopilotStreamStore } from "../copilotStreamStore";+import {+ renderHost,+ TEST_BACKEND_BASE_URL,+ TEST_SESSION_ID,+ typeAndSend,+} from "./sse-helpers";++vi.mock("@/services/environment", async (importActual) => {+ const actual = await importActual<typeof import("@/services/environment")>();+ return {+ ...actual,+ environment: {+ ...actual.environment,+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,+ },+ };+});++vi.mock("../helpers", async (importActual) => {+ const actual = await importActual<typeof import("../helpers")>();+ return {+ ...actual,+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),+ };+});++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: { id: "test-user" },+ isUserLoading: false,+ isLoggedIn: true,+ }),+}));++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: {+ CHAT_MODE_OPTION: "CHAT_MODE_OPTION",+ ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",+ },+ useGetFlag: () => false,+}));++const SYSTEM = "[__COPILOT_SYSTEM_e3b0__]";++function marker(+ sequence: number,+ pause: Record<string, unknown>,+ note: string,+) {+ return {+ id: `row-${sequence}`,+ role: "assistant",+ content: `${SYSTEM} ${note}`,+ sequence,+ metadata: {+ turn_paused: {+ resets_at: null,+ steps: null,+ checkpoint_saved: true,+ started: true,+ ...pause,+ },+ },+ };+}++function row(sequence: number, role: string, content: string) {+ return { id: `row-${sequence}`, role, content, sequence };+}++const PAUSED_CHAT = [+ row(0, "user", "Build the quarterly report."),+ row(1, "assistant", "Halfway there: the numbers are in."),+ marker(+ 2,+ { reason: "steps", steps: 450 },+ "Paused: checking in after a long run.",+ ),+];++beforeEach(() => {+ resetCopilotChatRegistry();+ useCopilotStreamStore.getState().resetAll();+ window.localStorage.clear();+});++afterEach(() => {+ resetCopilotChatRegistry();+});++describe("the Paused card in a reopened chat", () => {+ it("is rebuilt from the stored marker row, and only the last one offers ways back in", async () => {+ renderHost({+ sessionOverride: {+ messages: [+ ...PAUSED_CHAT,+ row(3, "user", "Carry on with the charts."),+ row(4, "assistant", "Charts drafted."),+ marker(+ 5,+ { reason: "task" },+ "Paused: this task reached its size limit.",+ ),+ ],+ },+ });++ const card = await screen.findByRole(+ "region",+ { name: "Paused · this task reached its size limit" },+ { timeout: 5000 },+ );+ expect(+ within(card).getByRole("button", { name: "Keep going" }),+ ).toBeDefined();+ expect(+ within(card).getByRole("button", { name: "Stop here" }),+ ).toBeDefined();+ expect(+ screen.getByRole("note", {+ name: "Paused · checking in after a long run. Picked back up",+ }),+ ).toBeDefined();+ // The row's grey system note gives way to the card it now draws.+ expect(+ screen.queryByText("Paused: this task reached its size limit."),+ ).toBeNull();+ }, 15_000);++ it("picks the task up on Keep going and follows the turn the server started", async () => {+ // The route stores the continuation note and dispatches the turn before+ // it answers; the page finds that turn on the session and resumes it.+ const note = row(+ 3,+ "assistant",+ `${SYSTEM} Keep going: pick the task up from the checkpoint above.`,+ );+ const answer = "Back on it: the charts are next.";+ const continued: unknown[] = [];+ let phase: "paused" | "running" | "done" = "paused";+ server.use(+ http.post(+ "*/api/chat/sessions/:sessionId/continue",+ async ({ request }) => {+ continued.push(await request.json());+ phase = "running";+ return HttpResponse.json({ turn_id: "turn-2" }, { status: 202 });+ },+ ),+ http.get(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ ({ request }) => {+ phase = "done";+ return streamSseResponse(assistantTextChunks(answer), {+ abortSignal: request.signal,+ });+ },+ ),+ );+ renderHost({+ sessionResponse: getGetV2GetSessionMockHandler200(() =>+ session(+ phase === "paused"+ ? { messages: PAUSED_CHAT }+ : phase === "running"+ ? {+ messages: [...PAUSED_CHAT, note],+ active_stream: {+ turn_id: "turn-2",+ last_message_id: "row-3",+ started_at: "2026-05-13T00:00:00Z",+ },+ }+ : {+ messages: [...PAUSED_CHAT, note, row(4, "assistant", answer)],+ },+ ),+ ),+ });++ const user = userEvent.setup();+ await user.click(+ await screen.findByRole(+ "button",+ { name: "Keep going" },+ { timeout: 5000 },+ ),+ );++ expect(+ await screen.findByText(answer, undefined, { timeout: 5000 }),+ ).toBeDefined();+ expect(continued).toEqual([{ model: "standard" }]);+ // Once the turn ends the stored rows come back, and the pause they hold+ // has the note and the new work after it: history now.+ expect(+ await screen.findByRole(+ "note",+ { name: "Paused · checking in after a long run. Picked back up" },+ { timeout: 5000 },+ ),+ ).toBeDefined();+ expect(screen.getByText(answer)).toBeDefined();+ expect(screen.queryByRole("button", { name: "Keep going" })).toBeNull();+ }, 15_000);+});++describe("the Paused card as the turn lands", () => {+ it("stays stopped when the live pause it was stopped on comes back as its stored row", async () => {+ let sent = false;+ server.use(+ http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ ({ request }) => {+ sent = true;+ return streamSseResponse(+ [+ { type: "start", messageId: "live-turn" },+ { type: "start-step" },+ { type: "text-start", id: "t1" },+ {+ type: "text-delta",+ id: "t1",+ delta: "Halfway there: the numbers are in.",+ },+ { type: "text-end", id: "t1" },+ { type: "finish-step" },+ {+ type: "data-turn-paused",+ data: {+ reason: "steps",+ resets_at: null,+ steps: 450,+ checkpoint_saved: true,+ started: true,+ },+ },+ { type: "finish" },+ ],+ // The turn ends a beat later, so the card is still the live part,+ // with no stored row yet, when it is stopped.+ {+ abortSignal: request.signal,+ perChunkDelaysMs: [0, 0, 0, 0, 0, 0, 0, 1500],+ },+ );+ },+ ),+ );+ renderHost({+ sessionResponse: getGetV2GetSessionMockHandler200(() =>+ session({ messages: sent ? PAUSED_CHAT : [] }),+ ),+ });++ await typeAndSend("Build the quarterly report.");+ const user = userEvent.setup();+ await user.click(+ await screen.findByRole(+ "button",+ { name: "Stop here" },+ { timeout: 5000 },+ ),+ );+ expect(screen.getByText("Stopped here")).toBeDefined();++ // Once the turn ends the chat swaps the live part for the stored row,+ // which the card then remounts from.+ await waitFor(+ () =>+ expect(+ document.querySelector(+ `[data-message-id="${TEST_SESSION_ID}-seq-2"]`,+ ),+ ).not.toBeNull(),+ { timeout: 8000 },+ );+ expect(+ screen.getByRole("note", {+ name: "Paused · checking in after a long run. Stopped here",+ }),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: "Keep going" })).toBeNull();+ }, 20_000);+});++function session(over: Partial<SessionDetailResponse>): SessionDetailResponse {+ return {+ id: TEST_SESSION_ID,+ created_at: "2026-05-13T00:00:00Z",+ updated_at: "2026-05-13T00:00:00Z",+ user_id: "test-user",+ chat_status: "idle",+ messages: [],+ has_more_messages: false,+ oldest_sequence: null,+ active_stream: null,+ metadata: { dry_run: false, builder_graph_id: null },+ expert_id: null,+ ...over,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.tsindex 41d6737b9a..4223971455 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.ts@@ -141,6 +141,22 @@ describe("latestProviderFailure", () => {expect(failure?.credentialId).toBe("cred-1");});+ it("recovers a failure stored on a retryable marker too", () => {+ // The retryable prefix is the backend's COPILOT_RETRYABLE_ERROR_PREFIX.+ // Matched under a wrong suffix, the marker read as a real reply, and the+ // scan reported the chat as recovered from the failure it sits on.+ const failure = latestProviderFailure([+ { role: "user", content: "hi", metadata: null },+ {+ role: "assistant",+ content: "[__COPILOT_RETRYABLE_ERROR_a9c2__] out of turns",+ metadata: { [PROVIDER_FAILURE_KEY]: { ...envelope, retryable: true } },+ },+ ]);+ expect(failure?.kind).toBe("usage_limit");+ expect(failure?.retryable).toBe(true);+ });+it("takes the newest one, so a recovered-from failure stays history", () => {const older = { ...envelope, credentialId: "old" };const newer = { ...envelope, credentialId: "new" };diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsxindex 579fc899a9..767e2f294f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx@@ -252,6 +252,52 @@ const BACKEND_STARTED_TURN_MESSAGES = [sessionMessage(3, "assistant", PERSISTED_HALF),];+const CHECKPOINT = "Halfway through: the numbers are in";+const CONTINUED = "Back on it: the charts are next";+const KEEP_GOING_NOTE =+ "Keep going: pick the task up from the checkpoint above.";++/**+ * A task that paused at a step check-in and was picked back up with Keep+ * going. The route saves the continuation note before it dispatches the+ * turn, so every row predates the running turn's ``started_at``: nothing of+ * that turn is persisted yet, and none of these rows are the replay's.+ */+const PICKED_UP_MESSAGES = [+ sessionMessage(1, "user", EARLIER_PROMPT),+ sessionMessage(2, "assistant", CHECKPOINT),+ {+ ...sessionMessage(+ 3,+ "assistant",+ "[__COPILOT_SYSTEM_e3b0__] Paused: checking in after a long run.",+ ),+ metadata: {+ turn_paused: {+ reason: "steps",+ resets_at: null,+ steps: 450,+ checkpoint_saved: true,+ started: true,+ },+ },+ },+ sessionMessage(+ 4,+ "assistant",+ `[__COPILOT_SYSTEM_e3b0__] ${KEEP_GOING_NOTE}`,+ ),+];++const CONTINUATION_REPLAY: UIMessageChunk[] = [+ { type: "data-status", data: { message: "Picking the task back up…" } },+ { type: "start", messageId: "continued-turn" },+ { type: "start-step" },+ { type: "text-start", id: "continued-1" },+ { type: "text-delta", id: "continued-1", delta: CONTINUED },+ { type: "text-end", id: "continued-1" },+];+function renderResumedSession(messages: SessionDetailResponseMessagesItem[] = HYDRATED_SESSION_MESSAGES,activeStreamStartedAt = "2026-05-13T00:04:00Z",@@ -529,6 +575,38 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);},);++ it(+ "keeps the paused answer when the turn picking it up has persisted nothing yet",+ { timeout: 20000 },+ async () => {+ renderResumedSession(+ PICKED_UP_MESSAGES,+ "2026-05-13T00:05:00Z",+ CONTINUATION_REPLAY,+ );++ expect(+ await screen.findByText(CONTINUED, undefined, { timeout: 10000 }),+ ).toBeDefined();++ // The replay only appends, so the answer the task paused on stays on+ // screen while the continuation streams — trimming back to the last+ // user message would hide it, and its card, until the turn ends.+ expect(screen.getAllByText(CHECKPOINT)).toHaveLength(1);+ expect(screen.getAllByText(KEEP_GOING_NOTE)).toHaveLength(1);+ expect(screen.getAllByText(EARLIER_PROMPT)).toHaveLength(1);+ // The pause is history now: one line, not a card with buttons. The+ // replayed turn's message opens with a copy of the bubble before it,+ // which must not draw that line a second time.+ expect(+ screen.getAllByRole("note", {+ name: "Paused · checking in after a long run. Picked back up",+ }),+ ).toHaveLength(1);+ expect(screen.queryByRole("button", { name: "Keep going" })).toBeNull();+ },+ );});/**diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex 6d8df370c1..03b5aa1177 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -362,6 +362,8 @@ export const ChatContainer = ({<CopilotChatActionsProvideronSend={guardedOnSend}onBackendTurn={onBackendTurn}+ sessionId={sessionId}+ assistantName={expertIdentity?.name ?? "Otto"}><LayoutGroup id="copilot-2-chat-layout"><div className="flex h-full min-h-0 w-full flex-col px-2 lg:px-0">diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex 212f93675f..9022a50d6a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -45,6 +45,7 @@ import {PENDING_DRAINED_PART_TYPE,} from "../../messageParts";import { RESTORE_STALL_TIMEOUT_MS } from "../../restoreConstants";+import { TURN_PAUSED_PART_TYPE } from "../../turnPause";import type { ExpertIdentity } from "../../useExpertMap";import { ChatMinimap } from "../ChatMinimap/ChatMinimap";import { WorkCard } from "../WorkCard/WorkCard";@@ -398,6 +399,9 @@ export function ChatMessagesContainer({// into the next part without flashing back to "Thinking...".if (lastPart.type === "step-start") return true;+ // A pause is how the turn ends, so nothing more is coming to wait on.+ if (lastPart.type === TURN_PAUSED_PART_TYPE) return true;+if (lastPart.type.startsWith(TOOL_PART_PREFIX) &&"state" in lastPart &&diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex cf67a0003a..61c3244399 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -228,6 +228,30 @@ describe("ChatMessagesContainer — assistant rendering", () => {expect(screen.getByTestId("thinking-indicator")).toBeDefined();});+ it("drops the thinking indicator once a streaming turn has landed on a pause", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={[+ {+ id: "assistant-paused",+ role: "assistant",+ parts: [+ { type: "text", text: "Saved where I got to." },+ {+ type: "data-turn-paused",+ data: { reason: "steps", steps: 450 },+ },+ ],+ },+ ]}+ status="streaming"+ />,+ );++ expect(screen.queryByTestId("thinking-indicator")).toBeNull();+ });+it("keeps the backend's status lines out of the thinking indicator", () => {render(<ChatMessagesContainerdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsxindex 4068a9f6bd..d0636d4017 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx@@ -27,6 +27,8 @@ import { SetupTriggerTool } from "../../../tools/SetupTrigger/SetupTrigger";import { ViewAgentOutputTool } from "../../../tools/ViewAgentOutput/ViewAgentOutput";import { CompactionCard } from "../../CompactionCard/CompactionCard";import { ExpertOnboardingCard } from "../../ExpertOnboardingCard/ExpertOnboardingCard";+import { TurnPausedCard } from "../../TurnPausedCard/TurnPausedCard";+import { TURN_PAUSED_PART_TYPE } from "../../../turnPause";import {parseCompactionOutput,type CompactionPhase,@@ -223,6 +225,19 @@ export function MessagePartRenderer({/>);}+ case TURN_PAUSED_PART_TYPE: {+ // A pause built from its stored row is keyed by that row; one still+ // streaming in has no row yet, so its key is this render's only.+ const rowKey = "id" in part ? part.id : undefined;+ return (+ <TurnPausedCard+ key={key}+ data={"data" in part ? part.data : undefined}+ pauseKey={rowKey || key}+ isStoredRow={Boolean(rowKey)}+ />+ );+ }case "tool-ask_question":return <AskQuestionTool key={key} part={part as ToolUIPart} />;case "tool-expert_onboarding":diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsxindex e0df0c6de8..a37ffd258f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsx@@ -7,6 +7,8 @@ import { getPendingOnboardingCallId } from "../../ExpertOnboardingCard/helpers";import { PendingOnboardingContext } from "../../ExpertOnboardingCard/PendingOnboardingContext";import { getPendingQuestions } from "../../QuestionDock/helpers";import { PendingQuestionsContext } from "../../QuestionDock/PendingQuestionsContext";+import { CurrentPauseContext } from "../../TurnPausedCard/CurrentPauseContext";+import { getCurrentPause } from "../../TurnPausedCard/helpers";interface Props {messages: UIMessage<unknown, UIDataTypes, UITools>[];@@ -14,9 +16,9 @@ interface Props {}/** What the session is still waiting on the user for: the clarifying-question- * dock, the hire's onboarding card and a held call's row each decide from- * here whether they are live or already history, rather than from local- * state a reload would lose. */+ * dock, the hire's onboarding card, a held call's row and a Paused card each+ * decide from here whether they are live or already history, rather than+ * from local state a reload would lose. */export function PendingAnswerContexts({ messages, children }: Props) {return (<PendingQuestionsContext.Provider value={getPendingQuestions(messages)}>@@ -24,7 +26,9 @@ export function PendingAnswerContexts({ messages, children }: Props) {value={getPendingOnboardingCallId(messages)}><HeldOutcomesContext.Provider value={getHeldOutcomes(messages)}>- {children}+ <CurrentPauseContext.Provider value={getCurrentPause(messages)}>+ {children}+ </CurrentPauseContext.Provider></HeldOutcomesContext.Provider></PendingOnboardingContext.Provider></PendingQuestionsContext.Provider>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsxindex 165a7843a8..9a353a45f2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx@@ -11,6 +11,8 @@ interface Props {/** Defaults to "copilot" — the standalone page. */chatSurface?: CopilotChatSurface;getExecutionShareToken?: (executionId: string) => string | null | undefined;+ sessionId?: string | null;+ assistantName?: string;children: React.ReactNode;}@@ -19,11 +21,20 @@ export function CopilotChatActionsProvider({onBackendTurn,chatSurface = "copilot",getExecutionShareToken,+ sessionId,+ assistantName,children,}: Props) {return (<CopilotChatActionsContext.Provider- value={{ onSend, onBackendTurn, chatSurface, getExecutionShareToken }}+ value={{+ onSend,+ onBackendTurn,+ chatSurface,+ getExecutionShareToken,+ sessionId,+ assistantName,+ }}>{children}</CopilotChatActionsContext.Provider>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.tsindex 987d07ee5c..bd8500af41 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts@@ -31,6 +31,10 @@ interface CopilotChatActions {* auth-gated ``/library/agents/...`` link.*/getExecutionShareToken?: (executionId: string) => string | null | undefined;+ /** The chat a card acts on. Absent where the surface has none to act on. */+ sessionId?: string | null;+ /** What the chat calls its assistant: the expert's name, or Otto. */+ assistantName?: string;}const CopilotChatActionsContext = createContext<CopilotChatActions | null>(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.tsindex 749b61a9ad..417dcc9515 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts@@ -8,6 +8,7 @@ import {useGetV2ListChatConnections,usePutV2ChangeTheConnectionAnExistingChatRunsOn,} from "@/app/api/__generated__/endpoints/chat/chat";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";import { toast } from "@/components/molecules/Toast/use-toast";import type { ProviderFailure } from "../../providerFailure";@@ -17,12 +18,15 @@ interface Args {failure: ProviderFailure | null;sessionId: string | null;onDismiss: () => void;+ /** Narrows which connections may be offered; any of them by default. */+ eligible?: (offer: AIConnectionOffer) => boolean;}export function useProviderLimitDialog({failure,sessionId,onDismiss,+ eligible,}: Args) {const queryClient = useQueryClient();@@ -43,7 +47,10 @@ export function useProviderLimitDialog({connectionsQuery.isError ||(connectionsQuery.data !== undefined &&connectionsQuery.data.status !== 200);- const alternative = alternativeConnection(offers, failure);+ const alternative = alternativeConnection(+ eligible ? offers?.filter(eligible) : offers,+ failure,+ );const { mutateAsync: changeConnection, isPending: isSwitching } =usePutV2ChangeTheConnectionAnExistingChatRunsOn({diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/CurrentPauseContext.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/CurrentPauseContext.tsnew file mode 100644index 0000000000..66a7a4b2bc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/CurrentPauseContext.ts@@ -0,0 +1,9 @@+"use client";++import { createContext } from "react";++/** The `data` of the pause the chat is sitting on, or `null` when it sits on+ * none, provided by PendingAnswerContexts. `undefined` — the default on+ * surfaces that don't track it, such as the share viewer — says nothing+ * either way, so every card there shows just its title. */+export const CurrentPauseContext = createContext<unknown>(undefined);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/TurnPausedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/TurnPausedCard.tsxnew file mode 100644index 0000000000..9b80852ca2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/TurnPausedCard.tsx@@ -0,0 +1,35 @@+"use client";++import { LivePausedCard } from "./components/LivePausedCard/LivePausedCard";+import { PausedLine } from "./components/PausedLine";+import { pauseTitle } from "./helpers";+import { useTurnPausedCard } from "./useTurnPausedCard";++interface Props {+ data: unknown;+ pauseKey: string;+ /** The pause is a stored row, so its key outlives a reload. */+ isStoredRow: boolean;+}++/**+ * Where a turn that landed at a limit ends: what stopped it and the ways to+ * pick it back up. Only the pause the chat is still sitting on offers them;+ * any other reads as a one-line record of what happened.+ */+export function TurnPausedCard({ data, pauseKey, isStoredRow }: Props) {+ const card = useTurnPausedCard({ data, pauseKey, isStoredRow });+ if (!card.pause) return null;+ if (card.isLive && card.sessionId) {+ return (+ <LivePausedCard+ pause={card.pause}+ sessionId={card.sessionId}+ assistantName={card.assistantName}+ onFollow={card.followTurn}+ onStop={card.stop}+ />+ );+ }+ return <PausedLine title={pauseTitle(card.pause)} note={card.note} />;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsxnew file mode 100644index 0000000000..ee2353dba4--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/TurnPausedCard.test.tsx@@ -0,0 +1,787 @@+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ getGetV2ListChatConnectionsMockHandler200,+ getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import { server } from "@/mocks/mock-server";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";++import { useCopilotUIStore } from "../../../store";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import { CurrentPauseContext } from "../CurrentPauseContext";+import { TurnPausedCard } from "../TurnPausedCard";++const { toast } = vi.hoisted(() => ({ toast: vi.fn() }));++vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >()),+ toast,+}));++vi.mock("@/services/pro-activation/useProActivation", () => ({+ useProActivation: () => ({ start: vi.fn(), isBusy: false, isReady: false }),+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >()),+ useGetFlag: () => true,+}));++const SESSION_ID = "chat-1";+// Sunday evening in local time, so the resets below read the same anywhere.+const NOW = new Date(2026, 9, 11, 20, 48);+const TONIGHT_1AM = new Date(2026, 9, 12, 1, 0);+const WEDNESDAY_1AM = new Date(2026, 9, 14, 1, 0);+const RESUMES_AT = new Date(2026, 9, 12, 1, 5);++function pause(over: Record<string, unknown> = {}) {+ return {+ reason: "daily",+ resets_at: TONIGHT_1AM.toISOString(),+ steps: null,+ checkpoint_saved: true,+ started: true,+ ...over,+ };+}++function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {+ return {+ offer_id: "platform:deployment",+ provider_family: "autogpt",+ auth_provider: "platform",+ display_name: "AutoGPT Platform",+ auth_method: "deployment",+ credential_id: null,+ backed_by_label: "Your AutoGPT plan",+ description: "",+ state: "ready",+ selectable: true,+ is_default: true,+ tiers: [],+ limitations: [],+ lock_reason: null,+ unlock_href: null,+ ...over,+ };+}++const PLATFORM = offer();+const CHATGPT = offer({+ offer_id: "codex:cred-1",+ provider_family: "openai",+ auth_provider: "codex",+ display_name: "ChatGPT",+ auth_method: "chatgpt_oauth",+ credential_id: "cred-1",+ is_default: false,+});+const M365 = offer({+ offer_id: "microsoft_365_copilot:cred-9",+ provider_family: "microsoft",+ auth_provider: "microsoft_365_copilot",+ display_name: "Microsoft 365 Copilot",+ auth_method: "device_code",+ credential_id: "cred-9",+ is_default: false,+});++function backend({+ tier = "PRO",+ offers = [PLATFORM],+ jobs = [] as unknown[],+} = {}) {+ const calls = {+ continued: [] as unknown[],+ scheduled: [] as unknown[],+ switched: [] as unknown[],+ cancelled: 0,+ listed: 0,+ plan: 0,+ };+ let pending = jobs;+ server.use(+ http.get("*/api/chat/usage", () =>+ HttpResponse.json({+ tier,+ daily: { percent_used: 100, resets_at: TONIGHT_1AM.toISOString() },+ weekly: { percent_used: 40, resets_at: WEDNESDAY_1AM.toISOString() },+ }),+ ),+ http.get("*/api/credits/subscription", () => {+ calls.plan += 1;+ return HttpResponse.json({+ tier,+ tier_costs: { PRO: 5000, MAX: 32000 },+ monthly_cost: 5000,+ proration_credit_cents: 0,+ });+ }),+ getGetV2ListChatConnectionsMockHandler200({ offers }),+ http.get("*/api/chat/sessions/:id/at-reset", () => {+ calls.listed += 1;+ return HttpResponse.json({ jobs: pending });+ }),+ http.post("*/api/chat/sessions/:id/at-reset", async ({ request }) => {+ calls.scheduled.push(await request.json());+ const job = {+ kind: "resume",+ run_at: RESUMES_AT.toISOString(),+ message: null,+ };+ pending = [job];+ return HttpResponse.json(job);+ }),+ http.delete("*/api/chat/sessions/:id/at-reset/:kind", () => {+ calls.cancelled += 1;+ pending = [];+ return new HttpResponse(null, { status: 204 });+ }),+ http.post("*/api/chat/sessions/:id/continue", async ({ request }) => {+ calls.continued.push(await request.json());+ return HttpResponse.json({ turn_id: "turn-2" }, { status: 202 });+ }),+ getPutV2ChangeTheConnectionAnExistingChatRunsOnMockHandler200(+ async ({ request }) => {+ calls.switched.push(await request.json());+ return {};+ },+ ),+ );+ return calls;+}++interface CardOptions {+ current?: boolean;+ name?: string;+ sessionId?: string;+ /** Still streaming in: no stored row, so no key that outlives a reload. */+ live?: boolean;+ rowKey?: string;+}++function cardTree(+ data: Record<string, unknown>,+ {+ current = true,+ name = "Otto",+ sessionId = SESSION_ID,+ live = false,+ rowKey = "seq-7",+ }: CardOptions,+ onBackendTurn: () => void,+) {+ return (+ <CopilotChatActionsProvider+ onSend={vi.fn()}+ onBackendTurn={onBackendTurn}+ sessionId={sessionId}+ assistantName={name}+ >+ <CurrentPauseContext.Provider value={current ? data : null}>+ <TurnPausedCard+ data={data}+ pauseKey={live ? "live-turn-3" : rowKey}+ isStoredRow={!live}+ />+ </CurrentPauseContext.Provider>+ </CopilotChatActionsProvider>+ );+}++function renderCard(data: Record<string, unknown>, options: CardOptions = {}) {+ const onBackendTurn = vi.fn();+ const view = render(cardTree(data, options, onBackendTurn));+ return {+ onBackendTurn,+ ...view,+ rerenderCard: (next: Record<string, unknown>, nextOptions: CardOptions) =>+ view.rerender(cardTree(next, nextOptions, onBackendTurn)),+ };+}++/** Exact text whose spaces may be any whitespace: times can carry a narrow+ * no-break space before "AM", depending on the ICU build. */+function phrase(text: string) {+ const escaped = text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return new RegExp(`^${escaped.replace(/ /g, "\\s")}$`);+}++function buttonsIn(card: HTMLElement) {+ return within(card)+ .queryAllByRole("button")+ .map((button) => (button.textContent ?? "").replace(/\s+/g, " ").trim());+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(NOW);+ window.localStorage.clear();+ useCopilotUIStore.setState({ copilotLlmModel: "standard" });+});++afterEach(() => {+ vi.useRealTimers();+});++describe("TurnPausedCard — what it says and offers", () => {+ it.each([+ [+ "a daily budget pause",+ pause(),+ "Paused · out of today's budget",+ "Otto saved its progress above. Your budget resets at 1:00 AM, in 4 h 12 min.",+ ["Resume at 1:00 AM", "Upgrade"],+ ],+ [+ "a weekly budget pause",+ pause({ reason: "weekly", resets_at: WEDNESDAY_1AM.toISOString() }),+ "Paused · out of this week's budget",+ "Otto saved its progress above. Your budget resets Wednesday at 1:00 AM, in 2 days.",+ ["Resume Wednesday at 1:00 AM", "Upgrade"],+ ],+ [+ "a pause stopped before its checkpoint",+ pause({ checkpoint_saved: false }),+ "Paused · out of today's budget",+ "Otto was stopped before it could summarize its progress. Your budget resets at 1:00 AM, in 4 h 12 min.",+ ["Resume at 1:00 AM", "Upgrade"],+ ],+ [+ "a turn refused before it ran",+ pause({ started: false }),+ "Not started · out of today's budget",+ "Otto didn't start this because you're out of today's budget. It resets at 1:00 AM, in 4 h 12 min.",+ ["Resume at 1:00 AM", "Upgrade"],+ ],+ // No plan (a trial that is over): the backend sends "weekly" with no+ // reset, so there is no window to name and nothing to wait for.+ [+ "a budget with no plan behind it, which never refills",+ pause({ reason: "weekly", resets_at: null }),+ "Paused · out of AutoPilot budget",+ "Otto saved its progress above.",+ ["Upgrade"],+ ],+ [+ "a turn refused on a budget that never refills",+ pause({ reason: "weekly", resets_at: null, started: false }),+ "Not started · out of AutoPilot budget",+ "Otto didn't start this because you're out of AutoPilot budget.",+ ["Upgrade"],+ ],+ [+ "a spent trial",+ pause({ reason: "trial", resets_at: null }),+ "Paused · trial allowance used",+ "Otto saved its progress above.",+ ["Upgrade"],+ ],+ [+ "a task at its size limit",+ pause({ reason: "task", resets_at: null }),+ "Paused · this task reached its size limit",+ "Otto saved its progress above.",+ ["Keep going", "Stop here"],+ ],+ [+ "a step check-in",+ pause({ reason: "steps", resets_at: null, steps: 450 }),+ "Paused · checking in after a long run",+ "Otto has taken 450 steps on this and summarized its progress above.",+ ["Keep going", "Stop here"],+ ],+ ])("%s", async (_, data, title, body, buttons) => {+ backend();+ renderCard(data);+ const card = await screen.findByRole("region", { name: title });+ expect(within(card).getByText(phrase(body))).toBeDefined();+ await waitFor(() => expect(buttonsIn(card)).toEqual(buttons));+ });++ it("counts a reset just under a day away in hours, as it names the time without a day", async () => {+ // Tuesday, a day less 30 seconds before the reset.+ vi.setSystemTime(new Date(2026, 9, 13, 1, 0, 30));+ backend();+ renderCard(+ pause({ reason: "weekly", resets_at: WEDNESDAY_1AM.toISOString() }),+ );+ const card = await screen.findByRole("region", {+ name: "Paused · out of this week's budget",+ });++ expect(+ within(card).getByText(+ phrase(+ "Otto saved its progress above. Your budget resets at 1:00 AM, in 24 h.",+ ),+ ),+ ).toBeDefined();+ });++ it("offers ChatGPT beside Upgrade on a budget that never refills, and never a resume", async () => {+ const calls = backend({ offers: [PLATFORM, CHATGPT] });+ renderCard(pause({ reason: "weekly", resets_at: null }));+ const card = await screen.findByRole("region", {+ name: "Paused · out of AutoPilot budget",+ });++ await waitFor(() =>+ expect(buttonsIn(card)).toEqual(["Continue on ChatGPT", "Upgrade"]),+ );+ expect(+ within(card).getByText("Otto saved its progress above."),+ ).toBeDefined();+ expect(calls.listed).toBe(0);+ });++ it("speaks as the chat's own expert", async () => {+ backend();+ renderCard(pause({ reason: "task", resets_at: null }), { name: "Nova" });+ expect(screen.getByText("Nova saved its progress above.")).toBeDefined();+ });++ it("leaves Upgrade off a top-tier plan, which keeps Resume and ChatGPT", async () => {+ const calls = backend({ tier: "MAX", offers: [PLATFORM, CHATGPT] });+ renderCard(pause());+ const card = await screen.findByRole("region", {+ name: "Paused · out of today's budget",+ });+ await screen.findByRole("button", { name: "Continue on ChatGPT" });+ await waitFor(() => expect(calls.plan).toBeGreaterThan(0));+ await expect(+ screen.findByRole("button", { name: "Upgrade" }, { timeout: 1000 }),+ ).rejects.toThrow();+ expect(buttonsIn(card)).toEqual([+ "Resume at 1:00 AM",+ "Continue on ChatGPT",+ ]);+ });+});++describe("TurnPausedCard — Keep going", () => {+ it("picks the task up on the composer's model, then follows the turn", async () => {+ const calls = backend();+ useCopilotUIStore.setState({ copilotLlmModel: "advanced" });+ const { onBackendTurn } = renderCard(+ pause({ reason: "steps", resets_at: null, steps: 450 }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Keep going" }));++ await waitFor(() => expect(onBackendTurn).toHaveBeenCalledOnce());+ expect(calls.continued).toEqual([{ model: "advanced" }]);+ expect(+ screen.getByRole("note", {+ name: "Paused · checking in after a long run. Picked back up",+ }),+ ).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();+ });++ it("follows the turn that is already running instead of failing", async () => {+ backend();+ server.use(+ http.post("*/api/chat/sessions/:id/continue", () =>+ HttpResponse.json({ detail: "turn_in_progress" }, { status: 409 }),+ ),+ );+ const { onBackendTurn } = renderCard(+ pause({ reason: "task", resets_at: null }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Keep going" }));++ await waitFor(() => expect(onBackendTurn).toHaveBeenCalledOnce());+ expect(await screen.findByText("Picked back up")).toBeDefined();+ });++ it("says why when the chat now runs on Microsoft 365 Copilot", async () => {+ backend();+ server.use(+ http.post("*/api/chat/sessions/:id/continue", () =>+ HttpResponse.json(+ { detail: "unsupported_connection" },+ { status: 409 },+ ),+ ),+ );+ const { onBackendTurn } = renderCard(+ pause({ reason: "task", resets_at: null }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Keep going" }));++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Couldn't pick this back up",+ description:+ "This chat now runs on Microsoft 365 Copilot, which can't pick up a paused task. Switch its connection back to keep going.",+ variant: "destructive",+ }),+ );+ expect(onBackendTurn).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: "Keep going" })).toBeDefined();+ });++ it("passes on the server's reason when too many tasks are running", async () => {+ backend();+ const tooMany =+ "You have 3 tasks already running. Please wait for one of them to finish before starting a new one.";+ server.use(+ http.post("*/api/chat/sessions/:id/continue", () =>+ HttpResponse.json({ detail: tooMany }, { status: 429 }),+ ),+ );+ const { onBackendTurn } = renderCard(+ pause({ reason: "task", resets_at: null }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Keep going" }));++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Couldn't pick this back up",+ description: tooMany,+ variant: "destructive",+ }),+ );+ expect(onBackendTurn).not.toHaveBeenCalled();+ });++ it("turns into the budget pause when the account ran out meanwhile", async () => {+ backend();+ server.use(+ http.post("*/api/chat/sessions/:id/continue", () =>+ HttpResponse.json(+ {+ detail: {+ kind: "usage_limit",+ message: "You've reached your daily usage limit.",+ authProvider: "platform",+ credentialId: null,+ resetsAt: TONIGHT_1AM.getTime() / 1000,+ retryable: false,+ reconnectFixesIt: false,+ },+ },+ { status: 429 },+ ),+ ),+ );+ const { onBackendTurn } = renderCard(+ pause({ reason: "task", resets_at: null }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Keep going" }));++ const card = await screen.findByRole("region", {+ name: "Paused · out of today's budget",+ });+ expect(+ within(card).getByText(+ phrase(+ "Otto saved its progress above. Your budget resets at 1:00 AM, in 4 h 12 min.",+ ),+ ),+ ).toBeDefined();+ await waitFor(() =>+ expect(buttonsIn(card)).toEqual(["Resume at 1:00 AM", "Upgrade"]),+ );+ expect(onBackendTurn).not.toHaveBeenCalled();+ });++ it("is offered once the budget has refilled", async () => {+ backend();+ renderCard(+ pause({ resets_at: new Date(2026, 9, 11, 20, 0).toISOString() }),+ );++ expect(+ screen.getByText("Otto saved its progress above. Your budget has reset."),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: "Keep going" })).toBeDefined();+ expect(screen.queryByRole("button", { name: /^Resume/ })).toBeNull();+ });++ it("keeps counting down while the chat sits open, and is offered once the reset passes", async () => {+ vi.useFakeTimers({ toFake: ["Date", "setInterval", "clearInterval"] });+ vi.setSystemTime(NOW);+ backend();+ renderCard(pause());+ const card = await screen.findByRole("region", {+ name: "Paused · out of today's budget",+ });+ await waitFor(() =>+ expect(buttonsIn(card)).toEqual(["Resume at 1:00 AM", "Upgrade"]),+ );++ // Synchronous from here: the usage poll fires but none of its responses+ // land, so only the card's own clock can move the text.+ act(() => {+ vi.advanceTimersByTime(10 * 60_000);+ });++ expect(+ within(card).getByText(+ phrase(+ "Otto saved its progress above. Your budget resets at 1:00 AM, in 4 h 2 min.",+ ),+ ),+ ).toBeDefined();++ act(() => {+ vi.setSystemTime(TONIGHT_1AM);+ vi.advanceTimersByTime(1000);+ });++ expect(+ within(card).getByText(+ "Otto saved its progress above. Your budget has reset.",+ ),+ ).toBeDefined();+ expect(buttonsIn(card)).toEqual(["Keep going", "Upgrade"]);+ });+});++describe("TurnPausedCard — Resume at the reset", () => {+ it("sets the resume, says when it runs, and cancels it", async () => {+ const calls = backend();+ renderCard(pause());++ fireEvent.click(+ await screen.findByRole("button", { name: phrase("Resume at 1:00 AM") }),+ );++ expect(await screen.findByText(phrase("Resumes at 1:05 AM"))).toBeDefined();+ expect(calls.scheduled).toEqual([{ kind: "resume", message: null }]);+ expect(screen.queryByRole("button", { name: /^Resume/ })).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(+ await screen.findByRole("button", { name: phrase("Resume at 1:00 AM") }),+ ).toBeDefined();+ expect(calls.cancelled).toBe(1);+ expect(screen.queryByText(/Resumes at/)).toBeNull();+ });++ it("shows a resume that was already set when the chat opens", async () => {+ backend({+ jobs: [+ { kind: "send", run_at: RESUMES_AT.toISOString(), message: "Hi" },+ { kind: "resume", run_at: RESUMES_AT.toISOString(), message: null },+ ],+ });+ renderCard(pause());++ expect(await screen.findByText(phrase("Resumes at 1:05 AM"))).toBeDefined();+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDefined();+ expect(screen.queryByRole("button", { name: /^Resume/ })).toBeNull();+ });++ it("offers Keep going instead when the budget turns out to be back", async () => {+ backend();+ server.use(+ http.post("*/api/chat/sessions/:id/at-reset", () =>+ HttpResponse.json({ detail: "not_out_of_budget" }, { status: 409 }),+ ),+ );+ renderCard(pause());++ fireEvent.click(+ await screen.findByRole("button", { name: phrase("Resume at 1:00 AM") }),+ );++ expect(+ await screen.findByRole("button", { name: "Keep going" }),+ ).toBeDefined();+ expect(+ screen.getByText("Otto saved its progress above. Your budget has reset."),+ ).toBeDefined();+ });++ it.each([+ {+ status: 409,+ detail: "no_reset",+ title: "This allowance doesn't reset",+ description: "Upgrade to keep going.",+ },+ {+ status: 503,+ detail: "Rate limit service degraded, retry shortly",+ title: "Couldn't check your budget",+ description: "Try again in a moment.",+ },+ ])(+ "says why it couldn't set the resume ($status $detail)",+ async ({ status, detail, title, description }) => {+ backend();+ server.use(+ http.post("*/api/chat/sessions/:id/at-reset", () =>+ HttpResponse.json({ detail }, { status }),+ ),+ );+ renderCard(pause());++ fireEvent.click(+ await screen.findByRole("button", {+ name: phrase("Resume at 1:00 AM"),+ }),+ );++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title,+ description,+ variant: "destructive",+ }),+ );+ expect(+ screen.getByRole("button", { name: phrase("Resume at 1:00 AM") }),+ ).toBeDefined();+ },+ );+});++describe("TurnPausedCard — Continue on ChatGPT", () => {+ it("moves the chat to the ChatGPT account, then picks the task up there", async () => {+ const calls = backend({ offers: [PLATFORM, M365, CHATGPT] });+ const { onBackendTurn } = renderCard(pause());++ fireEvent.click(+ await screen.findByRole("button", { name: "Continue on ChatGPT" }),+ );++ await waitFor(() => expect(onBackendTurn).toHaveBeenCalledOnce());+ expect(calls.switched).toEqual([+ { llm_auth_provider: "codex", llm_credential_id: "cred-1" },+ ]);+ expect(calls.continued).toEqual([{ model: "standard" }]);+ });++ it("never offers Microsoft 365 Copilot, which runs no tools, nor a locked ChatGPT", async () => {+ backend({+ offers: [+ PLATFORM,+ M365,+ { ...CHATGPT, offer_id: "codex:locked", credential_id: null },+ { ...CHATGPT, offer_id: "codex:cred-2", selectable: false },+ ],+ });+ renderCard(pause());++ await screen.findByRole("button", { name: "Upgrade" });+ await expect(+ screen.findByRole("button", { name: /continue on/i }, { timeout: 1000 }),+ ).rejects.toThrow();+ });++ it("is not offered for a pause the account still has budget for", async () => {+ backend({ offers: [PLATFORM, CHATGPT] });+ renderCard(pause({ reason: "task", resets_at: null }));++ await expect(+ screen.findByRole("button", { name: /continue on/i }, { timeout: 1000 }),+ ).rejects.toThrow();+ });+});++describe("TurnPausedCard — once it's history", () => {+ it("stops here, and stays stopped when the chat is opened again", () => {+ backend();+ const data = pause({ reason: "steps", resets_at: null, steps: 450 });+ const first = renderCard(data);++ fireEvent.click(screen.getByRole("button", { name: "Stop here" }));++ expect(screen.getByText("Stopped here")).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();++ first.unmount();+ renderCard(data);+ expect(screen.getByText("Stopped here")).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();+ });++ it("keeps a stop made while the pause was live once its stored row takes over, and only for that pause", () => {+ backend();+ const sessionId = "chat-stopped-live";+ const data = pause({ reason: "steps", resets_at: null, steps: 450 });+ const live = renderCard(data, { sessionId, live: true });++ fireEvent.click(screen.getByRole("button", { name: "Stop here" }));+ expect(screen.getByText("Stopped here")).toBeDefined();++ // The stream ends and the chat rebuilds the pause from its stored row.+ live.unmount();+ const stored = renderCard({ ...data }, { sessionId, rowKey: "seq-9" });+ expect(screen.getByText("Stopped here")).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();++ // Kept under that row from now on, as for a stop made on the row itself.+ stored.unmount();+ const reopened = renderCard({ ...data }, { sessionId, rowKey: "seq-9" });+ expect(screen.getByText("Stopped here")).toBeDefined();++ // A later pause in the same chat is its own, however alike.+ reopened.unmount();+ renderCard({ ...data }, { sessionId, rowKey: "seq-12" });+ expect(screen.getByRole("button", { name: "Stop here" })).toBeDefined();+ });++ it("forgets a live stop the chat moved past before the pause's row arrived", () => {+ backend();+ const sessionId = "chat-moved-past";+ const data = pause({ reason: "task", resets_at: null });+ const live = renderCard(data, { sessionId, live: true });++ fireEvent.click(screen.getByRole("button", { name: "Stop here" }));+ // A new message lands under it while it is still the live part.+ live.rerenderCard(data, { sessionId, live: true, current: false });+ live.unmount();++ renderCard({ ...data }, { sessionId, rowKey: "seq-12" });+ expect(screen.getByRole("button", { name: "Keep going" })).toBeDefined();+ });++ it("reads as one static line once the chat has moved past it", () => {+ backend();+ renderCard(pause(), { current: false });++ expect(+ screen.getByRole("note", {+ name: "Paused · out of today's budget. Picked back up",+ }),+ ).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();+ });++ it("shows just the title where the chat can't be acted on", () => {+ render(+ <CopilotChatActionsProvider onSend={vi.fn()} chatSurface="share">+ <TurnPausedCard data={pause()} pauseKey="seq-7" isStoredRow />+ </CopilotChatActionsProvider>,+ );++ expect(+ screen.getByRole("note", { name: "Paused · out of today's budget" }),+ ).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/useNow.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/useNow.test.tsnew file mode 100644index 0000000000..bfc006e06e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/__tests__/useNow.test.ts@@ -0,0 +1,38 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useNow } from "../components/LivePausedCard/useNow";++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++describe("useNow", () => {+ it("keeps time until the moment it counts to, then stops", () => {+ const start = Date.now();+ const { result } = renderHook(() => useNow(start + 2_500));++ act(() => vi.advanceTimersByTime(1_000));+ expect(result.current.getTime()).toBe(start + 1_000);++ act(() => vi.advanceTimersByTime(2_000));+ const stopped = result.current.getTime();+ expect(stopped).toBeGreaterThanOrEqual(start + 2_500);++ act(() => vi.advanceTimersByTime(5_000));+ expect(result.current.getTime()).toBe(stopped);+ });++ it("doesn't tick with nothing to count to", () => {+ const { result } = renderHook(() => useNow(null));+ const first = result.current.getTime();++ act(() => vi.advanceTimersByTime(5_000));++ expect(result.current.getTime()).toBe(first);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/LivePausedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/LivePausedCard.tsxnew file mode 100644index 0000000000..c07e28c360--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/LivePausedCard.tsx@@ -0,0 +1,50 @@+"use client";++import { PauseIcon } from "@hugeicons/core-free-icons";++import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";++import type { TurnPause } from "../../../../turnPause";+import { PausedCardActions } from "./components/PausedCardActions";+import { useLivePausedCard } from "./useLivePausedCard";++interface Props {+ pause: TurnPause;+ sessionId: string;+ assistantName: string;+ onFollow: () => void;+ onStop: () => void;+}++export function LivePausedCard({ onStop, ...args }: Props) {+ const card = useLivePausedCard(args);+ const hasActions =+ card.resume.resumesAt !== null ||+ card.primary !== null ||+ card.chatGptName !== null ||+ card.canStop ||+ card.canUpgrade;++ return (+ <section+ aria-label={card.title}+ className="my-2 overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-sm duration-500 animate-in fade-in slide-in-from-bottom-2 fill-mode-both"+ >+ <div className="flex items-start gap-3 px-5 py-4">+ <span className="flex size-9 shrink-0 items-center justify-center rounded-xl border border-purple-200 bg-purple-50 text-purple-600">+ <Icon icon={PauseIcon} size={18} />+ </span>+ <div className="min-w-0 flex-1">+ <Text variant="body-medium" className="!text-zinc-900">+ {card.title}+ </Text>+ <Text variant="small" className="mt-1 !leading-5 !text-zinc-500">+ {card.body}+ </Text>+ </div>+ </div>+ {hasActions && <PausedCardActions card={card} onStop={onStop} />}+ </section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsxnew file mode 100644index 0000000000..4679797d47--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/components/PausedCardActions.tsx@@ -0,0 +1,98 @@+import { ArrowRight02Icon, Clock01Icon } from "@hugeicons/core-free-icons";++import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";++import { resetAt, resumeLabel } from "../../../helpers";+import type { useLivePausedCard } from "../useLivePausedCard";++interface Props {+ card: ReturnType<typeof useLivePausedCard>;+ onStop: () => void;+}++export function PausedCardActions({ card, onStop }: Props) {+ const { keep, resume, chatGpt } = card;+ const isBusy =+ keep.isContinuing ||+ resume.isScheduling ||+ resume.isCancelling ||+ chatGpt.isSwitching;++ return (+ <div className="flex flex-wrap items-center gap-2 border-t border-zinc-100 px-5 py-3">+ {resume.resumesAt && (+ <div className="flex items-center gap-1.5 pr-1">+ <Icon icon={Clock01Icon} size={14} className="text-purple-500" />+ <Text variant="small-medium" className="!text-zinc-700">+ Resumes {resetAt(resume.resumesAt, card.now)}+ </Text>+ <Button+ variant="link"+ onClick={() => void resume.cancelResume()}+ loading={resume.isCancelling}+ disabled={isBusy}+ className="ml-1 text-sm"+ >+ Cancel+ </Button>+ </div>+ )}+ {card.primary === "resume" && (+ <Button+ size="small"+ onClick={() => void resume.resumeAtReset()}+ loading={resume.isScheduling}+ disabled={isBusy}+ >+ {resumeLabel(card.shown.resets_at, card.now)}+ </Button>+ )}+ {card.primary === "keep_going" && (+ <Button+ size="small"+ onClick={() => void keep.keepGoing()}+ loading={keep.isContinuing}+ disabled={isBusy}+ >+ Keep going+ </Button>+ )}+ {card.chatGptName && (+ <Button+ size="small"+ variant="secondary"+ onClick={() => void chatGpt.continueHere()}+ // After the switch, the pick-up runs under this button too.+ loading={+ chatGpt.isSwitching ||+ (keep.isContinuing && card.primary !== "keep_going")+ }+ disabled={isBusy}+ >+ Continue on {card.chatGptName}+ </Button>+ )}+ {card.canStop && (+ <Button size="small" variant="ghost" onClick={onStop} disabled={isBusy}>+ Stop here+ </Button>+ )}+ {card.canUpgrade && (+ <Button+ size="small"+ // The only way on for a trial or a budget that never refills.+ variant={+ card.primary === null && !resume.resumesAt ? "primary" : "ghost"+ }+ onClick={card.upgrade}+ disabled={isBusy || card.isUpgradeDisabled}+ rightIcon={<Icon icon={ArrowRight02Icon} size={14} />}+ >+ Upgrade+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/helpers.tsnew file mode 100644index 0000000000..3973f4f2b3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/helpers.ts@@ -0,0 +1,148 @@+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";++import {+ parseProviderFailure,+ type ProviderFailure,+} from "../../../../providerFailure";+import type { TurnPause } from "../../../../turnPause";+import { neverResets } from "../../helpers";++/** A budget pause waits on our own allowance, so the platform is the+ * connection that's out and never the one to continue on. */+export const PLATFORM_BUDGET: ProviderFailure = {+ kind: "usage_limit",+ message: "Usage limit reached",+ authProvider: "platform",+ credentialId: null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+};++/** A task can only be picked back up where tools run: ChatGPT runs them,+ * Microsoft 365 Copilot returns text only. */+export function canContinueTask(offer: AIConnectionOffer): boolean {+ return offer.auth_provider === "codex";+}++interface PrimaryArgs {+ pause: TurnPause;+ budgetBack: boolean;+ resume: { resumesAt: Date | null };+}++/** What the card leads with. A trial, or a budget that never refills, has+ * only Upgrade (and ChatGPT) as ways on; a resume already set shows in place+ * of the button that would set it. */+export function primaryAction({+ pause,+ budgetBack,+ resume,+}: PrimaryArgs): "keep_going" | "resume" | null {+ if (pause.reason === "trial" || neverResets(pause)) return null;+ if (pause.reason === "task" || pause.reason === "steps" || budgetBack) {+ return "keep_going";+ }+ return resume.resumesAt ? null : "resume";+}++/** The same task, now waiting on the budget the account ran out of after+ * it paused, when "Keep going" was refused for it. */+export function pauseAfterRefusal(+ pause: TurnPause,+ window: string | null,+ resetsAt: string | null,+): TurnPause {+ if (window === "trial") {+ return { ...pause, reason: "trial", resets_at: null, steps: null };+ }+ return {+ ...pause,+ reason: window === "weekly" ? "weekly" : "daily",+ resets_at: resetsAt,+ steps: null,+ };+}++export type ContinueOutcome =+ | { kind: "running" }+ | { kind: "out_of_budget"; resetsAt: string | null }+ | { kind: "failed"; description: string };++export function continueOutcome(error: unknown): ContinueOutcome {+ const failure = apiFailureOf(error);+ if (failure?.status === 409 && failure.detail === "unsupported_connection") {+ return {+ kind: "failed",+ description:+ "This chat now runs on Microsoft 365 Copilot, which can't pick up a paused task. Switch its connection back to keep going.",+ };+ }+ // One turn per chat: the one already running is the one to follow.+ if (failure?.status === 409) return { kind: "running" };+ const limit =+ failure?.status === 429 ? parseProviderFailure(failure.detail) : null;+ if (limit?.kind === "usage_limit") {+ return {+ kind: "out_of_budget",+ resetsAt:+ limit.resetsAt !== null+ ? new Date(limit.resetsAt * 1000).toISOString()+ : null,+ };+ }+ if (failure?.status === 402) {+ return { kind: "failed", description: "Choose a plan to keep going." };+ }+ // The running-turn cap explains itself.+ if (failure?.status === 429 && typeof failure.detail === "string") {+ return { kind: "failed", description: failure.detail };+ }+ return { kind: "failed", description: "Try again in a moment." };+}++export type AtResetOutcome =+ | { kind: "budget_back" }+ | { kind: "failed"; title: string; description: string };++export function atResetOutcome(error: unknown): AtResetOutcome {+ const failure = apiFailureOf(error);+ if (failure?.status === 409 && failure.detail === "not_out_of_budget") {+ return { kind: "budget_back" };+ }+ if (failure?.status === 409 && failure.detail === "no_reset") {+ return {+ kind: "failed",+ title: "This allowance doesn't reset",+ description: "Upgrade to keep going.",+ };+ }+ return {+ kind: "failed",+ title:+ failure?.status === 503+ ? "Couldn't check your budget"+ : "Couldn't set the resume",+ description: "Try again in a moment.",+ };+}++interface ApiFailure {+ status: number;+ detail: unknown;+}++/** The status and FastAPI `detail` of a call the generated client rejected. */+function apiFailureOf(error: unknown): ApiFailure | null {+ if (!error || typeof error !== "object") return null;+ const { status, response } = error as {+ status?: unknown;+ response?: unknown;+ };+ if (typeof status !== "number") return null;+ const detail =+ response && typeof response === "object"+ ? (response as { detail?: unknown }).detail+ : undefined;+ return { status, detail };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useKeepGoing.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useKeepGoing.tsnew file mode 100644index 0000000000..5141554a14--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useKeepGoing.ts@@ -0,0 +1,54 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";++import {+ getGetV2GetCopilotUsageQueryKey,+ usePostV2ContinueSession,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";++import { useCopilotUIStore } from "../../../../store";+import { continueOutcome } from "./helpers";++interface Args {+ sessionId: string;+ /** Attach to the turn the server started. */+ onFollow: () => void;+ /** The account ran out of budget since the pause; when it next resets. */+ onOutOfBudget: (resetsAt: string | null) => void;+}++export function useKeepGoing({ sessionId, onFollow, onOutOfBudget }: Args) {+ const queryClient = useQueryClient();+ // The composer's model choice, as a message sent now would carry it.+ const model = useCopilotUIStore((state) => state.copilotLlmModel);+ const { mutateAsync, isPending } = usePostV2ContinueSession();++ async function keepGoing() {+ try {+ await mutateAsync({ sessionId, data: { model } });+ onFollow();+ } catch (error) {+ const outcome = continueOutcome(error);+ if (outcome.kind === "running") {+ onFollow();+ return;+ }+ if (outcome.kind === "out_of_budget") {+ void queryClient.invalidateQueries({+ queryKey: getGetV2GetCopilotUsageQueryKey(),+ });+ onOutOfBudget(outcome.resetsAt);+ return;+ }+ toast({+ title: "Couldn't pick this back up",+ description: outcome.description,+ variant: "destructive",+ });+ }+ }++ return { keepGoing, isContinuing: isPending };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useLivePausedCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useLivePausedCard.tsnew file mode 100644index 0000000000..9ad9548572--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useLivePausedCard.ts@@ -0,0 +1,104 @@+"use client";++import { useState } from "react";++import { useUsageActions } from "@/services/usageExperience/useUsageActions";++import type { TurnPause } from "../../../../turnPause";+import { useProviderLimitDialog } from "../../../ProviderLimitDialog/useProviderLimitDialog";+import {+ hasReset,+ isBudgetPause,+ neverResets,+ pauseBody,+ pauseTitle,+} from "../../helpers";+import {+ canContinueTask,+ pauseAfterRefusal,+ PLATFORM_BUDGET,+ primaryAction,+} from "./helpers";+import { useKeepGoing } from "./useKeepGoing";+import { useNow } from "./useNow";+import { useResumeAtReset } from "./useResumeAtReset";++interface Args {+ pause: TurnPause;+ sessionId: string;+ assistantName: string;+ onFollow: () => void;+}++export function useLivePausedCard({+ pause,+ sessionId,+ assistantName,+ onFollow,+}: Args) {+ const usage = useUsageActions();+ const { experience } = usage;+ // Set when "Keep going" was refused because the account ran out meanwhile.+ const [refusal, setRefusal] = useState<{ resetsAt: string | null }>();+ const [isBudgetBack, setIsBudgetBack] = useState(false);+ const shown = refusal+ ? pauseAfterRefusal(+ pause,+ experience.window,+ refusal.resetsAt ?? isoOrNull(experience.resetsAt),+ )+ : pause;+ const isBudget = isBudgetPause(shown);+ const waitsOnReset = isBudget && !neverResets(shown);+ // Once the budget is back the card's text stops changing.+ const now = useNow(+ waitsOnReset && !isBudgetBack && shown.resets_at+ ? Date.parse(shown.resets_at)+ : null,+ );+ const budgetBack = isBudget && (isBudgetBack || hasReset(shown, now));+ const keep = useKeepGoing({+ sessionId,+ onFollow,+ onOutOfBudget: (resetsAt) => {+ setRefusal({ resetsAt });+ setIsBudgetBack(false);+ },+ });+ const resume = useResumeAtReset({+ sessionId,+ enabled: waitsOnReset,+ onBudgetBack: () => setIsBudgetBack(true),+ });+ // Switching the chat's connection, then picking the task up on it.+ const chatGpt = useProviderLimitDialog({+ failure: isBudget ? PLATFORM_BUDGET : null,+ sessionId,+ onDismiss: () => void keep.keepGoing(),+ eligible: canContinueTask,+ });++ return {+ shown,+ now,+ title: pauseTitle(shown),+ body: pauseBody({ pause: shown, name: assistantName, budgetBack, now }),+ primary: primaryAction({ pause: shown, budgetBack, resume }),+ canStop: shown.reason === "task" || shown.reason === "steps",+ canUpgrade:+ (isBudget || shown.reason === "trial") &&+ usage.isBillingEnabled &&+ experience.targetTier !== null,+ chatGptName: isBudget ? (chatGpt.alternative?.display_name ?? null) : null,+ keep,+ resume,+ chatGpt,+ upgrade: usage.upgrade,+ isUpgradeDisabled: usage.offer.disabled,+ };+}++function isoOrNull(value: string | Date | null | undefined): string | null {+ const date = value ? new Date(value) : null;+ return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useNow.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useNow.tsnew file mode 100644index 0000000000..1cb8d6e7f2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useNow.ts@@ -0,0 +1,22 @@+"use client";++import { useEffect, useState } from "react";++const TICK_MS = 1000;++/** The time now, kept current until `until` (epoch ms) passes, so a countdown+ * on the card moves with the clock and stops once there is nothing left to+ * count. `null` never ticks. */+export function useNow(until: number | null) {+ const [now, setNow] = useState(Date.now);+ const isTicking = until !== null && now < until;++ useEffect(() => {+ if (!isTicking) return;+ setNow(Date.now());+ const timer = setInterval(() => setNow(Date.now()), TICK_MS);+ return () => clearInterval(timer);+ }, [isTicking]);++ return new Date(now);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useResumeAtReset.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useResumeAtReset.tsnew file mode 100644index 0000000000..014d54c55b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/LivePausedCard/useResumeAtReset.ts@@ -0,0 +1,81 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";++import {+ getGetV2ListTurnsAtBudgetResetQueryKey,+ useDeleteV2CancelTurnAtBudgetReset,+ useGetV2ListTurnsAtBudgetReset,+ usePostV2ScheduleTurnAtBudgetReset,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";++import { atResetOutcome } from "./helpers";++interface Args {+ sessionId: string;+ enabled: boolean;+ /** The budget refilled already, so there is nothing to wait for. */+ onBudgetBack: () => void;+}++export function useResumeAtReset({ sessionId, enabled, onBudgetBack }: Args) {+ const queryClient = useQueryClient();+ const jobs = useGetV2ListTurnsAtBudgetReset(sessionId, {+ query: {+ enabled,+ select: (response) => (response.status === 200 ? response.data.jobs : []),+ },+ });+ // Settles once the list shows the change, so the card never flashes the+ // state it just left.+ const refresh = {+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: getGetV2ListTurnsAtBudgetResetQueryKey(sessionId),+ }),+ };+ const schedule = usePostV2ScheduleTurnAtBudgetReset({ mutation: refresh });+ const cancel = useDeleteV2CancelTurnAtBudgetReset({ mutation: refresh });+ const resume = jobs.data?.find((job) => job.kind === "resume");++ async function resumeAtReset() {+ try {+ await schedule.mutateAsync({+ sessionId,+ data: { kind: "resume", message: null },+ });+ } catch (error) {+ const outcome = atResetOutcome(error);+ if (outcome.kind === "budget_back") {+ onBudgetBack();+ return;+ }+ toast({+ title: outcome.title,+ description: outcome.description,+ variant: "destructive",+ });+ }+ }++ async function cancelResume() {+ try {+ await cancel.mutateAsync({ sessionId, kind: "resume" });+ } catch {+ toast({+ title: "Couldn't cancel the resume",+ description: "Try again in a moment.",+ variant: "destructive",+ });+ }+ }++ return {+ resumesAt: resume ? new Date(resume.run_at) : null,+ resumeAtReset,+ cancelResume,+ isScheduling: schedule.isPending,+ isCancelling: cancel.isPending,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/PausedLine.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/PausedLine.tsxnew file mode 100644index 0000000000..b10d2bcb2b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/components/PausedLine.tsx@@ -0,0 +1,34 @@+import { PauseCircleIcon } from "@hugeicons/core-free-icons";++import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";++interface Props {+ title: string;+ /** What became of the pause, when that is known. */+ note: string | null;+}++export function PausedLine({ title, note }: Props) {+ return (+ <div+ role="note"+ aria-label={note ? `${title}. ${note}` : title}+ className="my-2 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-xl bg-zinc-50 px-3 py-2"+ >+ <Icon+ icon={PauseCircleIcon}+ size={14}+ className="shrink-0 text-zinc-400"+ />+ <Text variant="small" className="!text-zinc-600">+ {title}+ </Text>+ {note && (+ <Text variant="small" className="!text-zinc-400">+ {note}+ </Text>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/helpers.tsnew file mode 100644index 0000000000..fb8c2eaf75--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/helpers.ts@@ -0,0 +1,171 @@+import type { UIMessage } from "ai";++import { TURN_PAUSED_PART_TYPE, type TurnPause } from "../../turnPause";++/**+ * The pause the chat is sitting on: the last thing in it, with nothing drawn+ * after it. Once anything follows (a "Keep going" note, a resumed turn, the+ * user's next message) the pause is history and its card stops offering+ * ways back in. A card knows it is this pause by comparing its `data` to it+ * by reference, so the chat's message transforms must pass that object on.+ */+export function getCurrentPause(messages: readonly UIMessage[]): unknown {+ 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];+ if (part.type === TURN_PAUSED_PART_TYPE) {+ return (part as { data?: unknown }).data ?? null;+ }+ if (!drawsNothing(part)) return null;+ }+ return null;+}++function drawsNothing(part: UIMessage["parts"][number]): boolean {+ if (part.type === "step-start" || part.type.startsWith("data-")) return true;+ if (part.type === "text" || part.type === "reasoning") {+ return !part.text.trim();+ }+ return false;+}++type BudgetPause = TurnPause & { reason: "daily" | "weekly" };++export function isBudgetPause(pause: TurnPause): pause is BudgetPause {+ return pause.reason === "daily" || pause.reason === "weekly";+}++/** A budget pause with no reset time: the account has no plan, so its+ * allowance never refills on its own. */+export function neverResets(pause: TurnPause): boolean {+ return isBudgetPause(pause) && pause.resets_at === null;+}++/** The window the pause waited on has refilled since. */+export function hasReset(pause: TurnPause, now = new Date()): boolean {+ if (!isBudgetPause(pause) || !pause.resets_at) return false;+ return Date.parse(pause.resets_at) <= now.getTime();+}++const BUDGET: Record<"daily" | "weekly", string> = {+ daily: "today's budget",+ weekly: "this week's budget",+};++export function pauseTitle(pause: TurnPause): string {+ const lead = pause.started ? "Paused" : "Not started";+ // No plan behind it, so no window that will refill to name.+ if (neverResets(pause)) return `${lead} · out of AutoPilot budget`;+ if (isBudgetPause(pause)) return `${lead} · out of ${BUDGET[pause.reason]}`;+ if (pause.reason === "trial") return `${lead} · trial allowance used`;+ if (!pause.started) return lead;+ return pause.reason === "task"+ ? "Paused · this task reached its size limit"+ : "Paused · checking in after a long run";+}++interface BodyArgs {+ pause: TurnPause;+ name: string;+ /** The budget refilled after the pause, so there is nothing to wait for. */+ budgetBack?: boolean;+ now?: Date;+}++export function pauseBody({+ pause,+ name,+ budgetBack = false,+ now = new Date(),+}: BodyArgs): string {+ if (pause.reason === "steps" && pause.started) return stepsBody(pause, name);+ if (!pause.started) return notStartedBody(pause, name, budgetBack, now);+ const saved = pause.checkpoint_saved+ ? `${name} saved its progress above.`+ : `${name} was stopped before it could summarize its progress.`;+ if (!isBudgetPause(pause)) return saved;+ if (budgetBack) return `${saved} Your budget has reset.`;+ const reset = resetPhrase(pause.resets_at, now);+ return reset ? `${saved} Your budget resets ${reset}.` : saved;+}++function stepsBody(pause: TurnPause, name: string): string {+ const done =+ pause.steps !== null+ ? `has taken ${pause.steps.toLocaleString()} steps on this`+ : "has been at this a while";+ return pause.checkpoint_saved+ ? `${name} ${done} and summarized its progress above.`+ : `${name} ${done} and was stopped before it could summarize its progress.`;+}++function notStartedBody(+ pause: TurnPause,+ name: string,+ budgetBack: boolean,+ now: Date,+): string {+ if (pause.reason === "trial") {+ return `${name} didn't start this because you're out of your trial allowance.`;+ }+ if (!isBudgetPause(pause)) return `${name} didn't start this.`;+ if (neverResets(pause)) {+ return `${name} didn't start this because you're out of AutoPilot budget.`;+ }+ const budget = BUDGET[pause.reason];+ if (budgetBack) {+ return `${name} didn't start this because you were out of ${budget}. It has reset since.`;+ }+ const reset = resetPhrase(pause.resets_at, now);+ const lead = `${name} didn't start this because you're out of ${budget}.`;+ return reset ? `${lead} It resets ${reset}.` : lead;+}++/** "at 1:00 AM, in 4 h 12 min", or nothing when the time is unknown. */+function resetPhrase(resetsAt: string | null, now: Date): string | null {+ if (!resetsAt) return null;+ const date = new Date(resetsAt);+ if (!Number.isFinite(date.getTime())) return null;+ return `${resetAt(date, now)}, ${resetIn(date, now)}`;+}++/** "Resume at 1:00 AM", or a plain "Resume at reset" when the time is unknown. */+export function resumeLabel(resetsAt: string | null, now = new Date()) {+ const date = resetsAt ? new Date(resetsAt) : null;+ return date && Number.isFinite(date.getTime())+ ? `Resume ${resetAt(date, now)}`+ : "Resume at reset";+}++const DAY_MS = 24 * 60 * 60 * 1000;++/** "at 1:00 AM" within a day, "Monday at 1:00 AM" within a week. */+export function resetAt(date: Date, now = new Date()): string {+ const time = date.toLocaleTimeString(undefined, {+ hour: "numeric",+ minute: "2-digit",+ });+ const ms = date.getTime() - now.getTime();+ if (ms < DAY_MS) return `at ${time}`;+ const day =+ ms < 7 * DAY_MS+ ? date.toLocaleDateString(undefined, { weekday: "long" })+ : date.toLocaleDateString(undefined, { month: "short", day: "numeric" });+ return `${day} at ${time}`;+}++/** "in 4 h 12 min", "in 45 min", "in 2 days". */+export function resetIn(date: Date, now = new Date()): string {+ const ms = date.getTime() - now.getTime();+ const minutes = Math.max(1, Math.ceil(ms / 60_000));+ if (minutes < 60) return `in ${minutes} min`;+ // resetAt's cut-off: a time it names without the day never reads "in 1 day".+ if (ms < DAY_MS) {+ const hours = Math.floor(minutes / 60);+ const rest = minutes % 60;+ return rest ? `in ${hours} h ${rest} min` : `in ${hours} h`;+ }+ const days = Math.round(minutes / (24 * 60));+ return `in ${days} ${days === 1 ? "day" : "days"}`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/stoppedPauses.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/stoppedPauses.tsnew file mode 100644index 0000000000..19efb76052--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/stoppedPauses.ts@@ -0,0 +1,65 @@+import { Key, storage } from "@/services/storage/local-storage";++import type { TurnPause } from "../../turnPause";++const MAX_STOPPED = 50;++/** "Stop here" is the user's call alone, so it lives on this device only. */+export function isPauseStopped(key: string): boolean {+ return readStopped().includes(key);+}++export function rememberStoppedPause(key: string) {+ const kept = readStopped()+ .filter((stopped) => stopped !== key)+ .slice(-(MAX_STOPPED - 1));+ storage.set(Key.COPILOT_STOPPED_PAUSES, JSON.stringify([...kept, key]));+}++function readStopped(): string[] {+ try {+ const value: unknown = JSON.parse(+ storage.get(Key.COPILOT_STOPPED_PAUSES) ?? "[]",+ );+ return Array.isArray(value)+ ? value.filter((key): key is string => typeof key === "string")+ : [];+ } catch {+ return [];+ }+}++// A stop made on a pause still streaming in, which has no stored row yet to+// keep it under: held per session until that row arrives.+const pendingStops = new Map<string, string>();++export function holdPendingStop(sessionId: string, pause: TurnPause) {+ pendingStops.set(sessionId, pauseFingerprint(pause));+}++export function isPendingStop(sessionId: string, pause: TurnPause): boolean {+ return pendingStops.get(sessionId) === pauseFingerprint(pause);+}++/** The pause's stored row arrived: it keeps the stop from now on. */+export function settlePendingStop(sessionId: string, storageKey: string) {+ rememberStoppedPause(storageKey);+ pendingStops.delete(sessionId);+}++export function dropPendingStop(sessionId: string) {+ pendingStops.delete(sessionId);+}++// The same pause live and stored. The API client hands a stored reset over+// as a Date, whose ISO form differs from the wire's, so it compares as an+// instant.+function pauseFingerprint(pause: TurnPause): string {+ return JSON.stringify([+ pause.reason,+ pause.resets_at === null ? null : Date.parse(pause.resets_at),+ pause.steps,+ pause.checkpoint_saved,+ pause.started,+ ]);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/useStopHere.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/useStopHere.tsnew file mode 100644index 0000000000..17c3e5532a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/useStopHere.ts@@ -0,0 +1,64 @@+"use client";++import { useEffect, useState } from "react";++import type { TurnPause } from "../../turnPause";+import {+ dropPendingStop,+ holdPendingStop,+ isPauseStopped,+ isPendingStop,+ rememberStoppedPause,+ settlePendingStop,+} from "./stoppedPauses";++interface Args {+ sessionId: string | null;+ pause: TurnPause | null;+ pauseKey: string;+ /** The key is the pause's stored row's, so it outlives a reload. */+ isStoredRow: boolean;+ isCurrent: boolean;+}++/**+ * "Stop here", kept on this device under the pause's stored row. A pause+ * still streaming in has no row yet, so a stop made then is held for the+ * session and handed to the row when it replaces the live part.+ */+export function useStopHere({+ sessionId,+ pause,+ pauseKey,+ isStoredRow,+ isCurrent,+}: Args) {+ const storageKey = sessionId ? `${sessionId}:${pauseKey}` : null;+ const hasPendingStop = Boolean(+ sessionId && pause && isCurrent && isPendingStop(sessionId, pause),+ );+ const [isStopped, setIsStopped] = useState(+ () => (storageKey !== null && isPauseStopped(storageKey)) || hasPendingStop,+ );+ const holdsPendingStop = isStopped && !isStoredRow;++ useEffect(() => {+ if (hasPendingStop && isStoredRow && sessionId && storageKey) {+ settlePendingStop(sessionId, storageKey);+ }+ }, [hasPendingStop, isStoredRow, sessionId, storageKey]);++ // The chat moved past the live pause before its row arrived: the stop+ // belongs to no later pause, however alike.+ useEffect(() => {+ if (holdsPendingStop && !isCurrent && sessionId) dropPendingStop(sessionId);+ }, [holdsPendingStop, isCurrent, sessionId]);++ function stop() {+ if (isStoredRow && storageKey) rememberStoppedPause(storageKey);+ else if (sessionId && pause) holdPendingStop(sessionId, pause);+ setIsStopped(true);+ }++ return { isStopped, stop };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/useTurnPausedCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/useTurnPausedCard.tsnew file mode 100644index 0000000000..eb006d4dd5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/TurnPausedCard/useTurnPausedCard.ts@@ -0,0 +1,55 @@+"use client";++import { useContext, useState } from "react";++import { parseTurnPause } from "../../turnPause";+import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopilotChatActions";+import { CurrentPauseContext } from "./CurrentPauseContext";+import { useStopHere } from "./useStopHere";++interface Args {+ data: unknown;+ /** Stable for the pause across reloads when it is its stored row's. */+ pauseKey: string;+ /** The pause is a stored row, so its key outlives a reload. */+ isStoredRow: boolean;+}++export function useTurnPausedCard({ data, pauseKey, isStoredRow }: Args) {+ const actions = useContext(CopilotChatActionsContext);+ const current = useContext(CurrentPauseContext);+ const pause = parseTurnPause(data);+ const sessionId = actions?.sessionId ?? null;+ const [isPickedUp, setIsPickedUp] = useState(false);+ const isTracked = current !== undefined;+ const isCurrent = data != null && data === current;+ const { isStopped, stop } = useStopHere({+ sessionId,+ pause,+ pauseKey,+ isStoredRow,+ isCurrent,+ });+ // Acting needs a chat to act on and a way to follow the turn the server+ // starts; the share viewer and the side panels have neither.+ const canAct = Boolean(sessionId && actions?.onBackendTurn);++ function followTurn() {+ setIsPickedUp(true);+ actions?.onBackendTurn?.();+ }++ return {+ pause,+ sessionId: canAct ? sessionId : null,+ assistantName: actions?.assistantName ?? "Otto",+ isLive: isCurrent && canAct && !isStopped && !isPickedUp,+ note: isStopped+ ? "Stopped here"+ : isPickedUp || (isTracked && !isCurrent)+ ? "Picked back up"+ : null,+ stop,+ followTurn,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.tsindex 8f823d0ebb..c339be8b3a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts@@ -5,6 +5,7 @@ import type { ChatStatus, UIMessage } from "ai";import { deleteV2DisconnectSessionStream } from "@/app/api/__generated__/endpoints/chat/chat";import { TOOL_PART_PREFIX } from "./components/JobStatsBar/constants";import { parseSpecialMarkers } from "./helpers/messageMarkers";+import { TURN_PAUSED_PART_TYPE } from "./turnPause";export const ORIGINAL_TITLE = "AutoGPT";@@ -115,8 +116,9 @@ export function hasActiveBackendStream(result: { data?: unknown }): boolean {/*** Whether the trailing assistant message has at least one part the UI* would visibly render: text with non-empty content, reasoning with- * non-empty content, or any tool part (tool cards render regardless of- * state). Used to gate the resume-snapshot discard — the replay may stream+ * non-empty content, any tool part (tool cards render regardless of+ * state), or a Paused card — a turn refused before it ran streams nothing+ * else. Used to gate the resume-snapshot discard — the replay may stream* empty reasoning-start / step-start chunks for minutes before any* rendered content (e.g. Perplexity deep research), and we do not want to* drop the pre-replay snapshot until the user actually sees something.@@ -128,6 +130,7 @@ export function hasVisibleAssistantContent(messages: UIMessage[]): boolean {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_PART_PREFIX)) return true;+ if (part.type === TURN_PAUSED_PART_TYPE) return true;return false;});}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.tsindex e7adb678f4..e4790881e0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts@@ -692,3 +692,60 @@ describe("the [Attached files] block", () => {]);});});++describe("a pause marker row", () => {+ const MARKER =+ "[__COPILOT_SYSTEM_e3b0__] Paused: this task is out of today's budget.";+ const PAUSE = {+ reason: "daily",+ resets_at: "2026-10-12T06:00:00.000Z",+ steps: null,+ checkpoint_saved: true,+ started: true,+ };++ it("becomes the Paused card's part, riding the bubble it merges into", () => {+ const { messages } = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "user", content: "Do the thing.", sequence: 0 },+ { role: "assistant", content: "Saved where I got to.", sequence: 1 },+ {+ role: "assistant",+ content: MARKER,+ sequence: 2,+ // The API client hands dates over as Date objects.+ metadata: {+ turn_paused: { ...PAUSE, resets_at: new Date(PAUSE.resets_at) },+ },+ },+ ],+ { isComplete: true },+ );++ expect(messages).toHaveLength(2);+ expect(messages[1].parts).toEqual([+ { type: "text", text: "Saved where I got to.", state: "done" },+ { type: "data-turn-paused", id: "seq-2", data: PAUSE },+ ]);+ });++ it("stays a system note when its pause can't be read", () => {+ const { messages } = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ {+ role: "assistant",+ content: MARKER,+ sequence: 0,+ metadata: { turn_paused: { reason: "lunch" } },+ },+ ],+ { isComplete: true },+ );++ expect(messages[0].parts).toEqual([+ { type: "text", text: MARKER, state: "done" },+ ]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/renderTurnLog.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/renderTurnLog.test.tsindex 129416db7a..9744cffd08 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/renderTurnLog.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/renderTurnLog.test.ts@@ -150,6 +150,45 @@ describe("rendering a turn log", () => {]);});+ it("draws a pause as the Paused card, exactly as a reload of its marker row does", () => {+ const pause = {+ reason: "daily",+ resets_at: "2026-10-12T06:00:00Z",+ steps: null,+ checkpoint_saved: true,+ started: true,+ };+ const log = fold([+ { type: "text-start", id: "a" },+ { type: "text-delta", id: "a", delta: "Saved where I got to." },+ { type: "text-end", id: "a" },+ { type: "data-turn-paused", data: pause },+ { type: "finish" },+ { type: "data-checkpoint", data: { rows: 2, sequence: 4, digest: "x" } },+ ]);+ const reloaded = convertChatSessionMessagesToUiMessages(+ "s",+ [+ { role: "assistant", content: "Saved where I got to.", sequence: 4 },+ {+ role: "assistant",+ content:+ "[__COPILOT_SYSTEM_e3b0__] Paused: this task is out of today's budget.",+ sequence: 5,+ metadata: { turn_paused: pause },+ },+ ],+ { isComplete: true },+ ).messages;++ const [live] = render(log);+ expect(live.parts).toEqual([+ { type: "text", text: "Saved where I got to.", state: "done" },+ { type: "data-turn-paused", id: "seq-5", data: pause },+ ]);+ expect(live.parts).toEqual(reloaded[0].parts);+ });+it("returns an unchanged bubble as the same object, so React skips it", () => {const renderer = createTurnLogRenderer((id) => id);const before = fold([diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/stripReplayPrefix.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/stripReplayPrefix.test.tsindex 0da83c2339..84765634d6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/stripReplayPrefix.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/stripReplayPrefix.test.ts@@ -180,6 +180,58 @@ describe("stripReplayPrefix", () => {expect(stripReplayPrefix([])).toEqual([]);});+ it("drops the copy of the bubble before it that a resumed turn opens with, cards included", () => {+ // `useChat` seeds a GET-resumed turn from the assistant message the list+ // ends on, so the turn's message starts with all of that bubble's parts.+ const paused = {+ id: "a1",+ role: "assistant",+ parts: [+ { type: "text", text: "Halfway there.", state: "done" },+ { type: "data-turn-paused", data: { reason: "steps", steps: 450 } },+ { type: "text", text: "Keep going.", state: "done" },+ { type: "data-status", data: { message: "Picking it back up…" } },+ ],+ } as UIMessage;+ const continued = {+ id: "a2",+ role: "assistant",+ parts: [+ ...structuredClone(paused.parts),+ { type: "step-start" },+ { type: "text", text: "Back on it.", state: "streaming" },+ ],+ } as UIMessage;++ const result = stripReplayPrefix([user("u1", "go"), paused, continued]);++ expect(result.map((m) => m.id)).toEqual(["u1", "a1", "a2"]);+ expect(result[1]).toBe(paused);+ expect(result[2].parts).toEqual([+ { type: "step-start" },+ { type: "text", text: "Back on it.", state: "streaming" },+ ]);+ });++ it("keeps a bubble that only resembles the one before it", () => {+ const next = {+ id: "a2",+ role: "assistant",+ parts: [+ { type: "data-turn-paused", data: { reason: "task" } },+ { type: "text", text: "Next.", state: "done" },+ ],+ } as UIMessage;++ const result = stripReplayPrefix([+ user("u1", "go"),+ assistant("a1", "Saved."),+ next,+ ]);++ expect(result[2]).toBe(next);+ });+it("handles the longest matching earlier assistant as the strip anchor", () => {// a3 matches a2's full text (which is longer than a1's). Should strip a2's// length, not a1's.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.tsindex afd1ac70b3..bf3c12137c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts@@ -1,6 +1,11 @@import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpoints/workspace/workspace";import type { FileUIPart, UIMessage, UIDataTypes, UITools } from "ai";import type { LogRow, OverlayPart, TurnLog } from "../stream/turnLog";+import {+ TURN_PAUSED_PART_TYPE,+ turnPauseOfMetadata,+ type TurnPause,+} from "../turnPause";import { toolDisplayName } from "./toolDisplay";import {WORKSPACE_FOLDER_PART_TYPE,@@ -556,6 +561,12 @@ interface RowPartsContext {}function buildRowParts(msg: SessionChatMessage, ctx: RowPartsContext) {+ // A pause marker draws the Paused card. The pause rides on the part rather+ // than the message, because merged assistant bubbles drop row metadata.+ const pause =+ msg.role === "assistant" ? turnPauseOfMetadata(msg.metadata) : null;+ if (pause) return [pausePart(msg, pause)];+const textState = ctx.streaming ? "streaming" : "done";const parts: UiPart[] = [];@@ -592,6 +603,17 @@ function buildRowParts(msg: SessionChatMessage, ctx: RowPartsContext) {return parts;}+// Keyed by the row, so whatever the card remembers about itself (a "Stop+// here") outlives the bubble id, which moves as later rows merge in.+function pausePart(msg: SessionChatMessage, pause: TurnPause): UiPart {+ const id = msg.sequence != null ? `seq-${msg.sequence}` : msg.id;+ return {+ type: TURN_PAUSED_PART_TYPE,+ ...(id ? { id } : {}),+ data: pause,+ } as UiPart;+}+function toolCallPart(rawToolCall: unknown, ctx: RowPartsContext) {if (!rawToolCall || typeof rawToolCall !== "object") return null;const toolCall = rawToolCall as {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/stripReplayPrefix.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/stripReplayPrefix.tsindex 260b293183..721ee4bb0b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/stripReplayPrefix.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/stripReplayPrefix.ts@@ -29,7 +29,7 @@ import { deduplicateMessages } from "../helpers";* cases we see.*/export function stripReplayPrefix(raw: UIMessage[]): UIMessage[] {- const deduped = deduplicateMessages(raw);+ const deduped = withoutSeededCopies(deduplicateMessages(raw));const texts = deduped.map(concatText);const out: UIMessage[] = [];@@ -52,6 +52,44 @@ export function stripReplayPrefix(raw: UIMessage[]): UIMessage[] {return out;}+/**+ * Drop the copy a resumed turn's message opens with.+ *+ * On a GET-resume `useChat` seeds the replayed turn from the assistant+ * message the list ends on, so that turn's message starts with every part of+ * the bubble before it, cards and tool calls as well as text, ahead of its+ * own. The text alone is caught below as a replay; the rest would draw a+ * second time. Only an exact copy of the whole bubble right before it goes.+ */+function withoutSeededCopies(messages: UIMessage[]): UIMessage[] {+ return messages.flatMap((message, i) => {+ const previous = messages[i - 1];+ if (message.role !== "assistant" || previous?.role !== "assistant") {+ return [message];+ }+ const seeded = previous.parts;+ if (seeded.length === 0 || seeded.length > message.parts.length) {+ return [message];+ }+ const isSeeded = seeded.every(+ (part, k) => partKey(part) === partKey(message.parts[k]),+ );+ if (!isSeeded) return [message];+ const own = message.parts.slice(seeded.length);+ return own.length > 0 ? [{ ...message, parts: own }] : [];+ });+}++// Cheap identity for a part: never serialises a tool's output, which can be+// large and this runs on every streamed delta.+function partKey(part: UIMessage["parts"][number]): string {+ if ("text" in part && typeof part.text === "string") {+ return `${part.type}:${part.text}`;+ }+ if ("toolCallId" in part) return `${part.type}:${part.toolCallId}`;+ return JSON.stringify(part);+}+function concatText(msg: UIMessage): string {return (msg.parts ?? []).map((p) => ("text" in p && typeof p.text === "string" ? p.text : ""))diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.tsindex 4f9191f990..8eec553be4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.ts@@ -83,10 +83,11 @@ export function parseProviderFailurePart(dataPart: {export const PROVIDER_FAILURE_KEY = "provider_failure";// Server-written prefixes that mark a row as a failure card rather than a-// reply. Kept in step with COPILOT_ERROR_PREFIX in the backend's constants.+// reply. Kept in step with COPILOT_ERROR_PREFIX and+// COPILOT_RETRYABLE_ERROR_PREFIX in the backend's constants.const ERROR_MARKER_PREFIXES = ["[__COPILOT_ERROR_f7a1__]",- "[__COPILOT_RETRYABLE_ERROR_f7a1__]",+ "[__COPILOT_RETRYABLE_ERROR_a9c2__]",];function isErrorMarker(row: { role?: unknown; content?: unknown }): boolean {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnConverter.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnConverter.test.tsindex de0a488b44..05a4f51a09 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnConverter.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnConverter.test.ts@@ -265,6 +265,54 @@ describe("the converter table", () => {expect(log.rows).toHaveLength(1);});+ it.each([+ [+ { reason: "daily", started: true },+ "Paused: this task is out of today's budget.",+ ],+ [+ { reason: "weekly", started: false },+ "Not started: out of this week's budget.",+ ],+ [{ reason: "steps", steps: 450 }, "Paused: checking in after a long run."],+ ])(+ "a pause %j appends the marker row the server stores, carrying it",+ (pause, summary) => {+ const log = fold([+ ...text("a", "Checkpoint."),+ { type: "data-turn-paused", data: pause },+ { type: "finish" },+ ]);+ expect(rowsOf(log)).toEqual([+ { role: "assistant", content: "Checkpoint.", calls: [] },+ {+ role: "assistant",+ content: `[__COPILOT_SYSTEM_e3b0__] ${summary}`,+ calls: [],+ },+ ]);+ expect(log.rows[1].metadata).toEqual({+ turn_paused: expect.objectContaining(pause),+ });+ expect(log.overlay).toEqual([]);+ expect(log.status).toBe("finished");+ },+ );++ it("a pause after a marker adds nothing, and an unknown one is reported", () => {+ const afterError = fold([+ { type: "error", errorText: "Boom" },+ { type: "data-turn-paused", data: { reason: "daily" } },+ ]);+ expect(afterError.rows).toHaveLength(1);++ const unknown = fold([+ { type: "data-turn-paused", data: { reason: "lunch" } },+ ]);+ expect(unknown.rows).toEqual([]);+ expect(reasons(unknown)).toEqual(["data-turn-paused: unknown pause"]);+ });+it("finish closes the turn and nothing else", () => {const log = fold([...call("c1"), { type: "finish" }]);expect(log.status).toBe("finished");diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnConverter.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnConverter.tsindex 5aa738e420..b99ad3030e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnConverter.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnConverter.ts@@ -1,8 +1,10 @@+import { parseTurnPause, TURN_PAUSED_PART_TYPE } from "../turnPause";import {addToolCall,addToolResult,appendDrainedUserRows,appendErrorMarker,+ appendPauseMarker,appendReasoning,appendText,canonicalRows,@@ -109,6 +111,14 @@ function applyChunk(log: TurnLog, entryId: string, chunk: WireChunk): TurnLog {...addOverlay(log, entryId, chunk),providerFailure: record(chunk.data),};+ // A row, not an overlay: the server stores the pause as a marker row, and+ // the card renders from that row live and on reload alike.+ case TURN_PAUSED_PART_TYPE: {+ const pause = parseTurnPause(chunk.data);+ return pause+ ? appendPauseMarker(log, entryId, pause)+ : protocolError(log, entryId, chunk.type, "unknown pause");+ }default:if (chunk.type.startsWith("data-"))return addOverlay(log, entryId, chunk);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnLog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnLog.tsindex ecc05e4f6b..276502fe5f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnLog.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnLog.ts@@ -7,6 +7,8 @@* turns the replay-equivalence test red.*/+import { TURN_PAUSE_KEY, turnPauseSummary, type TurnPause } from "../turnPause";+export type RowRole = "assistant" | "reasoning" | "tool" | "user";export interface LogToolCall {@@ -257,6 +259,26 @@ export function appendDrainedUserRows(return rows.reduce(pushRow, log);}+/**+ * Row rule 9: a pause becomes a marker row carrying it, unless one already+ * ends the turn (`append_pause_marker`).+ */+export function appendPauseMarker(+ log: TurnLog,+ entryId: string,+ pause: TurnPause,+) {+ const last = log.rows[log.rows.length - 1];+ if (last && isMarker(last)) return log;+ return pushRow(log, {+ ...assistantRow(+ `pause:${entryId}`,+ `${COPILOT_SYSTEM_PREFIX} ${turnPauseSummary(pause)}`,+ ),+ metadata: { [TURN_PAUSE_KEY]: pause },+ });+}+/*** The inverse of the row rules at a checkpoint: the persisted rows of a turn* seed a log that the stream tail after the checkpoint continues. At adiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/turnPause.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/turnPause.tsnew file mode 100644index 0000000000..7b6250d9e4--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/turnPause.ts@@ -0,0 +1,98 @@+/**+ * Why a turn stopped at a limit instead of failing.+ *+ * A turn that runs out of budget or steps now lands on purpose: the agent+ * writes a checkpoint and the chat shows a Paused card offering the ways to+ * pick the task back up. The payload arrives live as a `data-turn-paused`+ * part and is stored on a marker row, so a reload rebuilds the same card. One+ * parser for both, the way `providerFailure.ts` reads `data-provider-failure`.+ */++export const TURN_PAUSED_PART_TYPE = "data-turn-paused";++/** The key the backend stores the pause under on a marker row. */+export const TURN_PAUSE_KEY = "turn_paused";++export type TurnPauseReason = "daily" | "weekly" | "trial" | "task" | "steps";++export interface TurnPause {+ reason: TurnPauseReason;+ /** When the limiting window refills; set for daily and weekly pauses. */+ resets_at: string | null;+ /** Model calls the turn made; set for step check-ins. */+ steps: number | null;+ /** False when the turn was stopped before it could write its checkpoint. */+ checkpoint_saved: boolean;+ /** False when the turn was refused before it ran at all. */+ started: boolean;+}++const REASONS = new Set<string>(["daily", "weekly", "trial", "task", "steps"]);++/** The pause, from the stream part's data or the marker row's metadata. */+export function parseTurnPause(value: unknown): TurnPause | null {+ if (!value || typeof value !== "object") return null;+ const data = value as Record<string, unknown>;+ if (typeof data.reason !== "string" || !REASONS.has(data.reason)) {+ return null;+ }+ return {+ reason: data.reason as TurnPauseReason,+ resets_at: isoOrNull(data.resets_at),+ steps:+ typeof data.steps === "number" && Number.isFinite(data.steps)+ ? data.steps+ : null,+ // The backend model defaults both to true.+ checkpoint_saved: data.checkpoint_saved !== false,+ started: data.started !== false,+ };+}++export function parseTurnPausePart(part: {+ type: string;+ data?: unknown;+}): TurnPause | null {+ if (part.type !== TURN_PAUSED_PART_TYPE) return null;+ return parseTurnPause(part.data);+}++/** The pause a stored row records, if the row is a pause marker. */+export function turnPauseOfMetadata(metadata: unknown): TurnPause | null {+ if (!metadata || typeof metadata !== "object") return null;+ return parseTurnPause((metadata as Record<string, unknown>)[TURN_PAUSE_KEY]);+}++// Kept in step with `_SUMMARIES` / `_NOT_STARTED` in the backend's+// `copilot/turn_pause.py`: the marker row's text is part of the checkpoint+// digest, so the stream fold has to write the same words the server does.+const SUMMARIES: Record<TurnPauseReason, string> = {+ daily: "Paused: this task is out of today's budget.",+ weekly: "Paused: this task is out of this week's budget.",+ trial: "Paused: the trial allowance is used up.",+ task: "Paused: this task reached its size limit.",+ steps: "Paused: checking in after a long run.",+};++const NOT_STARTED: Record<TurnPauseReason, string> = {+ daily: "Not started: out of today's budget.",+ weekly: "Not started: out of this week's budget.",+ trial: "Not started: the trial allowance is used up.",+ task: "Not started.",+ steps: "Not started.",+};++/** The system note the marker row carries for clients that predate the card. */+export function turnPauseSummary(pause: TurnPause): string {+ return pause.started ? SUMMARIES[pause.reason] : NOT_STARTED[pause.reason];+}++// The API client turns ISO strings into Dates on the way in, so a stored row+// can carry either.+function isoOrNull(value: unknown): string | null {+ if (typeof value === "string") return value;+ if (value instanceof Date && Number.isFinite(value.getTime())) {+ return value.toISOString();+ }+ return null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex 01cd276444..d82d20b7b8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -186,6 +186,7 @@ export function useCopilotPage({sessionAuthProvider: sessionLlmAuthProvider,sessionCredentialId: sessionLlmCredentialId,activeTurnStartMessageId,+ activeTurnStartedAt: activeStreamStartedAt,hasActiveStream,refetchSession,// Sent whenever the picker can set it. The tier control is not behinddiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.tsindex ba147a4486..c1a9a51f92 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotRuntimeStream.ts@@ -232,7 +232,7 @@ export function useCopilotRuntimeStream({useEffect(() => {if (!sessionId || !rawSessionMessages?.length) return;- const historical = latestProviderFailure(+ const latest = latestProviderFailure(rawSessionMessages,sessionAuthProvider? {@@ -241,6 +241,10 @@ export function useCopilotRuntimeStream({}: null,);+ // The dialog answers a spent quota, as on the live path. Reopening it for+ // an expired login or a refused prompt would tell the user they hit a+ // limit they never hit.+ const historical = latest?.kind === "usage_limit" ? latest : null;const dismissed = dismissedProviderFailureRef.current;if (historical &&diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex 8b9fe22c72..84c435639b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -94,6 +94,9 @@ interface UseCopilotStreamArgs {/** Id of the first hydrated message of the turn the backend is still* running — the point the GET-resume replay starts from. */activeTurnStartMessageId?: string | null;+ /** ``active_stream.started_at`` of that turn. Known with no start message+ * above, it means the turn has persisted nothing yet. */+ activeTurnStartedAt?: string | null;hasActiveStream: boolean;refetchSession: () => Promise<{ data?: unknown }>;/** Model tier override. `undefined` = let backend decide. */@@ -108,6 +111,7 @@ export function useCopilotStream({sessionAuthProvider = null,sessionCredentialId = null,activeTurnStartMessageId = null,+ activeTurnStartedAt = null,hasActiveStream,refetchSession,copilotModel,@@ -463,6 +467,19 @@ export function useCopilotStream({// backend) cannot redraw it. When the hint does carry the text, the// transcript draws the bubble at the drain point and drops the// matching fallback row (`splitMessagesAtDrainHints`).+ const last = prev[prev.length - 1];+ // When the running turn's start is known and no hydrated row falls at+ // or after it, nothing of that turn is persisted yet — a turn started+ // by Keep going or a resume at the reset saves its note row before the+ // turn opens. Every hydrated row then belongs to earlier turns and the+ // replay only appends, so none is cut; only a partial this mount+ // streamed itself goes, because the replay redraws it.+ if (activeTurnStartedAt !== null && activeTurnStartMessageId === null) {+ return hasInProgressAssistantParts(last) &&+ extractDbSequence(last) === null+ ? prev.slice(0, -1)+ : prev;+ }const lastUserIndex = prev.findLastIndex((m) => m.role === "user");const userCut = lastUserIndex === -1 ? -1 : lastUserIndex + 1;const activeTurnIndex = activeTurnStartMessageId@@ -479,7 +496,6 @@ export function useCopilotStream({.map(asMidTurnFallbackRow);return [...prev.slice(0, cutIndex), ...drainedFollowUps];}- const last = prev[prev.length - 1];return hasInProgressAssistantParts(last) ? prev.slice(0, -1) : prev;});resumeStream();@@ -580,7 +596,7 @@ export function useCopilotStream({useEffect(() => {if (!sessionId || !rawSessionMessages?.length) return;- const historical = latestProviderFailure(+ const latest = latestProviderFailure(rawSessionMessages,sessionAuthProvider? {@@ -589,6 +605,10 @@ export function useCopilotStream({}: null,);+ // The dialog answers a spent quota, as on the live path. Reopening it for+ // an expired login or a refused prompt would tell the user they hit a+ // limit they never hit.+ const historical = latest?.kind === "usage_limit" ? latest : null;const dismissed = dismissedProviderFailureRef.current;if (historical &&diff --git a/autogpt_platform/frontend/src/services/storage/local-storage.ts b/autogpt_platform/frontend/src/services/storage/local-storage.tsindex a46efd74d9..428cc0d2ac 100644--- a/autogpt_platform/frontend/src/services/storage/local-storage.ts+++ b/autogpt_platform/frontend/src/services/storage/local-storage.ts@@ -23,6 +23,7 @@ export enum Key {COPILOT_MODE = "copilot-mode",COPILOT_MODEL = "copilot-model",COPILOT_COMPLETED_SESSIONS = "copilot-completed-sessions",+ COPILOT_STOPPED_PAUSES = "copilot-stopped-pauses",PUSH_SUBSCRIPTION_REGISTERED = "push-subscription-registered",COPILOT_DRY_RUN = "copilot-dry-run",COPILOT_VOICE_SILENCE_TIMEOUT = "copilot-voice-silence-timeout",