AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(platform/copilot): a message sent from a stale tab during another tab's turn shows as a queued follow-up (#15402)
Reinier van der Leer7dce0d8ee4c0
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 2d845b09c6..680098da33 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -98,6 +98,7 @@ from backend.copilot.response_model import (StreamError,StreamFinish,StreamFinishStep,+ StreamFollowUpQueued,StreamHeartbeat,StreamStart,StreamStartStep,@@ -1676,7 +1677,9 @@ def _ui_message_stream_headers() -> dict[str, str]:}-def _empty_ui_message_stream_response() -> StreamingResponse:+def _empty_ui_message_stream_response(+ follow_up_queued: bool = False,+) -> StreamingResponse:# Stable placeholder messageId for the empty queued-mid-turn stream.# Real turns generate per-message UUIDs via the executor; this stream# has no message to attach to, but the AI SDK parser still requires a@@ -1692,6 +1695,8 @@ def _empty_ui_message_stream_response() -> StreamingResponse:# full empty pair so the contract stays correct.yield StreamStart(messageId=message_id).to_sse()yield StreamStartStep().to_sse()+ if follow_up_queued:+ yield StreamFollowUpQueued().to_sse()yield StreamFinishStep().to_sse()yield StreamFinish().to_sse()yield "data: [DONE]\n\n"@@ -1868,7 +1873,7 @@ async def stream_chat_post(folder_ids=request.folder_ids,expert_id=session.expert_id,)- return _empty_ui_message_stream_response()+ return _empty_ui_message_stream_response(follow_up_queued=True)except HTTPException as exc:if exc.status_code != 409:raisediff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 33ba6a7c45..50a71c6a4c 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -597,6 +597,39 @@ def test_stream_chat_does_not_queue_kickoff_behind_an_unrelated_turn(mocks.enqueue.assert_not_awaited()+def test_stream_chat_marks_a_send_queued_behind_a_running_turn(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocker.patch(+ "backend.api.features.chat.routes.is_turn_in_flight",+ new_callable=AsyncMock,+ return_value=True,+ )+ queue_pending = mocker.patch(+ "backend.api.features.chat.routes.queue_pending_for_http",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/sessions/sess-1/stream", json={"message": "And example.org?"}+ )++ assert response.status_code == 200+ queue_pending.assert_awaited_once()+ mocks.enqueue.assert_not_awaited()+ assert '"type": "data-follow-up-queued"' in response.text+++async def test_other_empty_streams_carry_no_follow_up_marker() -> None:+ # The queued-at-cap and kicked-off-already streams are empty too.+ response = chat_routes._empty_ui_message_stream_response()+ body = "".join([str(chunk) async for chunk in response.body_iterator])++ assert "data: [DONE]" in body+ assert "data-follow-up-queued" not in body++def test_stream_chat_rejects_kickoff_for_plain_session(mocker: pytest_mock.MockerFixture,) -> None:diff --git a/autogpt_platform/backend/backend/copilot/response_model.py b/autogpt_platform/backend/backend/copilot/response_model.pyindex d8ff148563..655aab18cb 100644--- a/autogpt_platform/backend/backend/copilot/response_model.py+++ b/autogpt_platform/backend/backend/copilot/response_model.py@@ -62,6 +62,9 @@ class ResponseType(str, Enum):# buffer at a tool boundary. Lets the client promote queued chips to# bubbles immediately instead of waiting for its backstop poll.PENDING_DRAINED = "data-pending-drained"+ # Written by the stream route when a send joins a running turn's pending+ # queue, so the client can tell it from a turn that never started.+ FOLLOW_UP_QUEUED = "data-follow-up-queued"MODE_CHANGED = "data-mode-changed"# Live context-compaction progress — phase transitions plus token/message# deltas. Transient (never persisted); the durable record is the@@ -548,3 +551,16 @@ class StreamCheckpoint(StreamBaseResponse):"transient": True,}return f"data: {json.dumps(data)}\n\n"+++class StreamFollowUpQueued(StreamBaseResponse):+ """The send was queued as a follow-up to the session's running turn.++ Transient: the AI SDK hands it to ``onData`` and stores nothing.+ """++ type: ResponseType = ResponseType.FOLLOW_UP_QUEUED++ def to_sse(self) -> str:+ data = {"type": self.type.value, "data": {}, "transient": True}+ return f"data: {json.dumps(data)}\n\n"diff --git a/autogpt_platform/backend/backend/copilot/stream_registry.py b/autogpt_platform/backend/backend/copilot/stream_registry.pyindex 0f533b9f9d..0e3fa71041 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry.py@@ -49,6 +49,7 @@ from .response_model import (StreamError,StreamFinish,StreamFinishStep,+ StreamFollowUpQueued,StreamHeartbeat,StreamModeChanged,StreamPendingDrained,@@ -1320,6 +1321,7 @@ CHUNK_TYPE_TO_CLASS: dict[str, type[StreamBaseResponse]] = {ResponseType.STATUS.value: StreamStatus,ResponseType.DREAM_OPERATIONS.value: StreamDreamOperations,ResponseType.PENDING_DRAINED.value: StreamPendingDrained,+ ResponseType.FOLLOW_UP_QUEUED.value: StreamFollowUpQueued,ResponseType.MODE_CHANGED.value: StreamModeChanged,ResponseType.PROVIDER_FAILURE.value: StreamProviderFailure,ResponseType.COMPACTION.value: StreamCompactionProgress,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.tsindex ccd12b167a..619250f55e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/fakeBackend.ts@@ -8,15 +8,13 @@ const HEARTBEAT_MS = 10_000;const LISTENER_READ_MS = 5_000;const encoder = new TextEncoder();// What the route answers a send it queued: framing, no ids, no turn.-const QUEUED_STREAM = [- { type: "start", messageId: "queued" },- { type: "start-step" },- { type: "finish-step" },- { type: "finish" },-]- .map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`)- .concat("data: [DONE]\n\n")- .join("");+const QUEUED_STREAM = emptyStream();+// What it answers a send it queued behind the turn already running.+const FOLLOW_UP_STREAM = emptyStream({+ type: "data-follow-up-queued",+ data: {},+ transient: true,+});export interface FakeConnection {method: string;@@ -39,6 +37,8 @@ type Responder = (request: { method: string; url: URL }) =>| "network-error"// An open response that never yields a byte: a page frozen before it read any.| "silent"+ // The backend queued the send behind a turn already running.+ | "follow-up-queued"| { status: number; body: unknown };/**@@ -79,6 +79,11 @@ export function fakeBackend(turn: RecordedTurn) {requests.push({ method, url });const answer = responder({ method, url });if (answer === "network-error") throw new TypeError("Failed to fetch");+ if (answer === "follow-up-queued")+ return new Response(FOLLOW_UP_STREAM, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });if (answer === "silent")return new Response(new ReadableStream<Uint8Array>(), {status: 200,@@ -283,3 +288,16 @@ function dataOf(sse: string) {}): null;}++function emptyStream(...parts: object[]) {+ return [+ { type: "start", messageId: "queued" },+ { type: "start-step" },+ ...parts,+ { type: "finish-step" },+ { type: "finish" },+ ]+ .map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`)+ .concat("data: [DONE]\n\n")+ .join("");+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.tsindex 74e40f9913..ebf9604085 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts@@ -456,6 +456,25 @@ describe("recovery", () => {expect(most).toBe(1);});+ it("a send queued behind another tab's running turn is not drawn above that turn", async () => {+ // Another tab's turn runs; this tab has not read the session since.+ backend.beginRunning();+ backend.publish(FIRST_BLOCK_DONE);+ backend.respond(({ method }) =>+ method === "POST" ? "follow-up-queued" : "stream",+ );+ void runtime.send({ text: "And what about example.org?" }, undefined);+ await advance(2_000);++ expect(backend.connections.at(-1)?.url.searchParams.get("turn")).toBe(+ backend.turnId,+ );+ // The other tab's prompt (row 0) stays history above the followed turn.+ expect(snapshot().ownedFrom).toBe(1);+ expect(textsOf(render())).toEqual([FIRST_TEXT]);+ expect(snapshot().error).toBeNull();+ });+it("stops reading the session once its queued turn is cancelled", async () => {backend.queueNextTurn();void runtime.send({ text: PROMPT }, undefined);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.tsindex d57d8f5c61..febfc471ba 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts@@ -139,6 +139,8 @@ interface Connection {syntheticError: string | null;/** A send's own prompt segment, by key. */prompt: string | null;+ /** The backend queued this send behind the session's running turn. */+ followUp: boolean;}/** What the classification needs to know about a connection that is gone. */@@ -443,6 +445,7 @@ export class TurnRuntime {closedByClient: false,syntheticError: null,prompt: init.prompt ?? null,+ followUp: false,};if (asRotation) this.rotating = conn;else {@@ -494,6 +497,11 @@ export class TurnRuntime {this.applyFrom(conn, frame.entry);} else if (frame.kind === "synthetic" && frame.chunk.type === "error") {conn.syntheticError = str(frame.chunk.errorText);+ } else if (+ frame.kind === "synthetic" &&+ frame.chunk.type === "data-follow-up-queued"+ ) {+ conn.followUp = true;}this.emit();}@@ -552,6 +560,9 @@ export class TurnRuntime {return;}if (!seg) {+ // The page shows a queued follow-up as a chip; the prompt drawn at+ // send would sit above the running turn and take that turn's prompt row.+ if (conn.followUp) this.dropUnsentUserRow();this.findLostTurn(conn, end);return;}