From e148234e80249d9feeb6f8692461aa981aeaa6c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Thu, 18 Jun 2026 16:29:39 +0100 Subject: [PATCH] fix: backfill running chat turns without prompt frame (#1429) --- apps/web/e2e/helpers/ws-drop.ts | 83 ++++++++++ .../e2e/tests/chat/message-add-ws-gap.spec.ts | 31 ++++ .../chat/mobile-message-add-ws-gap.spec.ts | 36 +++++ .../workflow/workflow-auto-advance.spec.ts | 150 ++++++++++++++++++ .../workflow/workflow-automation.spec.ts | 94 ----------- .../workflow/workflow-step-proceed.spec.ts | 81 ++++++++++ .../session/use-session-messages.test.ts | 10 +- .../domains/session/use-session-messages.ts | 3 +- 8 files changed, 392 insertions(+), 96 deletions(-) create mode 100644 apps/web/e2e/helpers/ws-drop.ts create mode 100644 apps/web/e2e/tests/chat/message-add-ws-gap.spec.ts create mode 100644 apps/web/e2e/tests/chat/mobile-message-add-ws-gap.spec.ts create mode 100644 apps/web/e2e/tests/workflow/workflow-auto-advance.spec.ts diff --git a/apps/web/e2e/helpers/ws-drop.ts b/apps/web/e2e/helpers/ws-drop.ts new file mode 100644 index 0000000000..2d7f2eb541 --- /dev/null +++ b/apps/web/e2e/helpers/ws-drop.ts @@ -0,0 +1,83 @@ +import type { Page } from "@playwright/test"; + +type DroppedMessage = { + action: string; + content: string; +}; + +type PromptDropController = { + dropPrompt: (prompt: string) => void; + droppedCount: () => number; +}; + +function asRecord(value: unknown): Record | null { + return typeof value === "object" && value !== null ? (value as Record) : null; +} + +function isTargetUserMessageAdded( + message: unknown, + prompt: string, +): message is { payload: { content: string } } { + const envelope = asRecord(message); + const payload = asRecord(envelope?.payload); + return ( + envelope?.action === "session.message.added" && + payload?.author_type === "user" && + typeof payload.content === "string" && + payload.content.includes(prompt) + ); +} + +function filterServerFrame( + message: string | Buffer, + prompt: string | null, + dropped: DroppedMessage[], +): string | Buffer | null { + if (!prompt || typeof message !== "string") return message; + + const kept: string[] = []; + let didDrop = false; + for (const part of message.split("\n")) { + const trimmed = part.trim(); + if (!trimmed) { + kept.push(part); + continue; + } + try { + const parsed = JSON.parse(trimmed) as unknown; + if (isTargetUserMessageAdded(parsed, prompt)) { + didDrop = true; + dropped.push({ action: "session.message.added", content: parsed.payload.content }); + continue; + } + } catch { + // Preserve non-JSON frames; the app's WS client handles parse failures too. + } + kept.push(part); + } + + if (!didDrop) return message; + const filtered = kept.join("\n"); + return filtered.trim() ? filtered : null; +} + +export async function routeMainWebSocketWithPromptDrop(page: Page): Promise { + let promptToDrop: string | null = null; + const dropped: DroppedMessage[] = []; + + await page.routeWebSocket(/\/ws$/, (ws) => { + const server = ws.connectToServer(); + server.onMessage((message) => { + const filtered = filterServerFrame(message, promptToDrop, dropped); + if (filtered !== null) ws.send(filtered); + }); + }); + + return { + dropPrompt: (prompt: string) => { + promptToDrop = prompt; + dropped.length = 0; + }, + droppedCount: () => dropped.length, + }; +} diff --git a/apps/web/e2e/tests/chat/message-add-ws-gap.spec.ts b/apps/web/e2e/tests/chat/message-add-ws-gap.spec.ts new file mode 100644 index 0000000000..1d10cb6c05 --- /dev/null +++ b/apps/web/e2e/tests/chat/message-add-ws-gap.spec.ts @@ -0,0 +1,31 @@ +import { test, expect } from "../../fixtures/test-base"; +import { seedIdleSession } from "../../helpers/session"; +import { routeMainWebSocketWithPromptDrop } from "../../helpers/ws-drop"; + +test.describe("Chat send websocket gaps", () => { + test("shows an accepted user prompt when its message-added notification is missed", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(90_000); + + const wsDrop = await routeMainWebSocketWithPromptDrop(testPage); + const session = await seedIdleSession(testPage, apiClient, seedData, "Message added WS gap"); + + const prompt = "/slow 8s"; + wsDrop.dropPrompt(prompt); + + await session.sendMessageViaButton(prompt); + + await expect( + session.chat.locator(".chat-message-list:visible").getByText(prompt, { exact: false }), + ).toBeVisible({ timeout: 5_000 }); + await expect + .poll(wsDrop.droppedCount, { + message: "expected the test proxy to drop the prompt's session.message.added frame", + timeout: 10_000, + }) + .toBeGreaterThan(0); + }); +}); diff --git a/apps/web/e2e/tests/chat/mobile-message-add-ws-gap.spec.ts b/apps/web/e2e/tests/chat/mobile-message-add-ws-gap.spec.ts new file mode 100644 index 0000000000..ad5168fcd0 --- /dev/null +++ b/apps/web/e2e/tests/chat/mobile-message-add-ws-gap.spec.ts @@ -0,0 +1,36 @@ +import { test, expect } from "../../fixtures/test-base"; +import { routeMainWebSocketWithPromptDrop } from "../../helpers/ws-drop"; +import { seedIdleSession } from "../../helpers/session"; + +test.describe("Mobile chat send websocket gaps", () => { + test("shows an accepted user prompt when its message-added notification is missed", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(90_000); + + const wsDrop = await routeMainWebSocketWithPromptDrop(testPage); + const session = await seedIdleSession( + testPage, + apiClient, + seedData, + "Mobile Message Added WS Gap", + ); + + const prompt = "/slow 8s"; + wsDrop.dropPrompt(prompt); + + await session.sendMessageViaButton(prompt); + + await expect( + session.chat.locator(".chat-message-list:visible").getByText(prompt, { exact: false }), + ).toBeVisible({ timeout: 5_000 }); + await expect + .poll(wsDrop.droppedCount, { + message: "expected the test proxy to drop the prompt's session.message.added frame", + timeout: 10_000, + }) + .toBeGreaterThan(0); + }); +}); diff --git a/apps/web/e2e/tests/workflow/workflow-auto-advance.spec.ts b/apps/web/e2e/tests/workflow/workflow-auto-advance.spec.ts new file mode 100644 index 0000000000..2ebe1ba255 --- /dev/null +++ b/apps/web/e2e/tests/workflow/workflow-auto-advance.spec.ts @@ -0,0 +1,150 @@ +import { test, expect } from "../../fixtures/test-base"; +import { KanbanPage } from "../../pages/kanban-page"; +import { SessionPage } from "../../pages/session-page"; + +test.describe("Workflow auto-advance", () => { + /** + * Seeds a 3-step workflow (Inbox -> In Progress -> Done). + * Configures In Progress with on_enter: auto_start_agent and a custom step + * prompt routed to the mock agent, plus on_turn_complete: move_to_step(Done). + */ + test("auto_start_agent with step custom prompt; on_turn_complete advances to next column", async ({ + testPage, + apiClient, + seedData, + }) => { + const workflow = await apiClient.createWorkflow( + seedData.workspaceId, + "Automation Test Workflow", + ); + + const inboxStep = await apiClient.createWorkflowStep(workflow.id, "Inbox", 0); + const inProgressStep = await apiClient.createWorkflowStep(workflow.id, "In Progress", 1); + const doneStep = await apiClient.createWorkflowStep(workflow.id, "Done", 2); + + await apiClient.updateWorkflowStep(inProgressStep.id, { + prompt: 'e2e:delay(3000)\ne2e:message("delayed step response")\n{{task_prompt}}', + events: { + on_enter: [{ type: "auto_start_agent" }], + on_turn_complete: [{ type: "move_to_step", config: { step_id: doneStep.id } }], + }, + }); + + await apiClient.saveUserSettings({ + workspace_id: seedData.workspaceId, + workflow_filter_id: workflow.id, + enable_preview_on_click: false, + }); + + const task = await apiClient.createTask(seedData.workspaceId, "Auto Agent Workflow Task", { + workflow_id: workflow.id, + workflow_step_id: inboxStep.id, + agent_profile_id: seedData.agentProfileId, + repository_ids: [seedData.repositoryId], + }); + + await apiClient.moveTask(task.id, workflow.id, inProgressStep.id); + + const kanban = new KanbanPage(testPage); + await kanban.goto(); + + const cardInProgress = kanban.taskCardInColumn("Auto Agent Workflow Task", inProgressStep.id); + await expect(cardInProgress).toBeVisible({ timeout: 15_000 }); + + const cardInDone = kanban.taskCardInColumn("Auto Agent Workflow Task", doneStep.id); + await expect(cardInDone).toBeVisible({ timeout: 30_000 }); + + await cardInDone.click(); + await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 }); + + const session = new SessionPage(testPage); + await session.waitForLoad(); + await expect(session.stepperStep("Done")).toHaveAttribute("aria-current", "step", { + timeout: 10_000, + }); + await expect( + session.activeChat().getByText("delayed step response", { exact: true }), + ).toBeVisible({ + timeout: 30_000, + }); + await session.waitForChatIdle({ timeout: 15_000 }); + await expect(session.sidebarSection("Turn Finished")).toBeVisible(); + }); + + test("does not retrigger previous step prompt after auto-advancing into Done", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + + const workflow = await apiClient.createWorkflow( + seedData.workspaceId, + "Final Step No Retrigger Workflow", + ); + + const startStep = await apiClient.createWorkflowStep(workflow.id, "Start", 0); + const workStep = await apiClient.createWorkflowStep(workflow.id, "Work", 1); + await apiClient.createWorkflowStep(workflow.id, "Done", 2); + + await apiClient.updateWorkflowStep(startStep.id, { + events: { + on_turn_complete: [{ type: "move_to_next" }], + }, + }); + + const workMarker = "final-step-work-response-once"; + await apiClient.updateWorkflowStep(workStep.id, { + prompt: `e2e:message("${workMarker}")\n{{task_prompt}}`, + events: { + on_enter: [{ type: "auto_start_agent" }], + on_turn_complete: [{ type: "move_to_next" }], + }, + }); + + await apiClient.saveUserSettings({ + workspace_id: seedData.workspaceId, + workflow_filter_id: workflow.id, + enable_preview_on_click: false, + }); + + const task = await apiClient.createTask(seedData.workspaceId, "Final Done Retrigger Task", { + workflow_id: workflow.id, + workflow_step_id: startStep.id, + agent_profile_id: seedData.agentProfileId, + repository_ids: [seedData.repositoryId], + }); + + const session = new SessionPage(testPage); + await testPage.goto(`/t/${task.id}`); + await session.waitForLoad(); + await expect(session.stepperStep("Start")).toHaveAttribute("aria-current", "step", { + timeout: 10_000, + }); + + await session.sendMessageViaButton("/e2e:simple-message"); + + await expect(session.stepperStep("Done")).toHaveAttribute("aria-current", "step", { + timeout: 45_000, + }); + await expect(session.activeChat().getByText(workMarker, { exact: true })).toBeVisible({ + timeout: 30_000, + }); + await session.waitForChatIdle({ timeout: 30_000 }); + + const taskSessions = await apiClient.listTaskSessions(task.id); + const primarySession = taskSessions.sessions.find((candidate) => candidate.is_primary); + expect(primarySession, "expected a primary task session").toBeTruthy(); + + const { messages } = await apiClient.listSessionMessages(primarySession!.id); + const workResponses = messages.filter( + (message) => message.author_type === "agent" && message.content.includes(workMarker), + ); + const workPrompts = messages.filter( + (message) => message.author_type === "user" && message.content.includes(workMarker), + ); + + expect(workResponses).toHaveLength(1); + expect(workPrompts).toHaveLength(1); + }); +}); diff --git a/apps/web/e2e/tests/workflow/workflow-automation.spec.ts b/apps/web/e2e/tests/workflow/workflow-automation.spec.ts index 1fd65a8cee..7231ebaddb 100644 --- a/apps/web/e2e/tests/workflow/workflow-automation.spec.ts +++ b/apps/web/e2e/tests/workflow/workflow-automation.spec.ts @@ -3,100 +3,6 @@ import { KanbanPage } from "../../pages/kanban-page"; import { SessionPage } from "../../pages/session-page"; test.describe("Workflow automation", () => { - /** - * Seeds a 3-step workflow (Inbox → In Progress → Done). - * Configures In Progress with on_enter: auto_start_agent and a custom step - * prompt routed to the mock agent, plus on_turn_complete: move_to_step(Done). - * - * Verifies: - * - auto_start_agent fires when task is moved into In Progress - * - task appears in In Progress column before agent completes - * - step custom prompt is used (not the task description) - * - on_turn_complete advances task to Done column on the kanban board - * - session stepper shows Done as the current step - */ - test("auto_start_agent with step custom prompt; on_turn_complete advances to next column", async ({ - testPage, - apiClient, - seedData, - }) => { - // --- Seed a workflow with explicit step configuration --- - const workflow = await apiClient.createWorkflow( - seedData.workspaceId, - "Automation Test Workflow", - ); - - const inboxStep = await apiClient.createWorkflowStep(workflow.id, "Inbox", 0); - const inProgressStep = await apiClient.createWorkflowStep(workflow.id, "In Progress", 1); - const doneStep = await apiClient.createWorkflowStep(workflow.id, "Done", 2); - - // Configure In Progress: auto_start_agent on enter, custom step prompt with delay - // so we can observe the task in In Progress before on_turn_complete moves it to Done. - await apiClient.updateWorkflowStep(inProgressStep.id, { - prompt: 'e2e:delay(3000)\ne2e:message("delayed step response")\n{{task_prompt}}', - events: { - on_enter: [{ type: "auto_start_agent" }], - on_turn_complete: [{ type: "move_to_step", config: { step_id: doneStep.id } }], - }, - }); - - // Point the kanban page at our custom workflow - await apiClient.saveUserSettings({ - workspace_id: seedData.workspaceId, - workflow_filter_id: workflow.id, - enable_preview_on_click: false, - }); - - // Use the seed profile so tests don't pick up passthrough profiles from other tests. - const agentProfileId = seedData.agentProfileId; - - // Create task in Inbox — does NOT trigger auto_start_agent - const task = await apiClient.createTask(seedData.workspaceId, "Auto Agent Workflow Task", { - workflow_id: workflow.id, - workflow_step_id: inboxStep.id, - agent_profile_id: agentProfileId, - repository_ids: [seedData.repositoryId], - }); - - // Move task to In Progress → triggers on_enter: auto_start_agent - await apiClient.moveTask(task.id, workflow.id, inProgressStep.id); - - const kanban = new KanbanPage(testPage); - await kanban.goto(); - - // Task should appear in In Progress while the agent is working (3s delay) - const cardInProgress = kanban.taskCardInColumn("Auto Agent Workflow Task", inProgressStep.id); - await expect(cardInProgress).toBeVisible({ timeout: 15_000 }); - - // After the agent completes its turn, on_turn_complete fires and moves the - // task to Done. The kanban board receives a WS push. - const cardInDone = kanban.taskCardInColumn("Auto Agent Workflow Task", doneStep.id); - await expect(cardInDone).toBeVisible({ timeout: 30_000 }); - - // Navigate to the session page - await cardInDone.click(); - await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 }); - - const session = new SessionPage(testPage); - await session.waitForLoad(); - - // Stepper shows Done as current step - await expect(session.stepperStep("Done")).toHaveAttribute("aria-current", "step", { - timeout: 10_000, - }); - - // Mock agent response confirms the step custom prompt was executed - await expect(session.chat.getByText("delayed step response", { exact: true })).toBeVisible({ - timeout: 30_000, - }); - - // Session transitions to idle after agent completes - await session.waitForChatIdle({ timeout: 15_000 }); - - // Sidebar shows the task under "Turn Finished" section - await expect(session.sidebarSection("Turn Finished")).toBeVisible(); - }); - /** * Seeds a 4-step workflow (Todo → In Progress → Review → Done) and validates * the full lifecycle from both the kanban page and the session details page. diff --git a/apps/web/e2e/tests/workflow/workflow-step-proceed.spec.ts b/apps/web/e2e/tests/workflow/workflow-step-proceed.spec.ts index 06785aea1d..9ed76f1388 100644 --- a/apps/web/e2e/tests/workflow/workflow-step-proceed.spec.ts +++ b/apps/web/e2e/tests/workflow/workflow-step-proceed.spec.ts @@ -1,4 +1,5 @@ import { test, expect } from "../../fixtures/test-base"; +import { routeMainWebSocketWithPromptDrop } from "../../helpers/ws-drop"; import { KanbanPage } from "../../pages/kanban-page"; import { SessionPage } from "../../pages/session-page"; @@ -110,6 +111,86 @@ test.describe("Manual proceed to next workflow step", () => { await expect(session.idleInput()).toBeVisible({ timeout: 15_000 }); }); + test("shows next step auto-start prompt when its message-added notification is missed", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + + const wsDrop = await routeMainWebSocketWithPromptDrop(testPage); + const workflow = await apiClient.createWorkflow( + seedData.workspaceId, + "Proceed Message Gap Workflow", + ); + + const specStep = await apiClient.createWorkflowStep(workflow.id, "Spec", 0); + const workStep = await apiClient.createWorkflowStep(workflow.id, "Work", 1); + await apiClient.createWorkflowStep(workflow.id, "Done", 2); + + await apiClient.updateWorkflowStep(specStep.id, { + prompt: 'e2e:message("spec done")\n{{task_prompt}}', + events: { + on_enter: [{ type: "auto_start_agent" }], + }, + }); + + const workPrompt = "/slow 8s"; + await apiClient.updateWorkflowStep(workStep.id, { + prompt: `${workPrompt}\n{{task_prompt}}`, + events: { + on_enter: [{ type: "auto_start_agent" }], + }, + }); + + await apiClient.saveUserSettings({ + workspace_id: seedData.workspaceId, + workflow_filter_id: workflow.id, + enable_preview_on_click: false, + }); + + await apiClient.createTask(seedData.workspaceId, "Proceed Message Gap Task", { + workflow_id: workflow.id, + workflow_step_id: specStep.id, + agent_profile_id: seedData.agentProfileId, + repository_ids: [seedData.repositoryId], + }); + + const kanban = new KanbanPage(testPage); + await kanban.goto(); + + const card = kanban.taskCardInColumn("Proceed Message Gap Task", specStep.id); + await expect(card).toBeVisible({ timeout: 15_000 }); + await card.click(); + await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 }); + + const session = new SessionPage(testPage); + await session.waitForLoad(); + await session.waitForChatIdle({ timeout: 30_000 }); + await expect(session.stepperStep("Spec")).toHaveAttribute("aria-current", "step", { + timeout: 10_000, + }); + + const proceedBtn = session.proceedNextStepButton(); + await expect(proceedBtn).toBeVisible({ timeout: 10_000 }); + + wsDrop.dropPrompt(workPrompt); + await proceedBtn.click(); + + await expect(session.stepperStep("Work")).toHaveAttribute("aria-current", "step", { + timeout: 15_000, + }); + await expect( + session.chat.locator(".chat-message-list:visible").getByText(workPrompt, { exact: false }), + ).toBeVisible({ timeout: 5_000 }); + await expect + .poll(wsDrop.droppedCount, { + message: "expected the test proxy to drop the workflow prompt's message-added frame", + timeout: 10_000, + }) + .toBeGreaterThan(0); + }); + /** * Regression test: the proceed button must re-enable after each step transition. * Previously, isMoving stayed true after clicking proceed because the button diff --git a/apps/web/hooks/domains/session/use-session-messages.test.ts b/apps/web/hooks/domains/session/use-session-messages.test.ts index fd63f8293a..c3b20c6a91 100644 --- a/apps/web/hooks/domains/session/use-session-messages.test.ts +++ b/apps/web/hooks/domains/session/use-session-messages.test.ts @@ -185,7 +185,7 @@ describe("running message backfill guards", () => { ).toBe(false); }); - it("runs only for a connected RUNNING session with an active-turn user prompt", () => { + it("runs for a connected RUNNING session with an active turn", () => { const messages = [makeMessage({ id: "u1", turn_id: "turn-1", author_type: "user" })]; expect( shouldRunMessageBackfill({ @@ -195,6 +195,14 @@ describe("running message backfill guards", () => { messages, }), ).toBe(true); + expect( + shouldRunMessageBackfill({ + taskSessionState: "RUNNING", + connectionStatus: "connected", + activeTurnId: "turn-1", + messages: [], + }), + ).toBe(true); expect( shouldRunMessageBackfill({ taskSessionState: "WAITING_FOR_INPUT", diff --git a/apps/web/hooks/domains/session/use-session-messages.ts b/apps/web/hooks/domains/session/use-session-messages.ts index a2f2326e7c..79080a30b0 100644 --- a/apps/web/hooks/domains/session/use-session-messages.ts +++ b/apps/web/hooks/domains/session/use-session-messages.ts @@ -92,10 +92,11 @@ export function shouldRunMessageBackfill(params: { activeTurnId: string | null; messages: Message[]; }) { + // The active prompt may be the missed WS frame; start backfill once the turn exists. return ( params.connectionStatus === "connected" && params.taskSessionState === "RUNNING" && - hasUserPromptInActiveTurn(params.messages, params.activeTurnId) + params.activeTurnId !== null ); }