Files
pipelines/web/test/schedule-integration-browser.mjs
T

117 lines
11 KiB
JavaScript

// End-to-end saved schedules against a throwaway Go server/database. Human-only
// workflows and explicit titles/notify=off prevent provider turns/notifications.
// Only this fixture's private SQLite NextDue is advanced to exercise dispatch.
import assert from "node:assert/strict";
import { spawn, execFileSync } from "node:child_process";
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { resolve, join } from "node:path";
import net from "node:net";
import { PipelinesClient } from "../src/client.js";
import { PipelinesRepository } from "../src/repository.js";
import { validateServerUrl } from "../src/serverUrl.js";
import { launchChrome, eventually } from "./browser.mjs";
const arg=(name,fallback)=>{const i=process.argv.indexOf(name);return i<0?fallback:process.argv[i+1];};
const binary=arg('--server-binary');if(!binary)throw Error('--server-binary must name a current-source scratch binary');
const out=resolve(arg('--out','captures-schedule-integration'));await mkdir(out,{recursive:true});
const scratch=await mkdtemp(join(arg('--tmp-parent',tmpdir()),'schedule-integration-'));
const freePort=()=>new Promise(r=>{const s=net.createServer();s.listen(0,'127.0.0.1',()=>{const port=s.address().port;s.close(()=>r(port));});});
const serverPort=await freePort(),webPort=await freePort();
const source='# stage gate\n\n```prompt\nHuman-only scheduling fixture. Choose done.\n```\n\n```configs\ntype=human\n```\n\n```edges\ndone -> #success\nerror -> #failure\n```\n';
const fake=join(scratch,'opencode');await writeFile(fake,'#!/bin/sh\nprintf "%s\\n" "$*" >> "$PIPELINES_FAKE_LOG"\nexit 1\n',{mode:0o700});
for(const name of ['home','a','b','manual'])await mkdir(join(scratch,name));
const password=join(scratch,'endpoint-password');await writeFile(password,'fixture-only-password',{mode:0o600});
const env={...process.env,HOME:join(scratch,'home'),XDG_CONFIG_HOME:join(scratch,'config'),XDG_DATA_HOME:join(scratch,'data'),XDG_STATE_HOME:join(scratch,'state'),XDG_CACHE_HOME:join(scratch,'cache'),CODEX_HOME:join(scratch,'codex'),PIPELINES_OPENCODE:fake,PIPELINES_FAKE_LOG:join(scratch,'fake-cli.log'),PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE:password,PIPELINES_DEFAULT_MODEL:'fixture/model'};
env.PIPELINES_HARNESS_CONFIG=join(scratch,'no-operator-harness.json');
for(const key of Object.keys(env))if(key.startsWith('PIPELINES_NTFY')||key==='PIPELINES_PREFIX')delete env[key];
const db=join(scratch,'pipeline.db');
const server=spawn(resolve(binary),['-addr',`127.0.0.1:${serverPort}`,'-db',db,'-allow-authoring','-opencode-endpoint','http://127.0.0.1:1'],{cwd:scratch,env,stdio:['ignore','pipe','pipe']});
let serverLog='';server.stdout.on('data',d=>serverLog+=d);server.stderr.on('data',d=>serverLog+=d);
let proxy,browser,page,client;
const ownedRuns=[];
try {
await eventually(async()=>{try{return(await fetch(`http://127.0.0.1:${serverPort}/healthz`)).ok;}catch{return false;}},{timeout:15000,what:'scratch server'});
client=new PipelinesClient();
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(Error('scratch websocket timeout')),5000);client.addEventListener('state',e=>{if(e.detail.kind==='connected'){clearTimeout(timer);resolve();}});client.connect(validateServerUrl(`ws://127.0.0.1:${serverPort}/connect`));});
const repo=new PipelinesRepository(client);
const pipeline=await repo.submit('Reusable research fixture',source);
await repo.submit('No schedules fixture',source);
proxy=spawn(process.execPath,['web/serve.mjs','--host','127.0.0.1','--port',String(webPort),'--pipelines',`127.0.0.1:${serverPort}`],{cwd:resolve(import.meta.dirname,'../..'),env:{...env,PIPELINES_WEB_AUTH:'disabled'},stdio:'ignore'});
await eventually(async()=>{try{return(await fetch(`http://127.0.0.1:${webPort}/`)).ok;}catch{return false;}},{timeout:5000,what:'scratch browser proxy'});
browser=await launchChrome();page=await browser.openPage(`http://127.0.0.1:${webPort}/pipelines/${pipeline.id}`);
await page.waitForSelector('.schedule-add');
const add=async(name,prompt,workspace)=>{
await page.click('.schedule-add');await page.waitForSelector('.schedule-overlay[aria-label="Add schedule"]');
await page.fill('[name=name]',name);await page.fill('[name=prompt]',prompt);await page.fill('[name=workspace]',workspace);await page.fill('[name=timezone]','UTC');
await page.click('[name=enabled]');await page.click('.schedule-advanced summary');await page.fill('[name=notifyMode]','off');await page.fill('[name=title]',name+' future run');
await page.click('.schedule-footer button[type=submit]');
await eventually(()=>page.evaluate("!document.querySelector('.schedule-overlay[aria-label=\"Add schedule\"]')"),{timeout:5000,what:'saved schedule dialog'});
};
await add('Battery item','Research battery recycling',join(scratch,'a'));
await add('AI item','Research model evaluation',join(scratch,'b'));
let schedules=await repo.listSchedules(pipeline.id);assert.equal(schedules.length,2);
let a=schedules.find(s=>s.name==='Battery item'),b=schedules.find(s=>s.name==='AI item');
assert.notEqual(a.input.prompt,b.input.prompt);assert.equal(a.version,1);assert.equal(b.version,1);
await page.screenshot(join(out,'two-independent-items-desktop.png'));
await page.click('#filterToggle');await page.click('[data-pipeline-schedule=scheduled]');
assert.equal(await page.evaluate("document.querySelectorAll('#pipelineRows [data-pipeline-id]').length"),1);
await page.screenshot(join(out,'pipeline-has-schedules-filter.png'));
await page.click('#clearFilters');
await page.click(`[data-schedule-id="${a.id}"] button`);
await page.fill('[name=prompt]','Updated battery topic');
a=await repo.saveSchedule({...a,name:'Renamed externally'});
await page.click('.schedule-footer button[type=submit]');await page.waitForText('Your draft is preserved.');
assert.equal(await page.evaluate("document.querySelector('[name=prompt]').value"),'Updated battery topic');
await page.screenshot(join(out,'concurrent-edit-keeps-draft.png'));
await page.click('.schedule-footer button[type=button]');await page.click('.schedule-refresh');
await page.waitForText('Renamed externally');await page.click(`[data-schedule-id="${a.id}"] button`);await page.fill('[name=prompt]','Updated battery topic');await page.click('.schedule-footer button[type=submit]');
await eventually(()=>page.evaluate("!document.querySelector('.schedule-overlay[aria-label=\"Edit schedule\"]')"),{timeout:5000,what:'saved updated item'});
schedules=await repo.listSchedules(pipeline.id);a=schedules.find(s=>s.id===a.id);b=schedules.find(s=>s.id===b.id);
assert.equal(a.input.prompt,'Updated battery topic');assert.equal(b.input.prompt,'Research model evaluation');
const manualReply=await client.call({type:'run_pipeline',pipeline_id:pipeline.id,version:1,request_key:'manual-scope-fixture',input:{prompt:'Manual control'},workspace:join(scratch,'manual'),title:'Manual fixture run',notify_mode:'off',write_paths:['allowed.txt'],allow_tools:true});
const manual=manualReply.run_detail;ownedRuns.push(manual.id);
assert.equal(manual.scheduled,false);
await page.goto(`http://127.0.0.1:${webPort}/runs/${manual.id}`);await page.waitForSelector('.schedule-run');await page.click('.schedule-run');await page.waitForSelector('.schedule-overlay');
assert.equal(await page.evaluate("document.querySelector('[name=prompt]').value"),'Manual control');
assert.equal(await page.evaluate("document.querySelector('[name=title]').value"),'Manual fixture run');
assert.deepEqual(await page.evaluate("JSON.parse(document.querySelector('[name=writePaths]').value)"),['allowed.txt']);
await page.screenshot(join(out,'schedule-this-run-preserves-input-title-and-write-scope.png'));
await page.click('.schedule-footer button[type=button]');
assert.equal(await page.evaluate("document.activeElement.classList.contains('schedule-run')"),true);
const observed=[];
const scheduled=new Promise((resolve,reject)=>{
const timer=setTimeout(()=>reject(Error('fixture schedule did not dispatch')),12000);
client.addEventListener('frame',e=>{const f=e.detail.run_event;if(!f)return;observed.push(f);if(f.scheduled&&f.schedule_id===a.id){clearTimeout(timer);resolve(f.run_id);}});
});
repo.subscribeRuns();
a=await repo.saveSchedule({...a,enabled:true,notify_mode:'off',title:'Timer fixture run'});
// Fixture-only clock advancement: this database was created above and is
// never selected from a live URL, environment override or user data path.
execFileSync('python3',['-c',"import sqlite3,sys,datetime; d=sqlite3.connect(sys.argv[1]); due=(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(seconds=2)).replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%SZ'); d.execute('UPDATE saved_schedules SET next_due=? WHERE id=?',(due,int(sys.argv[2]))); d.commit()",db,String(a.id)]);
const runId=await scheduled;ownedRuns.push(runId);
const fired=await repo.getRun(runId);assert.equal(fired.scheduled,true);assert.equal(fired.schedule_id,a.id);assert.equal(fired.input.prompt,a.input.prompt);
assert.ok(observed.filter(f=>f.run_id===runId).every(f=>f.scheduled&&f.schedule_id===a.id),'origin must exist on the very first frame');
await page.resize(390,844);await page.goto(`http://127.0.0.1:${webPort}/runs`);await page.waitForSelector(`[data-run-id="${runId}"]`);
await page.click('#runFilterBtn');await page.click('[data-run-schedule=scheduled]');
assert.equal(await page.evaluate("document.querySelectorAll('.run-row').length"),1);assert.equal(await page.evaluate("document.querySelector('.run-row').dataset.runId"),String(runId));
await page.screenshot(join(out,'scheduled-run-filter-mobile.png'));
await page.click('#runFilterBtn');await page.click('[data-run-schedule=unscheduled]');
assert.equal(await page.evaluate("document.querySelectorAll('.run-row').length"),1);assert.equal(await page.evaluate("document.querySelector('.run-row').dataset.runId"),String(manual.id));
await page.screenshot(join(out,'manual-run-on-scheduled-pipeline-mobile.png'));
const beforeDelete=await repo.listSchedules(pipeline.id);for(const entry of beforeDelete)await repo.deleteSchedule(entry.id,entry.revision);
const history=await repo.getRun(runId);assert.equal(history.scheduled,true);assert.equal(history.schedule_id,a.id);
const detail=await repo.getPipeline(pipeline.id,1);assert.equal(detail.source,source);assert.equal(detail.schedule_count,0);assert.equal(detail.scheduled,false);
assert.equal((await repo.getRun(manual.id)).scheduled,false);
const cliLog=await readFile(join(scratch,'fake-cli.log'),'utf8').catch(()=> '');assert.doesNotMatch(cliLog,/prompt|generate/);
console.log('PASS: actual web/API integration, two independent saved items, CAS draft safety, genuine timer-origin first frames vs manual runs, both filters, immutable workflow source and history after deletion. Human-only fixture; no provider calls.');
for(const id of ownedRuns)await repo.cancelRun(id).catch(()=>{});
} catch(error) {
if(page){await page.screenshot(join(out,'failure.png'));console.error(await page.evaluate('document.body.innerText'));}
console.error(serverLog.slice(-5000));throw error;
} finally {
client?.disconnect();await browser?.close();
for(const process of [proxy,server])if(process&&process.exitCode===null&&process.signalCode===null){const exited=new Promise(resolve=>process.once('exit',resolve));process.kill('SIGTERM');await exited;}
await rm(scratch,{recursive:true,force:true});
}