fix: backfill running chat turns without prompt frame (#1429)

This commit is contained in:
Carlos Florêncio
2026-06-18 16:29:39 +01:00
committed by GitHub
parent fce3b421ea
commit e148234e80
8 changed files with 392 additions and 96 deletions
+83
View File
@@ -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<string, unknown> | null {
return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : 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<PromptDropController> {
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,
};
}
@@ -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);
});
});
@@ -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);
});
});
@@ -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);
});
});
@@ -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.
@@ -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
@@ -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",
@@ -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
);
}