feat(web): manage independent schedules and restore recorded stage navigation

This commit is contained in:
2026-10-21 02:06:15 +01:00
parent 4ab49a2749
commit 1e4654381e
31 changed files with 843 additions and 52 deletions
+68
View File
@@ -0,0 +1,68 @@
// Run graph and Timeline must route to the identical recorded-visit pane.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root=resolve(dirname(fileURLToPath(import.meta.url)),"..");
const out=resolve(process.argv[2]??"captures-run-graph-visit");await mkdir(out,{recursive:true});
const html=`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${["design/tokens/tokens","base","shell","lists","run-detail","chat","graph","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main id="pane-main"></main></div>
<script type="module">
window.fixtureErrors=[];addEventListener('error',event=>fixtureErrors.push(event.message));
import {createModalController} from '/src/modal.js';
import {createDialogsView} from '/src/views/dialogs.js';
import {createRunDetailView} from '/src/views/runDetail.js';
import {createChatView} from '/src/views/chat.js';
const graph={stages:[{key:'plan',type:'model',prompt:'Plan',configs:{},edges:{success:'review'}},{key:'review',type:'model',prompt:'Review',configs:{},edges:{success:'#success',rejected:'plan',extra:'unvisited'}},{key:'unvisited',type:'model',prompt:'Unvisited',configs:{},edges:{success:'#success'}}]};
const steps=[{sequence:1,stage:'plan',status:'completed',outcome:'success',target:'review'},
{sequence:2,stage:'review',status:'completed',outcome:'rejected',target:'plan',session_id:'ses_old',control:{visit:1,max_visits:3}},
{sequence:3,stage:'plan',status:'completed',outcome:'success',target:'review'},
{sequence:4,stage:'review',status:'completed',outcome:'success',target:'#success',session_id:'ses_latest',control:{visit:2,max_visits:3}}];
const run={id:42,pipeline_id:7,version:3,name:'Review fixture',status:'succeeded',graph,steps};
const state={view:'runs',runDetail:run,selectedRunId:42,runTab:'graph',runStagePane:null,runStageSections:new Set()};
const modal=createModalController();window.routes=[];window.requests=[];
const rt={state,modal,views:{},pushRoute:r=>routes.push(r),repo:{getPipeline:async(id,version)=>{requests.push({id,version});return{id,version,graph,source:'# stage review\\n\\n~~~prompt\\nReview latest files.\\n~~~\\n'};}},renderContent:()=>paint()};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);
window.paint=()=>{state.runGraph?.unmount();document.querySelector('main').replaceChildren(rt.views.runDetail.renderRunDetail());modal.reconcile();};
window.tab=key=>{modal.closeAll();state.runStagePane=null;state.runTab=key;paint();};
window.visit=()=>state.runStagePane;paint();
</script>`;
const server=createServer(async(req,res)=>{try{const path=new URL(req.url,"http://fixture").pathname;if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));let browser,page;
try {
browser=await launchChrome();page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
for(const width of [390,1100]) {
await page.resize(width,844);await page.evaluate("tab('graph')");
await page.waitForSelector('.graph-node[data-key="review"]');
await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');
await page.click('.graph-node[data-key="review"]');await page.waitForSelector('.stage-pane');
assert.deepEqual(await page.evaluate('visit()'),{stageKey:'review',visitIndex:1});
const graphPane=await page.evaluate("document.querySelector('.stage-pane').textContent");
assert.match(graphPane,/ses_latest/);assert.doesNotMatch(graphPane,/ses_old/);
assert.equal(await page.evaluate('requests.length'),0,'graph click must not fetch the definition');
await page.screenshot(resolve(out,`run-graph-latest-visit-${width}.png`));
await page.pressKey('Escape');
await page.evaluate("tab('steps')");await page.click('.timeline-row[data-stage-key="review"][data-visit-index="1"]');await page.waitForSelector('.stage-pane');
assert.equal(await page.evaluate("document.querySelector('.stage-pane').textContent"),graphPane);
assert.deepEqual(await page.evaluate('routes.at(-1)'),{kind:'runStage',id:42,stageKey:'review',visit:1});
await page.screenshot(resolve(out,`timeline-same-visit-${width}.png`));
await page.pressKey('Escape');
}
await page.evaluate("tab('graph')");await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');await page.click('.graph-node[data-key="unvisited"]');await page.waitForSelector('.stage-pane');
assert.equal(await page.evaluate("document.querySelectorAll('.stage-pane .audit-open').length"),0);
assert.equal(await page.evaluate('requests.length'),0);
await page.screenshot(resolve(out,'unvisited-stage-no-fabricated-visit.png'));
await page.pressKey('Escape');
await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');
await page.click('.graph-node[data-key="review"]');await page.waitForSelector('.audit-open');await page.click('.audit-open');await page.click('[data-audit-tab="definition"]');
await page.waitForText('Review latest files.');assert.deepEqual(await page.evaluate('requests'),[{id:7,version:3}]);
await page.screenshot(resolve(out,'definition-remains-an-explicit-audit-tab.png'));
console.log('PASS: run graph opens the same latest recorded visit as Timeline, route/identity match, unvisited stages fabricate nothing, and definition remains an explicit pinned-version audit tab.');
} catch(error) {
if(page){await page.screenshot(resolve(out,'failure.png'));console.error(await page.evaluate('JSON.stringify({errors:fixtureErrors,visit:visit(),text:document.body.innerText})'));}
throw error;
} finally {await browser?.close();await new Promise(r=>server.close(r));}
+116
View File
@@ -0,0 +1,116 @@
// 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});
}
+60
View File
@@ -0,0 +1,60 @@
import test from "node:test";
import assert from "node:assert/strict";
import { pipelineScheduleState, runScheduleState, pipelineScheduleLabel, scheduledRunLabel } from "../src/scheduleOrigin.js";
import { filterPipelines, EMPTY_PIPELINE_FILTERS, pipelineFilterCount } from "../src/pipelines.js";
import { filterRuns, defaultRunFilters, runFiltersActiveCount } from "../src/runs.js";
import { foldRunEvent, foldRunEventDetail, newRunSummaryFromFrame } from "../src/runEvents.js";
test("pipeline schedule filters use independent configurations, including paused entries", () => {
const all=[{id:1,name:"Research",scheduled:true,schedule_count:2,enabled_schedule_count:0},{id:2,name:"Review",scheduled:false,schedule_count:0},{id:3,name:"Legacy",shape:{settings:{schedules:[{every:"24h"}]}}}];
assert.deepEqual(filterPipelines(all,{...EMPTY_PIPELINE_FILTERS,scheduled:"scheduled"},new Map(),false).map(x=>x.id),[1]);
assert.deepEqual(filterPipelines(all,{...EMPTY_PIPELINE_FILTERS,scheduled:"unscheduled"}).map(x=>x.id),[2]);
assert.equal(pipelineScheduleState(all[2]),null);
assert.equal(pipelineScheduleLabel(all[0]),"2 schedules");
});
test("a manual run of a scheduled pipeline is not a scheduled run", () => {
const all=[{id:1,pipeline_id:7,scheduled:true,schedule_id:9,schedule_name:"Batteries"},{id:2,pipeline_id:7,scheduled:false},{id:3,pipeline_id:7}];
assert.deepEqual(filterRuns(all,{...defaultRunFilters(),scheduled:"scheduled"}).map(x=>x.id),[1]);
assert.deepEqual(filterRuns(all,{...defaultRunFilters(),scheduled:"unscheduled"}).map(x=>x.id),[2]);
assert.equal(runScheduleState(all[2]),null);
assert.equal(scheduledRunLabel(all[0]),"Scheduled · Batteries");
assert.equal(scheduledRunLabel(all[1]),"");
});
test("schedule filtering is an independent AND facet and clears with the defaults", () => {
assert.equal(pipelineFilterCount({...EMPTY_PIPELINE_FILTERS,name:"x",presence:"has_runs",lastRunStatuses:["failed"],scheduled:"scheduled"}),4);
assert.equal(runFiltersActiveCount({...defaultRunFilters(),statuses:new Set(["failed"]),pipelineId:7,timeRange:"today",scheduled:"scheduled"}),4);
assert.equal(pipelineFilterCount(EMPTY_PIPELINE_FILTERS),0);
assert.equal(runFiltersActiveCount(defaultRunFilters()),0);
const all=[{id:1,pipeline_id:7,scheduled:true,status:"failed"},{id:2,pipeline_id:7,scheduled:true,status:"succeeded"},{id:3,pipeline_id:8,scheduled:true,status:"failed"}];
const filters={...defaultRunFilters(),pipelineId:7,statuses:new Set(["failed"]),scheduled:"scheduled"};
assert.deepEqual(filterRuns(all,filters).map(x=>x.id),[1]);
});
const start={run_id:12,pipeline_id:7,name:"Research",version:3,status:"queued",scheduled:true,schedule_id:9,schedule_name:"Batteries"};
test("a scheduled run appears from its first live frame and retains origin on sparse updates", () => {
const row=newRunSummaryFromFrame(start);
assert.equal(row.scheduled,true);assert.equal(row.schedule_id,9);
const next=foldRunEvent([row],{run_id:12,status:"running",scheduled:false}).runs[0];
assert.equal(next.scheduled,true);assert.equal(next.schedule_id,9);assert.equal(next.schedule_name,"Batteries");
const detail=foldRunEventDetail({...row,steps:[]},{run_id:12,status:"running"});
assert.equal(detail.scheduled,true);assert.equal(detail.schedule_id,9);
});
test("lifecycle events cannot retarget an established schedule provenance", () => {
const row=newRunSummaryFromFrame(start);
const next=foldRunEvent([row],{run_id:12,status:"running",scheduled:true,schedule_id:100,schedule_name:"Another item"}).runs[0];
assert.equal(next.schedule_id,9);assert.equal(next.schedule_name,"Batteries");
const terminal=foldRunEvent([next],{run_id:12,status:"succeeded",scheduled:false}).runs[0];
assert.equal(runScheduleState(terminal),true);
});
test("older frames without origin remain unknown rather than guessed as manual", () => {
const {scheduled,schedule_id,schedule_name,...old}=start;
const row=newRunSummaryFromFrame(old);
assert.equal(runScheduleState(row),null);
const manual=newRunSummaryFromFrame({...old,scheduled:false});
assert.equal(runScheduleState(manual),false);
});
+35
View File
@@ -0,0 +1,35 @@
import test from "node:test";
import assert from "node:assert/strict";
import { PipelinesRepository } from "../src/repository.js";
test("schedule repository uses independent run-config commands, never definition publication", async () => {
const requests=[];
const record={id:8,revision:3,pipeline_id:4,version:2,input:{prompt:"Research batteries"},workspace:"/srv/research",enabled:true,rule:{every:"24h"}};
const repo=new PipelinesRepository({call:async request=>{
requests.push(request);
if(request.type==='list_schedules')return{type:'schedules',schedules:[record]};
if(request.type==='save_schedule')return{type:'schedule',schedule:record};
return{type:'schedule_deleted',schedule_id:8};
}});
assert.deepEqual(await repo.listSchedules(4),[record]);
assert.equal(await repo.saveSchedule(record,{requestKey:'schedule:stable-editor-key'}),record);
await repo.deleteSchedule(8,3);
assert.deepEqual(requests,[
{type:'list_schedules',pipeline_id:4},
{type:'save_schedule',schedule:record,request_key:'schedule:stable-editor-key'},
{type:'delete_schedule',schedule_id:8,expected_revision:3},
]);
});
test("an explicit empty schedules reply is different from missing server support", async () => {
const empty=new PipelinesRepository({call:async()=>({type:'schedules'})});
assert.deepEqual(await empty.listSchedules(),[]);
const old=new PipelinesRepository({call:async()=>({type:'pong'})});
await assert.rejects(old.listSchedules(),/no schedules response/);
});
test("schedule deletion refuses missing identity or revision before contacting the server", async () => {
let calls=0;const repo=new PipelinesRepository({call:async()=>{calls++;}});
for(const [id,revision] of [[0,1],[8,0],[8,undefined],[8,1.5]]) await assert.rejects(repo.deleteSchedule(id,revision));
assert.equal(calls,0);
});
+24 -1
View File
@@ -33,7 +33,7 @@ test('existing record roundtrip preserves CAS, unknown fields and typed extra in
test('run seeding copies only RunSpec and never origin metadata or a locked title', () => {
const run = { version: 3, workspace: '/server/run', input: { prompt: 'Past run', count: 2 },
model: 'p/m', stage_models: { a: 'p/x' }, notify_mode: 'on', title: 'User title', output_format: 'markdown',
model: 'p/m', stage_models: { a: 'p/x' }, notify_mode: 'on', title: 'User title', title_source:'explicit', output_format: 'markdown',
id: 87, origin: { kind: 'schedule' }, request_key: 'no-copy' };
const draft = scheduleDraft({ pipeline, run, workspace: '/different', timezone: 'UTC' });
const saved = serialize({ ...draft, name: 'From run', prompt: 'Editable title and prompt', otherInput: '{"count":2,"prompt":"ignored","array":[1,false]}' });
@@ -70,6 +70,29 @@ test('display is honest for invalid or absent next_due', () => {
assert.equal(scheduleDueLabel('invalid'), 'Next time unavailable');
assert.equal(scheduleDueLabel(null), 'Not scheduled');
assert.match(scheduleRuleLabel({ every: '24h' }), /Server timezone/);
assert.match(scheduleRuleLabel({ every: '24h', timezone:'Local' }), /Server timezone/);
assert.match(scheduleDueLabel('2026-10-21T09:00:00Z','Asia/Tokyo'), /Asia\/Tokyo/);
assert.match(scheduleDueLabel('2026-10-21T09:00:00Z'), /your local time/);
});
test('saved run-level write restrictions survive scheduling without widening edits', () => {
const run={version:3,input:{prompt:'Scoped change'},workspace:'/srv/research',write_paths:['src/file.go'],allow_tools:true,title:'Automatic title',title_source:'model'};
const draft=scheduleDraft({pipeline,run});
const result=serialize({...draft,name:'Scoped run'});
assert.deepEqual(result.write_paths,['src/file.go']);
assert.equal(result.allow_tools,true);
assert.equal(result.title,undefined,'generated titles must not become locked run titles');
for(const writePaths of ['null','{}','[1]','["../outside"]','["/absolute"]','["src/*.go"]']) {
assert.throws(()=>serialize({...make(),writePaths}),/Write paths/);
}
assert.equal(serialize({...make(),timezone:'Local'}).rule.timezone,'Local');
});
test('a prompt-only edit preserves the existing weekday order and timer rule', () => {
const original={...serialize(make()),id:4,revision:2,rule:{every:'24h',days:['fri','mon'],timezone:'UTC'}};
const draft={...scheduleDraft({pipeline,schedule:original}),prompt:'New topic',days:['mon','fri']};
const saved=serializeSchedule(draft,{schedule:original});
assert.deepEqual(saved.rule,original.rule);
});
test('view cache shares pending reads, refreshes explicitly and recovers after refusal', async () => {
+2 -2
View File
@@ -9,9 +9,9 @@ test("shell updates retain unrelated caches and the current app cache", async ()
let activation;
vm.runInNewContext(await readFile(new URL("../sw.js", import.meta.url), "utf8"), {
self: { addEventListener: (type, handler) => handlers.set(type, handler), clients: { claim: async () => {} } },
caches: { keys: async () => ["pipelines-shell-v11", "pipelines-shell-v12", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
caches: { keys: async () => ["pipelines-shell-v12", "pipelines-shell-v13", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
});
handlers.get("activate")({ waitUntil: (promise) => { activation = promise; } });
await activation;
assert.deepEqual(deleted, ["pipelines-shell-v11"]);
assert.deepEqual(deleted, ["pipelines-shell-v12"]);
});
+21 -9
View File
@@ -29,12 +29,13 @@ const modal = createModalController();
window.requests = []; window.routes = [];
const rt = {state,modal,views:{},repo:{getPipeline:async(id,version)=>{requests.push({id,version}); if(window.fail) throw new Error('fixture refusal'); if(window.delay) await new Promise(resolve => window.release=resolve); return window.missing ? {...detail,source:null} : detail;}},pushRoute:(r)=>routes.push(r)};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);rt.views.pipelines=createPipelinesView(rt);
rt.renderContent=()=>{document.querySelectorAll('.stage-pane').forEach(node=>node.remove());if(state.runStagePane)document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));modal.reconcile();};
window.show = (kind) => {
modal.closeAll();state.runGraph?.unmount();state.pipelineGraph?.unmount();
modal.closeAll();state.runStagePane=null;state.runGraph?.unmount();state.pipelineGraph?.unmount();
const host=document.querySelector('main');
host.replaceChildren(kind==='pipeline' ? rt.views.pipelines.renderPipelineDetail() : rt.views.runDetail.renderRunGraphTab(run));
};
window.pane = () => {document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));modal.reconcile();};
window.pane = () => {state.runStagePane={stageKey:'review',visitIndex:0};document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));modal.reconcile();};
window.expectedSource=source;window.rt=rt;show('run');
</script>`;
const server = createServer(async (req, res) => {
@@ -56,9 +57,18 @@ try {
await page.screenshot(resolve(out, name));
};
await page.waitForSelector('.graph-node[data-key="review"]');
const clickNode = async () => {
const openDefinition = async () => {
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
// Run nodes open visit evidence. Definition is explicit in its audit;
// workflow graph nodes still open authored source directly.
if (await page.evaluate('!!document.querySelector(".stage-pane")')) {
await page.click('.audit-open');
await page.click('[data-audit-tab="definition"]');
}
};
const clickNode = async () => {
await openDefinition();
await page.waitForSelector('.stage-definition-document .field-markdown');
};
await clickNode();
@@ -74,6 +84,8 @@ try {
assert.equal(await page.evaluate('document.querySelector(".audit-viewer").contains(document.activeElement)'), true);
}
await page.pressKey('Escape');
assert.equal(await page.evaluate('document.activeElement.classList.contains("audit-open")'), true);
await page.pressKey('Escape');
assert.equal(await page.evaluate('document.activeElement.dataset.key'), 'review');
assert.equal(await page.evaluate('location.pathname'), '/');
assert.deepEqual(await page.evaluate('routes'), []);
@@ -94,15 +106,15 @@ try {
assert.equal(await page.evaluate('document.activeElement.classList.contains("audit-open")'), true);
await page.evaluate("show('run');window.missing=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await openDefinition();
await page.waitForText('No definition has been reconstructed.');
await capture("05-definition-missing-source.png");
await page.evaluate("show('run');window.missing=false;window.fail=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await openDefinition();
await page.waitForText('fixture refusal');
await capture("06-definition-load-failed.png");
await page.evaluate("show('run');window.fail=false");
await page.evaluate("show('pipeline');window.fail=false");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="#success"]');
await page.waitForText('Terminal nodes have no authored stage definition.');
@@ -114,7 +126,7 @@ try {
await page.resize(1440, 900);
await page.evaluate("show('run');window.delay=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await openDefinition();
await page.waitForText('Loading stage definition…');
await capture("09-definition-loading.png");
await page.clickText('.audit-doc-mode', 'Raw');
@@ -123,11 +135,11 @@ try {
assert.equal(await page.evaluate('document.querySelector(".stage-definition-document code").textContent === expectedSource'), true);
await page.evaluate("show('run');window.delay=false;rt.state.runDetail.version=0;window.beforeRequests=requests.length");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await openDefinition();
await page.waitForText('The run did not include its pipeline version.');
assert.equal(await page.evaluate('requests.length === beforeRequests'), true);
await capture("10-definition-missing-version.png");
console.log(`PASS: run/pipeline node popup, exact source, keyboard focus/escape, nested stage preservation, missing/error states; captures ${out}`);
console.log(`PASS: explicit run-visit audit / workflow definition popup, exact source, keyboard focus/escape, nested stage preservation, missing/error states; captures ${out}`);
} finally {
await browser?.close();
await new Promise(resolve => server.close(resolve));