Files
maestro/ui/e2e/schedules.spec.ts
T
oss-sync 57702b4f34
CI / build-and-test (push) Canceled after 0s
sync: update from private repo (2336949a)
2026-09-17 11:29:31 +00:00

183 lines
8.6 KiB
TypeScript

import { test, expect, type Page } from '@playwright/test';
import { openSpaceTab } from './helpers/spaceTabs';
// ── Automations (scheduled task CRUD) E2E ─────────────────────────────────────
//
// REQUIRES `npm run test:e2e` + a running server (ui/playwright.config.ts boots
// the real orchestrator with auth OFF → synthetic 'local' user). This does NOT
// run in the sandbox — there is no live server here.
//
// WHERE the page lives: commit e6733e58 retired the top-level Automations tab
// and moved automations inside each workspace — `?page=schedules` now falls back
// to the spaces view, so the old `page.goto('/ui?page=schedules')` never reached
// the page and both tests in this file had been failing since (issue #1338). The
// screen itself is unchanged: SpaceDetail renders the SAME SchedulesPage
// component under its 自動実行 tab, which lives in the 「その他」 overflow menu
// (helpers/spaceTabs.ts). So this spec drives it there instead, and the
// selectors below still hold. Neither the workspaces view nor the automations
// screen is auth-gated. The cronForm lib is partially unit-covered; this proves
// the create/list/edit UI wiring that has no other e2e.
//
// Selector grounding (read from SchedulesPage.tsx + i18n locales en/ja):
// - List: a "New automation" / "新しい自動実行" button (list.new) opens the editor.
// - Editor: a Title input (placeholder "Weekly news roundup" / "週次ニュースまとめ"),
// a Prompt textarea (placeholder "Enter the prompt to run" / "実行するプロンプトを入力"),
// and a submit button "Create"/"作成" (gated on a non-empty prompt body).
// - Each schedule renders as a list <button> showing its title.
// Because these controls are i18n-text driven (no test-ids) and the runner's
// browser locale decides en vs ja, text selectors below use bilingual regexes.
// Backend state is verified through GET /api/scheduled-tasks?spaceId=… — the
// same endpoint the space-scoped page reads.
const BENIGN_PATHS = new Set([
'/api/auth/me',
'/api/users/me/orgs',
'/api/mcp/connections',
'/api/mcp/servers',
'/api/mcp/user-servers',
'/api/ssh/connections',
]);
const BENIGN_ASSET = /\.(ico|png|svg|map|webmanifest|json)$/i;
// The workspace opens on its chat tab before we reach 自動実行; those two probes
// 404 on a workspace with no console session / browser session (same allowlist
// as spaces.spec.ts and calendar.spec.ts).
const BENIGN_PATH_RE =
/\/api\/local\/tasks\/\d+\/console\/status$|\/api\/local\/browser\/sessions\/task-session\/\d+$/;
function trackFatalErrors(page: Page): string[] {
const fatalErrors: string[] = [];
page.on('pageerror', (err) => fatalErrors.push(`pageerror: ${err.message}`));
page.on('response', (res) => {
if (res.status() >= 400) {
const { pathname } = new URL(res.url());
if (!BENIGN_ASSET.test(pathname) && !BENIGN_PATHS.has(pathname) && !BENIGN_PATH_RE.test(pathname)) {
fatalErrors.push(`HTTP ${res.status()} ${res.url()}`);
}
}
});
return fatalErrors;
}
/**
* Create a case workspace and open it. Returns its id so the spec can scope the
* backend reads to it (mirrors the same helper in calendar.spec.ts).
*/
async function createAndOpenCaseSpace(page: Page, label: string): Promise<string> {
await page.goto('/ui');
await page.getByTestId('nav-spaces').click();
const rail = page.getByTestId('space-rail');
await expect(rail).toBeVisible();
await page.getByTestId('create-space-btn').click();
const titleInput = page.getByTestId('space-title-input');
await expect(titleInput).toBeVisible();
const caseTitle = `${label}-${Date.now()}`;
await titleInput.fill(caseTitle);
await page.getByTestId('space-form-submit').click();
await expect(titleInput).toHaveCount(0);
const caseRow = rail
.locator('[data-testid="space-row"][data-space-kind="case"]')
.filter({ hasText: caseTitle });
await expect(caseRow).toBeVisible();
const spaceId = await caseRow.getAttribute('data-space-id');
expect(spaceId, 'created space id').toBeTruthy();
await caseRow.click();
await expect(page.getByTestId('space-detail')).toBeVisible();
return spaceId as string;
}
/**
* Reopen an existing workspace's 自動実行 tab from a cold load. The open tab is
* component state, not a URL param, so the reload lands on 会話 and the overflow
* menu has to be walked again.
*/
async function reopenSpaceSchedules(page: Page, spaceId: string): Promise<void> {
await page.goto(`/ui?space=${encodeURIComponent(spaceId)}`);
await expect(page.getByTestId('space-detail')).toBeVisible();
await openSpaceTab(page, 'schedules');
}
// Bilingual matchers (the runner's browser locale picks en or ja; the harness
// pins no localStorage language, so navigator decides).
const NEW_AUTOMATION = /New automation|新しい自動実行/;
const SUBMIT_CREATE = /^(Create|作成)$/;
const TITLE_PLACEHOLDER = /Weekly news roundup|週次ニュースまとめ/;
const PROMPT_PLACEHOLDER = /Enter the prompt to run|実行するプロンプトを入力/;
const scheduleTitle = `e2e-schedule-${Date.now()}`;
test('create an automation via the UI, then see it listed and persisted', async ({ page }) => {
const fatalErrors = trackFatalErrors(page);
const spaceId = await createAndOpenCaseSpace(page, 'E2E自動実行');
await openSpaceTab(page, 'schedules');
// Open the editor.
await page.getByRole('button', { name: NEW_AUTOMATION }).first().click();
// Fill the editor: title + prompt (the submit button is gated on a non-empty
// prompt body). Default scheduleType is 'daily', so no extra cron input needed.
await page.getByPlaceholder(TITLE_PLACEHOLDER).fill(scheduleTitle);
await page.getByPlaceholder(PROMPT_PLACEHOLDER).fill('summarize today, e2e');
const submit = page.getByRole('button', { name: SUBMIT_CREATE });
await expect(submit).toBeEnabled({ timeout: 15_000 });
await submit.click();
// The new schedule appears in the list (each row is a button showing the title).
await expect(page.getByRole('button', { name: new RegExp(scheduleTitle) })).toBeVisible({ timeout: 15_000 });
// Backend: it was persisted via POST /api/scheduled-tasks (the same endpoint
// the list reads). A default daily schedule yields a cron expression.
let createdId = 0;
await expect
.poll(async () => {
const res = await page.request.get(`/api/scheduled-tasks?spaceId=${encodeURIComponent(spaceId)}`);
if (!res.ok()) return [];
const data = (await res.json()) as Array<{ id: number; title: string; cronExpression?: string }> | { tasks?: Array<{ id: number; title: string }> };
const list = Array.isArray(data) ? data : (data.tasks ?? []);
const match = list.find((t) => t.title === scheduleTitle);
if (match) createdId = match.id;
return list.map((t) => t.title);
}, { timeout: 15_000 })
.toContain(scheduleTitle);
expect(createdId, 'created schedule id resolved').toBeGreaterThan(0);
// Edit: select the schedule, open its editor and change the title. Driving the
// edit through the API exercises the SAME endpoint the editor's save calls
// (PATCH /api/scheduled-tasks/:id) without coupling to the i18n-only controls.
const editedTitle = `${scheduleTitle}-edited`;
const patched = await page.request.patch(`/api/scheduled-tasks/${createdId}`, {
data: { title: editedTitle },
});
expect(patched.ok(), 'edit schedule title').toBeTruthy();
// The list reflects the edit after a fresh load (refetches /api/scheduled-tasks).
await reopenSpaceSchedules(page, spaceId);
await expect(page.getByRole('button', { name: new RegExp(editedTitle) })).toBeVisible({ timeout: 15_000 });
expect(fatalErrors, `fatal errors:\n${fatalErrors.join('\n')}`).toEqual([]);
});
// Negative/visibility: opening the editor without a prompt body keeps the submit
// button disabled (the create gate). Proves the form validation wiring.
test('the create button stays disabled until a prompt is entered', async ({ page }) => {
const fatalErrors = trackFatalErrors(page);
await createAndOpenCaseSpace(page, 'E2E自動実行ガード');
await openSpaceTab(page, 'schedules');
await page.getByRole('button', { name: NEW_AUTOMATION }).first().click();
// With only a title (no prompt body) the submit is disabled.
await page.getByPlaceholder(TITLE_PLACEHOLDER).fill('no-prompt-schedule');
const submit = page.getByRole('button', { name: SUBMIT_CREATE });
await expect(submit).toBeDisabled();
// Typing a prompt enables it.
await page.getByPlaceholder(PROMPT_PLACEHOLDER).fill('now there is a prompt');
await expect(submit).toBeEnabled();
expect(fatalErrors, `fatal errors:\n${fatalErrors.join('\n')}`).toEqual([]);
});