Files
CatoandClaude f1e5fbadcd test(planner): the planner is checked signed in on the live site; the E2E sign-in waits for the form (#1822)
* test(planner): the planner is checked signed in, on the live site

Linking a calendar was off in production for a day while unit tests stayed
green. This spec signs in as the E2E account and does what a person does:
a task due today shows in the calendar with its actions, an entry is added,
the account's own feed is linked by its iCal address and read, a public
service says when it is free, and a task is handed to a bot (or the reason
it cannot be is said). It removes what it made. Run by the daily E2E Auth
workflow and on dispatch.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvmcF5JN8LusW4FjQg

* ci(diag): temporary sign-in probe for the live E2E account

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvmcF5JN8LusW4FjQg

* test(planner): the live check hands a task to a bot it makes for the purpose; sign-in waits long enough

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvmcF5JN8LusW4FjQg

* test(e2e): a sign-in that does not land says what it was answered

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvmcF5JN8LusW4FjQg

* test(e2e): sign in only once the form has been taken over by React

All three attempts of the 16:20 UTC run stayed on /auth with 'Enter your
email address.' and no sign-in call: the fields were filled before
hydration and wiped by it, so the form was sent empty. The daily E2E Auth
run failed the same way at 12:07.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvmcF5JN8LusW4FjQg

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 17:43:03 +01:00

125 lines
5.2 KiB
JavaScript

// Playwright global setup to pre-authenticate and save storage state for tests.
// Requires environment variables: E2E_USER_EMAIL and E2E_USER_PASSWORD
// (legacy E2E_TEST_USER_* also accepted).
// If credentials are missing or login fails, setup falls back gracefully (no storageState).
const fs = require('fs');
const path = require('path');
const { chromium } = require('@playwright/test');
module.exports = async () => {
const baseURL = process.env.E2E_BASE_URL || 'http://localhost:3000';
const email = process.env.E2E_TEST_USER_EMAIL || process.env.E2E_USER_EMAIL;
const password = process.env.E2E_TEST_USER_PASSWORD || process.env.E2E_USER_PASSWORD;
const authDir = path.resolve(__dirname, '..', '.auth');
const storagePath = path.join(authDir, 'user.json');
// Ensure auth directory exists
fs.mkdirSync(authDir, { recursive: true });
if (!email || !password) {
console.warn('[global-setup] Missing E2E_USER_EMAIL/E2E_USER_PASSWORD; skipping pre-auth.');
return;
}
// The sign-in page can hold two email inputs for a moment (the form is drawn
// twice around hydration, one copy hidden), and a bare
// `locator('input[type="email"]')` then throws a strict-mode violation.
// That silently left every spec without a session: "bounced to sign-in"
// for the Cat chat smoke (PR run 2026-10-27 22:42), while the same specs
// passed on the next run. Take the visible one, and try three times.
const attempts = 3;
let lastError;
for (let attempt = 1; attempt <= attempts; attempt++) {
console.log(`[global-setup] Starting login flow (attempt ${attempt}/${attempts})...`);
const browser = await chromium.launch();
const page = await browser.newPage();
// What the sign-in itself answered, for when it does not land: the
// status and error words of the token call, never a token.
const answers = [];
page.on('response', async res => {
if (/\/auth\/v1\/token/.test(res.url())) {
let words = '';
if (res.status() >= 400) {
try {
const body = JSON.parse(await res.text());
words = String(body.error_description || body.msg || body.error || '').slice(0, 160);
} catch {
words = '';
}
}
answers.push(`${res.status()} ${words}`.trim());
}
});
try {
await page.goto(`${baseURL}/auth?mode=login`, { waitUntil: 'domcontentloaded' });
const emailInput = page.locator('input[type="email"]:visible').first();
await emailInput.waitFor({ state: 'visible', timeout: 15000 });
// The form is server-drawn and then taken over by React. Words typed
// before that moment are wiped when it takes over, and the form was
// then sent with an empty address ("Enter your email address.", no
// sign-in call at all): all three attempts of 15 Nov 2026 16:20 UTC.
// So: type, wait a beat, and type again until both fields have kept
// what was typed.
// React marks the nodes it has taken over; wait for that mark first.
await page
.waitForFunction(
() =>
[...document.querySelectorAll('input[type="email"]')].some(el =>
Object.keys(el).some(key => key.startsWith('__reactProps'))
),
null,
{ timeout: 20000 }
)
.catch(() => undefined);
const passwordInput = page.locator('input[type="password"]:visible').first();
for (let i = 0; i < 20; i++) {
await emailInput.fill(email);
await passwordInput.fill(password);
await page.waitForTimeout(500);
const kept =
(await emailInput.inputValue()) === email &&
(await passwordInput.inputValue()) === password;
if (kept && i > 0) {
break;
}
}
await page.locator('form button[type="submit"]:visible').first().click();
// Wait for a successful redirect to an authenticated route
await page.waitForURL(/\/(dashboard|timeline|onboarding)/, { timeout: 20000 });
console.log('[global-setup] Login success. Saving storage state...');
await page.context().storageState({ path: storagePath });
console.log(`[global-setup] Storage state saved to ${storagePath}`);
return;
} catch (err) {
lastError = err;
console.warn(`[global-setup] Login attempt ${attempt} failed:`, err?.message || err);
const shown = await page
.locator('[role="alert"]')
.allInnerTexts()
.catch(() => []);
console.warn(
`[global-setup] stayed at ${page.url().split('?')[0]}; sign-in answered: ${answers.join(', ') || 'nothing'}; page said: ${
shown
.map(t => t.replace(/\s+/g, ' ').slice(0, 160))
.filter(Boolean)
.join(' | ') || 'nothing'
}`
);
} finally {
await browser.close();
}
}
// Without a session every signed-in spec fails with a misleading "bounced to
// sign-in". In CI, where the credentials exist, say so here instead.
if (process.env.CI) {
throw new Error(`[global-setup] Could not sign in as the E2E account: ${lastError?.message}`);
}
console.warn('[global-setup] Login failed or app not running. Proceeding without storageState.');
};