diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e3e35d042..e03ffc132 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,6 +1,9 @@ name: Tests on: + workflow_dispatch: + schedule: + - cron: "17 3 * * *" push: branches: - main @@ -96,6 +99,52 @@ jobs: working-directory: web run: npx eslint . + multi-worker-web: + name: Four-worker browser acceptance + if: vars.DEEPTUTOR_MULTI_WORKER_E2E_URL != '' + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: web/package-lock.json + + - name: Install frontend dependencies + working-directory: web + run: npm ci --legacy-peer-deps + + - name: Install Playwright Chromium + working-directory: web + run: npx playwright install --with-deps chromium + + - name: Run desktop and mobile four-worker scenarios + working-directory: web + run: >- + npx playwright test + --project=multi-worker-turns-desktop + --project=multi-worker-turns-mobile + env: + DEEPTUTOR_MULTI_WORKER_E2E: "1" + WEB_BASE_URL: ${{ vars.DEEPTUTOR_MULTI_WORKER_E2E_URL }} + NEXT_PUBLIC_API_BASE: ${{ vars.DEEPTUTOR_MULTI_WORKER_E2E_URL }} + DEEPTUTOR_MULTI_WORKER_CONTROL_URL: ${{ vars.DEEPTUTOR_MULTI_WORKER_CONTROL_URL || vars.DEEPTUTOR_MULTI_WORKER_E2E_URL }} + + - name: Upload browser traces and videos + if: always() + uses: actions/upload-artifact@v4 + with: + name: multi-worker-browser-evidence + path: | + web/playwright-report + web/test-results + if-no-files-found: ignore + import-check: name: Import Check (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest @@ -207,7 +256,7 @@ jobs: test-summary: name: Test Summary runs-on: ubuntu-latest - needs: [lint, web-tests, import-check, python-tests] + needs: [lint, web-tests, multi-worker-web, import-check, python-tests] if: always() steps: @@ -219,9 +268,10 @@ jobs: echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY echo "| Lint and format | ${{ needs.lint.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY echo "| Web node tests | ${{ needs.web-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY + echo "| Four-worker browser acceptance | ${{ needs.multi-worker-web.result == 'success' && '✅ Passed' || needs.multi-worker-web.result == 'skipped' && '⏭️ Fixture not configured' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY echo "| Import check (3.11/3.12/3.13; 3.14 best-effort) | ${{ needs.import-check.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY echo "| Python tests (3.11/3.12/3.13; 3.14 best-effort) | ${{ needs.python-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY - name: Fail if tests failed - if: needs.lint.result == 'failure' || needs.web-tests.result == 'failure' || needs.import-check.result == 'failure' || needs.python-tests.result == 'failure' + if: needs.lint.result == 'failure' || needs.web-tests.result == 'failure' || needs.multi-worker-web.result == 'failure' || needs.import-check.result == 'failure' || needs.python-tests.result == 'failure' run: exit 1 diff --git a/web/playwright.config.ts b/web/playwright.config.ts index 004653e8b..ebcca42c5 100644 --- a/web/playwright.config.ts +++ b/web/playwright.config.ts @@ -24,6 +24,7 @@ export default defineConfig({ testIgnore: [ "**/epub-reader.audit.ts", "**/e2e/turn-lifecycle.audit.ts", + "**/e2e/multi-worker-turns.audit.ts", ], use: { ...devices["Desktop Chrome"] }, }, @@ -32,6 +33,16 @@ export default defineConfig({ testMatch: "**/e2e/turn-lifecycle.audit.ts", use: { ...devices["Desktop Chrome"] }, }, + { + name: "multi-worker-turns-desktop", + testMatch: "**/e2e/multi-worker-turns.audit.ts", + use: { ...devices["Desktop Chrome"], reducedMotion: "reduce" }, + }, + { + name: "multi-worker-turns-mobile", + testMatch: "**/e2e/multi-worker-turns.audit.ts", + use: { ...devices["iPhone 13"], reducedMotion: "reduce" }, + }, { name: "epub-reader-chromium", testMatch: "**/epub-reader.audit.ts", diff --git a/web/tests/e2e/fixtures/runtime.ts b/web/tests/e2e/fixtures/runtime.ts new file mode 100644 index 000000000..f7ee3601e --- /dev/null +++ b/web/tests/e2e/fixtures/runtime.ts @@ -0,0 +1,182 @@ +import assert from "node:assert/strict"; + +import type { APIRequestContext, Page } from "@playwright/test"; +import { expect, test as base } from "@playwright/test"; + +export type MultiWorkerScenario = + | "cross_worker_resume" + | "cross_worker_cancel" + | "cross_worker_reply" + | "owner_loss" + | "reload_replay" + | "foreign_observation"; + +interface RuntimeStatus { + worker_count?: number; + coordination?: { backend?: string; healthy?: boolean }; + redis?: { configured?: boolean; healthy?: boolean }; +} + +interface ArmedScenario { + scenario_id: string; + prompt: string; + expected_turn_id?: string; +} + +export interface ScenarioEvidence { + scenario_id: string; + connection_workers: string[]; + command_workers?: string[]; + owner_worker?: string; + recovery_worker?: string; + observed_states?: string[]; + emitted_sequences: number[]; + delivered_sequences: number[]; + duplicate_count: number; + gap_count: number; + terminal_status?: string; + failure_code?: string; + retryable?: boolean; +} + +const DEFAULT_CONTROL_PATH = "/__e2e__/v2-turn-runtime"; + +export const multiWorkerFixtureAvailable = + process.env.DEEPTUTOR_MULTI_WORKER_E2E === "1"; + +function fixtureBaseUrl(): string { + return ( + process.env.DEEPTUTOR_MULTI_WORKER_CONTROL_URL || + process.env.NEXT_PUBLIC_API_BASE || + process.env.WEB_BASE_URL || + "http://127.0.0.1:8001" + ).replace(/\/$/, ""); +} + +export class MultiWorkerRuntimeFixture { + private readonly baseUrl = fixtureBaseUrl(); + private readonly controlPath = + process.env.DEEPTUTOR_MULTI_WORKER_CONTROL_PATH || DEFAULT_CONTROL_PATH; + private legacyRequests: string[] = []; + + constructor(private readonly request: APIRequestContext) {} + + trackNetwork(page: Page): void { + page.on("request", (request) => { + const pathname = new URL(request.url()).pathname; + if (pathname === "/api/v1/chat" || pathname.startsWith("/api/v1/chat/")) { + this.legacyRequests.push(request.url()); + } + }); + } + + async assertReady(): Promise { + const response = await this.request.get(`${this.baseUrl}/api/v1/system/runtime`); + expect(response.ok(), "runtime status endpoint must be reachable").toBeTruthy(); + const status = (await response.json()) as RuntimeStatus; + expect(status.worker_count, "browser acceptance requires exactly four workers").toBe(4); + expect(status.coordination?.backend, "browser acceptance requires Redis coordination").toBe( + "redis", + ); + expect( + status.coordination?.healthy ?? status.redis?.healthy, + "Redis coordination must be healthy", + ).toBe(true); + + const fixture = await this.request.get(this.controlUrl("health")); + expect(fixture.ok(), "the deterministic failure-injection fixture must be enabled").toBeTruthy(); + const fixtureStatus = (await fixture.json()) as { worker_ids?: string[] }; + expect(fixtureStatus.worker_ids).toHaveLength(4); + } + + async reset(): Promise { + this.legacyRequests = []; + const response = await this.request.post(this.controlUrl("reset")); + expect(response.ok(), "fixture reset failed").toBeTruthy(); + } + + async arm( + scenario: MultiWorkerScenario, + options: Record = {}, + ): Promise { + const response = await this.request.post(this.controlUrl("scenarios"), { + data: { scenario, ...options }, + }); + expect(response.ok(), `could not arm ${scenario}`).toBeTruthy(); + return (await response.json()) as ArmedScenario; + } + + async act(scenarioId: string, action: string): Promise { + const response = await this.request.post( + this.controlUrl(`scenarios/${encodeURIComponent(scenarioId)}/actions`), + { data: { action } }, + ); + expect(response.ok(), `fixture action ${action} failed`).toBeTruthy(); + } + + async evidence(scenarioId: string): Promise { + const response = await this.request.get( + this.controlUrl(`scenarios/${encodeURIComponent(scenarioId)}/evidence`), + ); + expect(response.ok(), "fixture evidence is unavailable").toBeTruthy(); + return (await response.json()) as ScenarioEvidence; + } + + async expectEvidence( + scenarioId: string, + predicate: (evidence: ScenarioEvidence) => boolean, + description: string, + ): Promise { + let latest: ScenarioEvidence | undefined; + await expect + .poll( + async () => { + latest = await this.evidence(scenarioId); + return predicate(latest); + }, + { message: description, timeout: 60_000 }, + ) + .toBe(true); + assert(latest); + return latest; + } + + assertNoLegacyRequests(): void { + assert.deepEqual( + this.legacyRequests, + [], + `the browser requested retired chat endpoints: ${this.legacyRequests.join(", ")}`, + ); + } + + private controlUrl(suffix: string): string { + return `${this.baseUrl}${this.controlPath}/${suffix}`; + } +} + +export const test = base.extend<{ runtimeFixture: MultiWorkerRuntimeFixture }>({ + runtimeFixture: async ({ request, page }, provide) => { + const fixture = new MultiWorkerRuntimeFixture(request); + fixture.trackNetwork(page); + await fixture.assertReady(); + await fixture.reset(); + await provide(fixture); + fixture.assertNoLegacyRequests(); + }, +}); + +export { expect }; + +export async function sendPrompt(page: Page, prompt: string): Promise { + const composer = page.getByRole("textbox").last(); + await expect(composer).toBeVisible(); + await composer.fill(prompt); + await composer.press("Enter"); +} + +export function lifecycleStatus(page: Page) { + return page.getByRole("status").filter({ + hasText: + /Connecting|Queued|Working|Waiting for your answer|Stopping|Reconnecting|Completed|Stopped|Response interrupted|Turn failed/i, + }); +} diff --git a/web/tests/e2e/multi-worker-turns.audit.ts b/web/tests/e2e/multi-worker-turns.audit.ts new file mode 100644 index 000000000..2be9fa415 --- /dev/null +++ b/web/tests/e2e/multi-worker-turns.audit.ts @@ -0,0 +1,171 @@ +import { + expect, + lifecycleStatus, + multiWorkerFixtureAvailable, + sendPrompt, + test, +} from "./fixtures/runtime"; + +test.describe("four-worker v2 turn acceptance", () => { + test.skip( + !multiWorkerFixtureAvailable, + "Set DEEPTUTOR_MULTI_WORKER_E2E=1 and connect the deterministic four-worker fixture.", + ); + + test.beforeEach(async ({ page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.goto("/"); + }); + + test("resumes through another worker without gaps or duplicates", async ({ + page, + runtimeFixture, + }) => { + const scenario = await runtimeFixture.arm("cross_worker_resume", { + owner_worker: "worker-a", + reconnect_worker: "worker-b", + disconnect_after_seq: 2, + }); + await sendPrompt(page, scenario.prompt); + + await expect(lifecycleStatus(page)).toContainText(/Working/i); + await runtimeFixture.act(scenario.scenario_id, "drop_socket"); + await expect(lifecycleStatus(page)).toContainText(/Reconnecting/i); + await expect(lifecycleStatus(page)).toContainText(/Working|Completed/i); + + const evidence = await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.terminal_status === "completed", + "the resumed turn did not complete", + ); + expect(evidence.connection_workers).toEqual( + expect.arrayContaining(["worker-a", "worker-b"]), + ); + expect(evidence.delivered_sequences).toEqual(evidence.emitted_sequences); + expect(evidence.duplicate_count).toBe(0); + expect(evidence.gap_count).toBe(0); + }); + + test("keeps cancellation pending until worker C acknowledges it", async ({ + page, + runtimeFixture, + }) => { + const scenario = await runtimeFixture.arm("cross_worker_cancel", { + owner_worker: "worker-a", + command_worker: "worker-c", + }); + await sendPrompt(page, scenario.prompt); + await expect(lifecycleStatus(page)).toContainText(/Working/i); + await page.getByRole("button", { name: /stop/i }).click(); + await expect(lifecycleStatus(page)).toContainText(/Stopping/i); + + const evidence = await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.terminal_status === "cancelled", + "the owner did not acknowledge cancellation", + ); + expect(evidence.command_workers).toContain("worker-c"); + await expect(lifecycleStatus(page)).toContainText(/Stopped/i); + }); + + test("replies through worker D and completes the same waiting turn", async ({ + page, + runtimeFixture, + }) => { + const scenario = await runtimeFixture.arm("cross_worker_reply", { + owner_worker: "worker-a", + command_worker: "worker-d", + }); + await sendPrompt(page, scenario.prompt); + await expect(lifecycleStatus(page)).toContainText(/Waiting for your answer/i); + + const answer = page.getByRole("textbox", { name: /answer/i }); + await answer.fill("Continue on the same turn"); + await page.getByRole("button", { name: /answer|submit/i }).click(); + await expect(lifecycleStatus(page)).toContainText(/Working|Completed/i); + + const evidence = await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.terminal_status === "completed", + "the answered turn did not complete", + ); + expect(evidence.command_workers).toContain("worker-d"); + expect(evidence.gap_count).toBe(0); + }); + + test("surfaces owner loss as retryable and regenerates elsewhere", async ({ + page, + runtimeFixture, + }) => { + const scenario = await runtimeFixture.arm("owner_loss", { + owner_worker: "worker-a", + recovery_worker: "worker-b", + }); + await sendPrompt(page, scenario.prompt); + await expect(lifecycleStatus(page)).toContainText(/Working/i); + await runtimeFixture.act(scenario.scenario_id, "kill_owner"); + await expect(lifecycleStatus(page)).toContainText(/Response interrupted/i, { + timeout: 45_000, + }); + + const failed = await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.failure_code === "worker_lost", + "owner loss was not recovered into a stable failure", + ); + expect(failed.retryable).toBe(true); + await page.getByRole("button", { name: /retry|regenerate/i }).click(); + await expect(lifecycleStatus(page)).toContainText(/Working|Completed/i); + await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.terminal_status === "completed" && value.recovery_worker === "worker-b", + "regeneration did not move to the recovery worker", + ); + }); + + test("reloads mid-stream and replays only events after the saved cursor", async ({ + page, + runtimeFixture, + }) => { + const scenario = await runtimeFixture.arm("reload_replay", { + owner_worker: "worker-a", + reload_worker: "worker-b", + }); + await sendPrompt(page, scenario.prompt); + await expect(lifecycleStatus(page)).toContainText(/Working/i); + await runtimeFixture.act(scenario.scenario_id, "pause_after_checkpoint"); + await page.reload(); + await expect(lifecycleStatus(page)).toContainText(/Reconnecting|Working|Completed/i); + + const evidence = await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.terminal_status === "completed", + "the reloaded turn did not complete", + ); + expect(evidence.delivered_sequences).toEqual(evidence.emitted_sequences); + expect(evidence.duplicate_count).toBe(0); + expect(evidence.gap_count).toBe(0); + }); + + test("observing a turn through a non-owner never marks it failed", async ({ + page, + runtimeFixture, + }) => { + const scenario = await runtimeFixture.arm("foreign_observation", { + owner_worker: "worker-a", + observer_worker: "worker-d", + }); + await sendPrompt(page, scenario.prompt); + await runtimeFixture.act(scenario.scenario_id, "query_from_observer"); + await expect(lifecycleStatus(page)).not.toContainText(/Turn failed|Response interrupted/i); + + const evidence = await runtimeFixture.expectEvidence( + scenario.scenario_id, + (value) => value.terminal_status === "completed", + "foreign observation changed the turn lifecycle", + ); + expect(evidence.observed_states).not.toContain("failed"); + expect(evidence.owner_worker).toBe("worker-a"); + }); +}); + diff --git a/web/tests/e2e/turn-lifecycle.audit.ts b/web/tests/e2e/turn-lifecycle.audit.ts index 240303364..08c06c596 100644 --- a/web/tests/e2e/turn-lifecycle.audit.ts +++ b/web/tests/e2e/turn-lifecycle.audit.ts @@ -1,5 +1,7 @@ import { expect, test } from "@playwright/test"; +import { lifecycleStatus, sendPrompt } from "./fixtures/runtime"; + const integrationFixtureAvailable = process.env.DEEPTUTOR_TURN_E2E_FIXTURE === "1"; @@ -12,12 +14,9 @@ test.describe("v2 turn lifecycle", () => { test("keeps server-authoritative lifecycle states visible", async ({ page }) => { await page.goto("/"); - const composer = page.getByRole("textbox").last(); - await expect(composer).toBeVisible(); - await composer.fill("Explain replay-safe turns"); - await composer.press("Enter"); + await sendPrompt(page, "Explain replay-safe turns"); - const status = page.getByTestId("turn-status"); + const status = lifecycleStatus(page); await expect(status).toContainText(/queued|connecting/i); await expect(status).toContainText(/streaming|responding/i); await expect(status).toContainText(/waiting for input/i); @@ -30,12 +29,11 @@ test.describe("v2 turn lifecycle", () => { test("recovers without inventing a terminal failure", async ({ page }) => { await page.goto("/"); - await page.getByRole("textbox").last().fill("Start a long turn"); - await page.getByRole("textbox").last().press("Enter"); + await sendPrompt(page, "Start a long turn"); - const status = page.getByTestId("turn-status"); + const status = lifecycleStatus(page); await expect(status).toContainText(/streaming|responding/i); - await page.getByTestId("fixture-drop-socket").click(); + await page.getByRole("button", { name: /drop connection/i }).click(); await expect(status).toContainText(/recovering|reconnecting/i); await expect(status).not.toContainText(/failed/i); await expect(status).toContainText(/streaming|completed/i); @@ -43,11 +41,10 @@ test.describe("v2 turn lifecycle", () => { test("waits for cancellation acknowledgement", async ({ page }) => { await page.goto("/"); - await page.getByRole("textbox").last().fill("Start a cancellable turn"); - await page.getByRole("textbox").last().press("Enter"); + await sendPrompt(page, "Start a cancellable turn"); await page.getByRole("button", { name: /stop|cancel/i }).click(); - const status = page.getByTestId("turn-status"); + const status = lifecycleStatus(page); await expect(status).toContainText(/cancelling/i); await expect(status).toContainText(/cancelled/i); });