EnergyVenom's picture
Astra: a restart never loses finished work; failed screen reads say what Fusion showed (90c64a4)
0108bcf verified
Raw History Blame Contribute Delete
12.3 kB
// Screen exploration on a real Oracle Fusion pod, the scout's way: signs in once (up to 4 browsers share that session,
// each reading its own areas), and for each business area of the plan
// finds the area's group on the pod's own home page, opens it, and takes what THIS pod and user offer: its quick
// actions (Create Invoice, Create Transaction ...) and its work areas' Tasks lists. It picks the tasks a test starts
// from (create, then manage, then the rest; no imports, reports or batch processes), up to the plan's limit, and
// records each one's screen inventory (labels, buttons, menus, sections; never values). Leaves every page with
// Cancel: nothing is ever saved on the pod. The plan only names likely groups and pages; the pod decides.
//
// FUSION_BASE_URL=... FUSION_USERNAME=... FUSION_PASSWORD=... npx tsx scripts/explore-fusion.ts PLAN.json --out-dir DIR
//
// PLAN.json: {"areas": [{"code": "AR", "groups": ["Receivables"], "pages": ["Billing"], "max_tasks": 4}]}
// Prints one line per step ("[explore] ..."), "AREA <json>" as each area is finished, then "EXPLORED <json>" as its last line: per area, what each group showed,
// each work area's tasks (or why not), each captured file and each task that could not be read.
import * as fs from 'fs';
import * as path from 'path';
import { chromium, type Browser, type BrowserContext } from '@playwright/test';
import { assertNoData, captureScreen, screenSlug } from '../src/fusion/capture';
import { FusionUi } from '../src/fusion/ui';
interface PlanArea { code: string; groups?: string[]; pages?: string[]; key_tasks?: string[]; max_tasks?: number }
interface WorkArea { navigator: string; tasks: string[]; error?: string; home_links?: string[]; group_links?: string[]; navigator_links?: string[] }
interface AreaResult { code: string; work_areas: WorkArea[]; captured: { task: string; file: string }[]; failed: { task: string; error: string }[] }
const log = (m: string) => console.log(`[explore] ${m}`);
const short = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 240);
// tasks a test would start from, best first: the area's key business tasks (catalog key_tasks, in their order), then
// by verb; anything else comes after, in the panel's order
const RANK = [/^create\b/i, /^manage\b/i, /^(enter|submit|record|add)\b/i, /^(review|view|search)\b/i];
const SKIP = /\b(report|reports|analytics|import|upload|spreadsheet|schedule|process|run|purge|export|setup|set up)\b/i;
export function pickTasks(tasks: string[], max: number, key: string[] = []): string[] {
const keys = key.map((k) => k.trim().toLowerCase());
const usable = tasks.filter((t) => keys.includes(t.trim().toLowerCase()) || !SKIP.test(t));
const rank = (t: string) => {
const k = keys.indexOf(t.trim().toLowerCase());
if (k >= 0) return k - keys.length; // before every verb rank
const i = RANK.findIndex((r) => r.test(t)); return i < 0 ? RANK.length : i;
};
return usable.map((t, i) => ({ t, i })).sort((a, b) => rank(a.t) - rank(b.t) || a.i - b.i).slice(0, max).map((x) => x.t);
}
// what an area's group shows that is a work area rather than a quick action or a dashboard
const NOT_A_PAGE = /\b(dashboard|workflow|agent|spreadsheet|report|guided)\b/i;
const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
/** One area, discovered on the pod itself: its home page group(s), the quick actions they show, the work areas and
* their Tasks lists. Returns the chosen task paths, best first ("Group > Action" or "Group > Page > Task"). */
async function discoverArea(ui: FusionUi, area: PlanArea, res: AreaResult, groupsOnHome: string[]): Promise<string[]> {
const wanted = area.groups ?? [];
const groups = groupsOnHome.filter((g) => wanted.some((w) => same(g, w)));
if (!groups.length) {
res.work_areas.push({ navigator: wanted.join(' | '), tasks: [], error: 'no such group on the home page for this user', home_links: groupsOnHome });
log(`${area.code}: no group ${wanted.join(' / ')} on the home page`);
return [];
}
const quick: string[] = [];
const paths: string[] = [];
for (const group of groups) {
await ui.goHome();
const before = await ui.visibleNames(250).catch(() => [] as string[]);
const shown = await ui.openGroup(group);
const revealed = shown.filter((n) => !before.includes(n) || (area.pages ?? []).some((p) => same(p, n)));
const actions = revealed.filter((n) => RANK.slice(0, 3).some((r) => r.test(n)) && !SKIP.test(n));
const pages = [...(area.pages ?? []).map((p) => shown.find((n) => same(n, p))).filter((x): x is string => !!x),
...revealed.filter((n) => !actions.includes(n) && !NOT_A_PAGE.test(n) && !RANK.some((r) => r.test(n)))]
.filter((v, i, a) => a.indexOf(v) === i).slice(0, 2);
res.work_areas.push({ navigator: group, tasks: actions, group_links: revealed });
log(`${area.code}: ${group} shows ${actions.length} quick action(s); work areas ${pages.join(', ') || '(none)'}`);
for (const a of actions) quick.push(`${group} > ${a}`);
for (const p of pages) {
try {
await ui.openWorkArea(group, p);
const tasks = await ui.taskNames();
res.work_areas.push({ navigator: `${group} > ${p}`, tasks });
log(`${area.code}: ${group} > ${p} has ${tasks.length} task(s)`);
for (const t of tasks) paths.push(`${group} > ${p} > ${t}`);
} catch (e) {
res.work_areas.push({ navigator: `${group} > ${p}`, tasks: [], error: short(e) });
log(`${area.code}: ${group} > ${p}: no Tasks list (${short(e)})`);
}
}
}
// best first by the task's own name; a task reached two ways is read once (the quick action first)
const byName = new Map<string, string>();
for (const p of [...quick, ...paths]) {
const n = p.split('>').pop()!.trim().toLowerCase();
if (!byName.has(n)) byName.set(n, p);
}
const names = pickTasks(Array.from(byName.values()).map((p) => p.split('>').pop()!.trim()), area.max_tasks ?? 4, area.key_tasks ?? []);
return names.map((n) => byName.get(n.toLowerCase())!);
}
// an area whose tasks keep failing is one this user cannot open: its remaining tasks are left after this many in a row
const FAILS_IN_A_ROW = 3;
// list fields of a screen whose choices are read (required ones first); each takes a few seconds
const LISTS_PER_SCREEN = 8;
/** One area: find its tasks on the pod, then read each one, within the area's time. */
async function readArea(ui: FusionUi, area: PlanArea, groupsOnHome: string[], outDir: string, minutes: number): Promise<AreaResult> {
const res: AreaResult = { code: area.code, work_areas: [], captured: [], failed: [] };
const deadline = Date.now() + minutes * 60_000;
let chosen: string[] = [];
try {
chosen = await discoverArea(ui, area, res, groupsOnHome);
} catch (e) {
res.work_areas.push({ navigator: (area.groups ?? []).join(' | '), tasks: [], error: short(e) });
log(`${area.code}: discovery failed: ${short(e)}`);
}
let fails = 0;
for (const task of chosen) {
if (Date.now() > deadline || fails >= FAILS_IN_A_ROW) {
const why = fails >= FAILS_IN_A_ROW
? `not read: the ${FAILS_IN_A_ROW} tasks before it failed, so this user probably cannot open this area`
: `not read: the ${minutes} minutes for this area were used up`;
res.failed.push({ task, error: why });
log(`${area.code}: ${task} ${why}`);
continue;
}
try {
log(`${area.code}: reading ${task}`);
await ui.openPath(task);
const inv = await captureScreen(ui.page, task, { prepare: true, log: (m) => log(` ${area.code}: ${m}`) });
assertNoData(inv);
const file = path.join(outDir, `${screenSlug(task)}.json`);
fs.writeFileSync(file, JSON.stringify(inv, null, 2) + '\n');
res.captured.push({ task, file });
// the choices this user is offered in the screen's lists: test data when the pod's records give none (a ledger,
// a journal source). Kept apart from the inventory (labels only, what the AI sees), in "<slug>.values"
const choices: Record<string, string[]> = {};
const lists = inv.fields.filter((f) => f.kind === 'list' || f.kind === 'lov')
.sort((a, b) => Number(b.required) - Number(a.required)).slice(0, LISTS_PER_SCREEN);
for (const f of lists) {
const got = await ui.listChoices(f.label).catch(() => [] as string[]);
if (got.length) choices[f.label] = got;
}
if (Object.keys(choices).length) fs.writeFileSync(path.join(outDir, `${screenSlug(task)}.values`), JSON.stringify(choices) + '\n');
fails = 0;
log(`${area.code}: ${task}: ${inv.fields.length} fields, ${inv.buttons.length} buttons, ${Object.keys(inv.menus).length} menus`);
} catch (e) {
// what Fusion showed instead (its page title, the headings of any open dialogs), so a failed read says why
const title = await ui.page.title().catch(() => '');
const dialogs = await ui.page.getByRole('dialog').filter({ visible: true }).evaluateAll((ds) =>
ds.map((d) => (d.getAttribute('aria-label') || (d as HTMLElement).innerText || '').replace(/\s+/g, ' ').trim().slice(0, 80))).catch(() => [] as string[]);
const seen = `page "${title.slice(0, 80)}"` + (dialogs.length ? `, dialog(s): ${dialogs.filter(Boolean).join(' | ')}` : ', no dialog');
res.failed.push({ task, error: `${short(e)} (Fusion showed ${seen})` });
fails++;
log(`${area.code}: ${task} failed: ${short(e)} (Fusion showed ${seen})`);
}
await ui.cancelPage().catch(() => {}); // leave without saving, whatever happened
}
return res;
}
async function newUi(browser: Browser, session?: Awaited<ReturnType<BrowserContext['storageState']>>): Promise<FusionUi> {
const page = await (await browser.newContext({ viewport: { width: 1440, height: 900 }, storageState: session })).newPage();
page.setDefaultTimeout(60_000);
page.setDefaultNavigationTimeout(120_000);
return new FusionUi(page);
}
async function main() {
const argv = process.argv.slice(2);
const planFile = argv.find((a) => !a.startsWith('--'));
const outDir = path.resolve(argv[argv.indexOf('--out-dir') + 1] || '.');
if (!planFile || !argv.includes('--out-dir')) throw new Error('usage: explore-fusion.ts PLAN.json --out-dir DIR');
const plan = JSON.parse(fs.readFileSync(planFile, 'utf8')) as { areas: PlanArea[]; workers?: number; area_minutes?: number };
fs.mkdirSync(outDir, { recursive: true });
const results = new Map<string, AreaResult>();
const browser = await chromium.launch({ headless: true });
try {
const first = await newUi(browser);
log('signing in');
await first.signIn();
const groupsOnHome = await first.groupsOnHome();
log(`home page groups: ${groupsOnHome.length}`);
// more browsers share the one sign-in (its session cookies, held in memory only, never written to disk): Fusion
// serves several windows of one session side by side, and each reads its own areas
const workers = Math.max(1, Math.min(plan.workers ?? 1, 4, plan.areas.length));
const session = workers > 1 ? await first.page.context().storageState() : undefined;
const uis = [first, ...await Promise.all(Array.from({ length: workers - 1 }, () => newUi(browser, session)))];
if (workers > 1) log(`${workers} browsers read at the same time`);
const queue = [...plan.areas];
await Promise.all(uis.map(async (ui) => {
for (let area = queue.shift(); area; area = queue.shift()) {
const res = await readArea(ui, area, groupsOnHome, outDir, plan.area_minutes ?? 20);
results.set(area.code, res);
console.log(`AREA ${JSON.stringify(res)}`); // kept even if the read is cut off before the end
}
}));
} finally {
await browser.close().catch(() => {});
}
console.log(`EXPLORED ${JSON.stringify({ areas: plan.areas.map((a) => results.get(a.code)).filter(Boolean) })}`);
}
if (require.main === module) {
main().then(() => process.exit(0), (e) => { console.error(`[explore] failed: ${short(e)}`); process.exit(1); });
}