EnergyVenom's picture
Patchwise Agent Studio: Oracle AI Agent Studio cycles
af1bee9 verified
Raw History Blame Contribute Delete
12.9 kB
// Live view ("Watch the test") hook for the co-worker executor. MOCK app only.
//
// Gated on FPT_LIVE_VIEW_DIR. When the variable is unset NOTHING here runs: no CDP session, no listeners, no files, so
// the plain `npm test` baseline is unchanged. When set (by coworker/adapters/playwright.py for a run with live view on),
// the hook drops two small files into that folder, always atomically (temp file, then rename):
// frame.jpg the latest Chromium screencast frame only (never a history)
// status.json { ts, pw_run_id, attempt, scenario_id, title, page_title, path, status: running|passed|failed,
// action, action_n, masked, ... } (action = the current browser action in plain words)
// Sign-in screens are never shown: frame writing is suspended at every navigation until the page has been checked for
// a password field, and stays off while one is present (status.masked = true). Typed passwords are never captioned.
// plus failed.jpg: the last frame of the most recent FAILED scenario (overwritten; removed with the folder).
// The backend serves frame.jpg as MJPEG. The test process gets no network path and no token (single-egress rule).
// Every error is swallowed and disables the hook for the rest of the test: live view must never change an outcome.
import * as fs from 'fs';
import * as path from 'path';
import type { CDPSession, Page, TestInfo } from '@playwright/test';
const MIN_FRAME_GAP_MS = 500; // <= 2 frames per second on disk
const FALLBACK_SHOT_MS = 1000; // page.screenshot fallback only when no CDP session can be created
const MAX_WRITE_ERRORS = 20;
const CASE_TAG = /^@?([A-Z][A-Z0-9]{1,5}-[A-Z0-9-]+)$/;
interface Status {
ts: string; pw_run_id: string | null; attempt: string | null; chunk: string | null; scenario_id: string | null; title: string;
page_title: string; path: string; status: 'running' | 'passed' | 'failed' | 'skipped'; frame_source: 'screencast' | 'screenshot' | 'none';
done_ids: string[]; counts: { passed: number; failed: number; skipped: number };
recent: { scenario_id: string | null; title: string; status: string }[];
last_failed: { scenario_id: string | null; title: string; ts: string } | null;
action?: string | null; action_n?: number; masked?: boolean;
}
export const liveViewDir = (): string | null => process.env.FPT_LIVE_VIEW_DIR || null;
function writeAtomic(dir: string, name: string, data: Buffer | string): boolean {
const tmp = path.join(dir, `.${name}.${process.pid}.tmp`);
try {
fs.writeFileSync(tmp, data);
fs.renameSync(tmp, path.join(dir, name)); // on Windows this can fail while a reader holds the file: skip that frame
return true;
} catch {
try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ }
return false;
}
}
function readStatus(dir: string): Status | null {
try { return JSON.parse(fs.readFileSync(path.join(dir, 'status.json'), 'utf8')) as Status; } catch { return null; }
}
function scenarioId(testInfo: TestInfo): string | null {
for (const t of testInfo.tags ?? []) { const m = CASE_TAG.exec(t); if (m) return m[1]; }
const m = /@([A-Z][A-Z0-9]{1,5}-[A-Z0-9-]+)/.exec(testInfo.title);
return m ? m[1] : null;
}
const cleanTitle = (t: string) => t.replace(/\s*@[\w-]+/g, '').replace(/^[A-Z][A-Z0-9]{1,5}-[A-Z0-9-]+\s+/, '').trim();
/** Per-test bookkeeping (start + result) in status.json. Returns the teardown callback, or null when live view is off. */
export function beginLiveStatus(testInfo: TestInfo): (() => void) | null {
const dir = liveViewDir();
if (!dir) return null;
try {
fs.mkdirSync(dir, { recursive: true });
const attempt = process.env.FPT_LIVE_VIEW_ATTEMPT || null;
const prev = readStatus(dir);
const keep = prev && prev.attempt === attempt ? prev : null; // counts continue across the chunks of ONE attempt
const st: Status = {
ts: new Date().toISOString(), pw_run_id: process.env.PW_RUN_ID || null, attempt, chunk: process.env.FPT_LIVE_VIEW_CHUNK || null,
scenario_id: scenarioId(testInfo), title: cleanTitle(testInfo.title), page_title: '', path: '', status: 'running', frame_source: 'none',
done_ids: keep?.done_ids ?? [], counts: keep?.counts ?? { passed: 0, failed: 0, skipped: 0 }, recent: keep?.recent ?? [],
last_failed: keep?.last_failed ?? null, action: null, action_n: 0, masked: false,
};
writeAtomic(dir, 'status.json', JSON.stringify(st));
return () => {
try {
const cur = readStatus(dir) ?? st;
const skipped = testInfo.status === 'skipped';
const ok = testInfo.status === testInfo.expectedStatus;
const result: 'passed' | 'failed' | 'skipped' = skipped ? 'skipped' : ok ? 'passed' : 'failed';
cur.status = result;
cur.ts = new Date().toISOString();
cur.counts[result] += 1;
if (cur.scenario_id && !cur.done_ids.includes(cur.scenario_id)) cur.done_ids.push(cur.scenario_id);
cur.recent = [{ scenario_id: cur.scenario_id, title: cur.title, status: result }, ...cur.recent].slice(0, 8);
if (result === 'failed') {
try {
fs.copyFileSync(path.join(dir, 'frame.jpg'), path.join(dir, `.failed.${process.pid}.tmp`));
fs.renameSync(path.join(dir, `.failed.${process.pid}.tmp`), path.join(dir, 'failed.jpg'));
cur.last_failed = { scenario_id: cur.scenario_id, title: cur.title, ts: cur.ts };
} catch { /* no frame for this scenario (API-only test): nothing to pin */ }
}
writeAtomic(dir, 'status.json', JSON.stringify(cur));
} catch { /* never affect the test */ }
};
} catch {
return null;
}
}
// ---- current action in plain words ---------------------------------------------------------------------------------
// The Locator action methods are wrapped ONCE per worker, only when live view is on. The wrapper tells the active
// recorder what is about to happen and then calls the original method unchanged; a recorder error is swallowed.
type Recorder = (method: string, locator: unknown, args: unknown[]) => void;
let recorder: Recorder | null = null;
const WRAPPED = Symbol.for('fpt.liveView.wrapped');
const ACTIONS = ['click', 'dblclick', 'fill', 'type', 'pressSequentially', 'selectOption', 'check', 'uncheck', 'press', 'setInputFiles'];
const SENSITIVE = /pass(word|code)?|secret|pin\b|token|otp/i;
const clip = (v: unknown, n = 40) => { const t = String(v ?? ''); return t.length > n ? `${t.slice(0, n)}…` : t; };
/** "getByRole('button', { name: 'Submit' })" -> { role: 'button', name: 'Submit' } (the LAST part of a chained locator). */
export function describeLocator(text: string): { role: string | null; name: string | null } {
let role: string | null = null;
let name: string | null = null;
const re = /getBy(Role|Label|Text|Placeholder|Title|AltText)\(\s*'((?:[^'\\]|\\.)*)'(?:\s*,\s*\{[^}]*?name:\s*'((?:[^'\\]|\\.)*)')?/g;
for (let m = re.exec(text); m; m = re.exec(text)) {
if (m[1] === 'Role') { role = m[2]; name = m[3] ?? null; } else { role = null; name = m[2]; }
}
return { role, name: name ? name.replace(/\\'/g, "'") : null };
}
/** One browser action as a sentence a consultant reads. Passwords and other secrets are never included. */
export function actionSentence(method: string, locatorText: string, args: unknown[], masked = false): string {
const { role, name } = describeLocator(locatorText);
const what = name ? `'${name}'` : role ? `the ${role}` : 'the field';
const secret = masked || SENSITIVE.test(name ?? '');
switch (method) {
case 'click': case 'dblclick': return name ? `Click ${what}${role && !['button', 'link'].includes(role) ? ` (${role})` : ''}` : `Click ${role ? `a ${role}` : 'the screen'}`;
case 'fill': case 'type': case 'pressSequentially': return secret ? 'Enter the sign-in details' : `Enter '${clip(args[0])}' in ${what}`;
case 'selectOption': return `Choose '${clip(typeof args[0] === 'object' ? JSON.stringify(args[0]) : args[0])}' in ${what}`;
case 'check': return `Tick ${what}`;
case 'uncheck': return `Untick ${what}`;
case 'press': return `Press ${clip(args[0], 20)}`;
case 'setInputFiles': return `Attach a file to ${what}`;
default: return `${method} ${what}`;
}
}
function wrapLocatorActions(page: Page): void {
const proto = Object.getPrototypeOf(page.locator('body')) as Record<string | symbol, unknown>;
if (!proto || proto[WRAPPED]) return;
for (const m of ACTIONS) {
const orig = proto[m];
if (typeof orig !== 'function') continue;
proto[m] = function wrapped(this: unknown, ...args: unknown[]) {
try { recorder?.(m, this, args); } catch { /* never affect the test */ }
return (orig as (...a: unknown[]) => unknown).apply(this, args);
};
}
proto[WRAPPED] = true;
}
/** Starts the screencast for this page. Returns the stop callback, or null when live view is off or could not start. */
export async function startLiveView(page: Page, _testInfo: TestInfo): Promise<(() => Promise<void>) | null> {
const dir = liveViewDir();
if (!dir) return null;
let disabled = false;
let lastWrite = 0;
let errors = 0;
let cdp: CDPSession | null = null;
let timer: NodeJS.Timeout | null = null;
let shooting = false;
let masked = false; // a password field is on the page: no frames
let suspended = false; // just navigated: no frames until the page has been checked
let actionN = 0;
const patch = (fields: Partial<Status>) => {
if (disabled) return;
const cur = readStatus(dir);
if (!cur) return;
writeAtomic(dir, 'status.json', JSON.stringify({ ...cur, ...fields, ts: new Date().toISOString() }));
};
const frame = (buf: Buffer) => {
const now = Date.now();
if (disabled || masked || suspended || now - lastWrite < MIN_FRAME_GAP_MS) return;
lastWrite = now;
if (writeAtomic(dir, 'frame.jpg', buf)) errors = 0;
else if (++errors >= MAX_WRITE_ERRORS) disabled = true;
};
const checkSignIn = () => {
if (disabled || page.isClosed()) return;
page.evaluate(() => !!document.querySelector('input[type="password"]')).then((has) => {
const changed = has !== masked;
masked = has;
suspended = false;
if (changed) patch({ masked });
}).catch(() => { /* page is navigating or closed: stay suspended until the next successful check */ });
};
const onNav = (f: { url(): string }) => {
if (disabled) return;
try {
if (f !== page.mainFrame()) return;
suspended = true;
checkSignIn();
let p = '';
try { p = new URL(f.url()).pathname; } catch { /* about:blank */ }
void page.title().then((t) => patch({ page_title: t, path: p })).catch(() => { /* page closed */ });
} catch { disabled = true; }
};
try {
fs.mkdirSync(dir, { recursive: true });
page.on('framenavigated', onNav);
page.on('domcontentloaded', checkSignIn);
page.on('load', checkSignIn);
wrapLocatorActions(page);
recorder = (method, locator, args) => {
if (disabled) return;
actionN += 1;
patch({ action: actionSentence(method, String(locator), args, masked), action_n: actionN });
};
try {
cdp = await page.context().newCDPSession(page);
cdp.on('Page.screencastFrame', (ev: { data: string; sessionId: number }) => {
void cdp?.send('Page.screencastFrameAck', { sessionId: ev.sessionId }).catch(() => { /* session gone */ });
try { frame(Buffer.from(ev.data, 'base64')); } catch { disabled = true; }
});
await cdp.send('Page.startScreencast', { format: 'jpeg', quality: 50, maxWidth: 960, everyNthFrame: 2 });
patch({ frame_source: 'screencast' });
} catch {
cdp = null; // not Chromium, or no CDP: periodic screenshots (each one blocks the page briefly, so only as a fallback)
patch({ frame_source: 'screenshot' });
timer = setInterval(() => {
if (disabled || shooting || page.isClosed()) return;
shooting = true;
page.screenshot({ type: 'jpeg', quality: 50, timeout: 2000 }).then(frame).catch(() => { /* busy page: skip */ }).finally(() => { shooting = false; });
}, FALLBACK_SHOT_MS);
timer.unref?.();
}
} catch {
disabled = true;
}
return async () => {
disabled = true;
recorder = null;
try { page.off('framenavigated', onNav); page.off('domcontentloaded', checkSignIn); page.off('load', checkSignIn); } catch { /* ignore */ }
if (timer) clearInterval(timer);
if (cdp) {
try { await cdp.send('Page.stopScreencast'); } catch { /* page already closed */ }
try { await cdp.detach(); } catch { /* ignore */ }
}
};
}