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
+45
View File
@@ -8,6 +8,51 @@ test, or a code change without a capture, is `partial` at best.
Status legend: `todo` · `partial` (some of it works) · `done` (working + captured).
### Run graph opens recorded visits (2026-10-21)
Run-graph stage clicks now call the same visit-pane action as Timeline, selecting
the stage's latest recorded visit. Earlier visits remain selectable from Timeline;
messages/tool turns within one visit remain together in its Session audit. A
graph click no longer fetches or defaults to the authored definition. Definition
remains an explicit Audit & debug tab, pinned to the run's pipeline version.
Unvisited nodes do not fabricate visits or sessions. Workflow-definition graph
clicks still open the definition viewer.
`test/run-graph-visit-browser.mjs` compares the graph and latest Timeline pane
contents/routes at 390/1100px, verifies a loop's latest session identity, no
definition request on default open, unvisited-node safety, and explicit pinned
definition access. Captures: approved OpenCode temporary
`run-graph-visit-captures/`. `test/ui-stage-definition.mjs` retains its source,
missing/loading/error and keyboard checks through the now-explicit run audit.
This supersedes the older run-graph definition-popup default described below.
### Independent schedules and provenance filters (2026-10-21)
Pipeline Summary/Schedules manages multiple independent run configurations for
the same pipeline/version: name, prompt, server workspace, timer and optional run
options. Schedule this run seeds original input/title/options and preserves
run-level write restrictions without changing workflow tool permissions. Creates
reuse one request key across response-loss retries; updates/deletes use revision
CAS and preserve conflicting drafts. No workflow publication occurs.
Pipelines filters distinguish configured schedules (including paused) from none;
Runs filters distinguish actual timer origins from nonscheduled runs. A manual
run of a configured pipeline is not tagged scheduled, and deletion retains old
run provenance. Older peers without fields remain unclassified. Sparse live
frames cannot clear/retarget known provenance. The header provides Refresh; no
per-step scheduling poll or new workflow is used to recover skipped dispatches.
`test/schedules-browser.mjs` covers edit/create/pause/delete, conflict handling,
unknown-server responses, keyboard/focus and 390/1100px. The real scratch-server
`test/schedule-integration-browser.mjs` checks two independent topics, both
filters, retained CAS drafts, Schedule this run preserving explicit title/input/
write scope, an actual claimed timer's first-frame provenance versus manual
execution, unchanged workflow source, and history after deletion. It uses only
human stages, explicit titles, notify=off and a fixture-only NextDue advancement;
it initiates no provider turns or live-user runs. Captures:
`schedule-editor-captures/` and `schedule-integration-captures/` under the approved
OpenCode temporary directory. Shell cache v13 refreshes the new modules/styles.
### Always-visible chat row actions (2026-10-21)
Star is always visible at the top right and Chat actions at the bottom right of
+1
View File
@@ -20,6 +20,7 @@
<link rel="stylesheet" href="./graph.css" />
<link rel="stylesheet" href="./dialogs.css" />
<link rel="stylesheet" href="./settings.css" />
<link rel="stylesheet" href="./schedules.css" />
</head>
<body>
<noscript>This page needs JavaScript to open the WebSocket connection.</noscript>
+2
View File
@@ -110,6 +110,8 @@
.filter-check:hover { background: var(--surface); }
.filter-check input { accent-color: var(--accent); }
.filter-menu { min-width: 240px; max-width: 340px; grid-template-columns: minmax(0, 1fr); }
.pipeline-schedule-meta, .run-row-schedule { color: var(--accent); overflow-wrap: anywhere; }
.filter-panel { max-height: min(65dvh, 600px); overflow-y: auto; overscroll-behavior: contain; }
/* The list body is the scroll container (shell.css gives it its height); the
day headers stick to its top. */
+33
View File
@@ -67,6 +67,7 @@ import {
readEphemeralChatIds,
} from "./views/chat.js";
import { createSearchView } from "./views/search.js";
import { createSchedulesView } from "./views/schedules.js";
import { installMobileViewport } from "./mobileViewport.js";
function defaultServerUrl() {
@@ -1318,6 +1319,7 @@ function setError(err) {
* caller so a stale, invalid URL field cannot spray an error into the UI on every
* visibilitychange/online event.
*/
let schedulesEndpoint = null;
function openConfiguredEndpoint({ surfaceError = true } = {}) {
const validated = validateServerUrl(state.url);
if (!validated.valid) {
@@ -1338,6 +1340,12 @@ function openConfiguredEndpoint({ surfaceError = true } = {}) {
state.error = "";
state.urlError = "";
writeServerUrl(localStorage, state.url);
if (schedulesEndpoint !== validated.wsUrl) {
views.schedules.clearScheduleCache();
modal.close("schedule-editor");
modal.close("schedule-delete");
schedulesEndpoint = validated.wsUrl;
}
repo.connect(validated);
}
@@ -1367,6 +1375,7 @@ function onForegroundActive() {
}
async function onConnected() {
views.schedules.clearScheduleCache();
// Establish the run-event watch immediately once the socket is up (R10): the
// unsubscribe/subscribe pair is sent before anything else is read, and its
// authoritative `list_runs` resync is the one the view then reuses, so a
@@ -1724,6 +1733,7 @@ function consumeRunAction(route) {
}
async function loadCurrentView(force = false, { runsFresh = false } = {}) {
if (force && state.view === "pipelines") views.schedules.clearScheduleCache();
// Settings is local: it has no server-backed list to (re)load, so switching to
// or refreshing it must never raise the "connect first" error.
if (state.view === "settings") {
@@ -2083,6 +2093,12 @@ function scheduleRunDetailSync(runId) {
function applyRunEvent(frame) {
const runId = Number(frame?.run_id);
if (!(runId > 0)) return;
if (state.runsLoaded && !state.runs.some((run) => run.id === runId) && Number(frame.schedule_id) > 0 &&
state.view === "pipelines" && state.pipelineDetail?.id === Number(frame.pipeline_id)) {
// A newly dispatched timer advanced NextDue. Refresh once on insertion,
// not on every stage delta, while retaining the no-polling run lifecycle.
void views.schedules.loadPipelineSchedules(Number(frame.pipeline_id), { force: true });
}
let listChanged = false;
if (state.runsLoaded) {
const fold = foldRunEvent(state.runs, frame);
@@ -2384,6 +2400,22 @@ const runtime = {
selectPipeline,
selectRun,
refreshRunDetail: scheduleRunDetailSync,
scheduleChanged: async (pipelineId) => {
const endpoint = state.url;
const pipelines = await repo.listPipelines();
if (endpoint !== state.url) return;
state.pipelines = pipelines;
state.pipelinesLoaded = true;
touchView("pipelines");
if (state.pipelineDetail?.id === pipelineId) {
const version = state.pipelineDetail.version;
const detail = await repo.getPipeline(pipelineId, version);
if (endpoint === state.url && state.pipelineDetail?.id === pipelineId && state.pipelineDetail.version === version) {
state.pipelineDetail = detail;
}
}
renderContent();
},
setError,
loadCurrentView,
};
@@ -2398,6 +2430,7 @@ const views = {
runDetail: createRunDetailView(runtime),
chat: createChatView(runtime),
search: createSearchView(runtime),
schedules: createSchedulesView(runtime),
};
runtime.views = views;
+14 -4
View File
@@ -14,6 +14,8 @@
// Timestamps and durations (ui/Format.kt)
// ---------------------------------------------------------------------------
import { pipelineScheduleState, matchesScheduleState } from "./scheduleOrigin.js";
/**
* Parses an RFC3339 timestamp to epoch millis, or null when blank or
* unparseable. The single parser every time-reading helper shares, so a bad
@@ -335,8 +337,14 @@ export const RUN_PRESENCES = [
{ key: "no_runs", label: "No runs" },
];
export const PIPELINE_SCHEDULE_FILTERS = [
{ key: "any", label: "Any schedule" },
{ key: "scheduled", label: "Has schedules" },
{ key: "unscheduled", label: "No schedules" },
];
/** The default, no-narrowing pipeline filter. */
export const EMPTY_PIPELINE_FILTERS = { presence: "any", lastRunStatuses: [], name: "" };
export const EMPTY_PIPELINE_FILTERS = { presence: "any", lastRunStatuses: [], name: "", scheduled: "any" };
/** Whether a run-history facet (presence or last-run status) is set. */
export function hasRunFacets(filters) {
@@ -345,7 +353,7 @@ export function hasRunFacets(filters) {
/** True when the filters actually narrow anything. */
export function pipelineFiltersActive(filters) {
return hasRunFacets(filters) || String(filters?.name ?? "").trim() !== "";
return hasRunFacets(filters) || String(filters?.name ?? "").trim() !== "" || ["scheduled", "unscheduled"].includes(filters?.scheduled);
}
/** The number of active facets, used for the control's badge. */
@@ -353,7 +361,8 @@ export function pipelineFilterCount(filters) {
return (
((filters?.presence ?? "any") !== "any" ? 1 : 0) +
((filters?.lastRunStatuses ?? []).length > 0 ? 1 : 0) +
(String(filters?.name ?? "").trim() !== "" ? 1 : 0)
(String(filters?.name ?? "").trim() !== "" ? 1 : 0) +
(["scheduled", "unscheduled"].includes(filters?.scheduled) ? 1 : 0)
);
}
@@ -402,6 +411,7 @@ export function filterPipelines(pipelines, filters, latestRuns = new Map(), runs
latestRuns instanceof Map ? latestRuns.get(pipeline.id) : latestRuns[pipeline.id];
return all.filter((pipeline) => {
if (!pipelineMatchesName(filters?.name, pipeline.name)) return false;
if (!matchesScheduleState(pipelineScheduleState(pipeline), filters?.scheduled)) return false;
if (runFacets && runsKnown) {
const latestRun = getRun(pipeline) ?? null;
if (!pipelineMatchesPresence(filters.presence, latestRun != null)) return false;
@@ -424,7 +434,7 @@ export function pipelineListEmptyState(all, items, filters) {
}
const name = String(filters?.name ?? "");
const message =
name.trim() !== "" && !hasRunFacets(filters)
name.trim() !== "" && !hasRunFacets(filters) && !["scheduled", "unscheduled"].includes(filters?.scheduled)
? `No pipelines match "${name}".`
: "No pipelines match the current filters.";
return { message, clearAction: "Clear filters" };
+6
View File
@@ -10,6 +10,12 @@ export const Protocol = Object.freeze({
PIPELINE_LIST: "pipelines",
GET_PIPELINE: "get_pipeline",
PIPELINE: "pipeline",
LIST_SCHEDULES: "list_schedules",
SCHEDULES: "schedules",
SAVE_SCHEDULE: "save_schedule",
SCHEDULE: "schedule",
DELETE_SCHEDULE: "delete_schedule",
SCHEDULE_DELETED: "schedule_deleted",
LIST_TEMPLATES: "list_templates",
TEMPLATES: "templates",
+31
View File
@@ -104,6 +104,37 @@ export class PipelinesRepository {
return { runs: response.runs ?? [], usage: response.usage ?? null };
}
async listSchedules(pipelineId = null) {
const request = { type: Protocol.LIST_SCHEDULES };
if (pipelineId != null) {
if (!Number.isSafeInteger(pipelineId) || pipelineId < 1) throw new ProtocolError("A positive pipeline ID is required.");
request.pipeline_id = pipelineId;
}
const response = await this.#client.call(request);
if (response.type !== Protocol.SCHEDULES || (response.schedules != null && !Array.isArray(response.schedules))) {
throw new ProtocolError("The server returned no schedules response.");
}
return response.schedules ?? [];
}
async saveSchedule(schedule, { requestKey } = {}) {
if (!schedule || typeof schedule !== "object" || Array.isArray(schedule)) throw new ProtocolError("A saved schedule is required.");
if (requestKey != null && (typeof requestKey !== "string" || requestKey.length > 128)) throw new ProtocolError("Schedule request keys must be strings of at most 128 characters.");
const request = { type: Protocol.SAVE_SCHEDULE, schedule };
if (requestKey) request.request_key = requestKey;
const response = await this.#client.call(request);
if (!response.schedule) throw new ProtocolError("The server returned no saved schedule.");
return response.schedule;
}
async deleteSchedule(id, revision) {
if (!Number.isSafeInteger(id) || id < 1 || !Number.isSafeInteger(revision) || revision < 1) {
throw new ProtocolError("An exact schedule ID and revision are required.");
}
const response = await this.#client.call({type:Protocol.DELETE_SCHEDULE,schedule_id:id,expected_revision:revision});
if (response.type !== Protocol.SCHEDULE_DELETED || response.schedule_id !== id) throw new ProtocolError("The server did not confirm deletion of this schedule.");
}
async getRun(id) {
const response = await this.#client.call({
type: Protocol.GET_RUN,
+21
View File
@@ -169,6 +169,23 @@ function sameResourceWait(a, b) {
);
}
// Execution origin is immutable. Sparse lifecycle frames (or older peers)
// cannot turn a scheduled run into a manual run or retarget its schedule.
function scheduleOriginFields(current, frame) {
const oldId = Number.isSafeInteger(current.schedule_id) && current.schedule_id > 0 ? current.schedule_id : 0;
const newId = Number.isSafeInteger(frame.schedule_id) && frame.schedule_id > 0 ? frame.schedule_id : 0;
const known = Object.hasOwn(current, "scheduled") || Object.hasOwn(frame, "scheduled") || oldId > 0 || newId > 0;
if (!known) return {};
const id = oldId > 0 ? oldId : newId > 0 ? newId : 0;
const incomingName = oldId > 0 && newId > 0 && oldId !== newId ? "" : frame.schedule_name;
const name = String(current.schedule_name || incomingName || "");
return {
scheduled: current.scheduled === true || frame.scheduled === true || id > 0,
...(id > 0 ? { schedule_id: id } : {}),
...(name ? { schedule_name: name } : {}),
};
}
/** The run-state fields a frame advances, shared by the summary row and the detail. */
function runStateFields(current) {
return {
@@ -195,11 +212,13 @@ function runStateFields(current) {
function applyRunStateFields(current, frame) {
if (isStaleRunFrame(current.status, frame.status, frame.resource_wait_set === true)) return current;
const before = runStateFields(current);
const origin = scheduleOriginFields(current, frame);
const status =
frame.resource_wait_set === true && frame.status === "queued" && !isTerminalRunStatus(before.status)
? "queued"
: advanceRunStatus(before.status, frame.status);
const merged = {
...origin,
notify_mode: blank(frame.notify_mode) ? before.notify_mode : frame.notify_mode,
resource_wait: isTerminalRunStatus(status)
? null
@@ -222,6 +241,7 @@ function applyRunStateFields(current, frame) {
// Detail already maintains full visits below; compact evidence is list-only.
const graphEvidence = Array.isArray(current.steps) ? current.graph_evidence : mergeGraphEvidence(current.graph_evidence, frame);
const changed =
Object.keys(origin).some((key) => current[key] !== origin[key]) ||
graphEvidence !== current.graph_evidence ||
merged.notify_mode !== before.notify_mode ||
!sameResourceWait(merged.resource_wait, before.resource_wait) ||
@@ -276,6 +296,7 @@ export function newRunSummaryFromFrame(frame) {
if (!(pipelineId > 0) || blank(name)) return null;
const graphEvidence = mergeGraphEvidence(null, frame);
return {
...scheduleOriginFields({}, frame),
...(graphEvidence ? { graph_evidence: graphEvidence } : {}),
resource_wait: frame.resource_wait ?? null,
id: Number(frame.run_id),
+13 -3
View File
@@ -10,6 +10,8 @@
// Every server-provided string is only ever compared or rendered, never parsed
// as markup; the caller sets it with textContent.
import { runScheduleState, matchesScheduleState } from "./scheduleOrigin.js";
// ---------------------------------------------------------------------------
// Status vocabulary
// ---------------------------------------------------------------------------
@@ -249,9 +251,15 @@ export const RUN_TIME_RANGES = [
export const DEFAULT_TIME_RANGE = "any_time";
export const RUN_SCHEDULE_FILTERS = [
{ value: "any", label: "Any trigger" },
{ value: "scheduled", label: "Scheduled runs" },
{ value: "unscheduled", label: "Not scheduled" },
];
/** The runs-list filters, each defaulting to "no narrowing". */
export function defaultRunFilters() {
return { statuses: new Set(), pipelineId: null, timeRange: DEFAULT_TIME_RANGE };
return { statuses: new Set(), pipelineId: null, timeRange: DEFAULT_TIME_RANGE, scheduled: "any" };
}
/** The number of active facets (one per status/pipeline/time choice). */
@@ -259,7 +267,8 @@ export function runFiltersActiveCount(filters) {
return (
(filters.statuses && filters.statuses.size > 0 ? 1 : 0) +
(filters.pipelineId != null ? 1 : 0) +
(filters.timeRange && filters.timeRange !== DEFAULT_TIME_RANGE ? 1 : 0)
(filters.timeRange && filters.timeRange !== DEFAULT_TIME_RANGE ? 1 : 0) +
(["scheduled", "unscheduled"].includes(filters.scheduled) ? 1 : 0)
);
}
@@ -303,7 +312,8 @@ export function runMatchesFilters(run, filters, today, zone) {
return (
runMatchesStatuses(run, filters.statuses) &&
runMatchesPipeline(run, filters.pipelineId) &&
runMatchesTimeRange(run, filters.timeRange, today, zone)
runMatchesTimeRange(run, filters.timeRange, today, zone) &&
matchesScheduleState(runScheduleState(run), filters.scheduled)
);
}
+32
View File
@@ -0,0 +1,32 @@
// Configuration and execution provenance are different facts. Never infer a
// timer-triggered run from its pipeline's current schedules or legacy Markdown.
export function pipelineScheduleState(pipeline) {
if (Number.isSafeInteger(pipeline?.schedule_count) && pipeline.schedule_count > 0) return true;
if (typeof pipeline?.scheduled === "boolean") return pipeline.scheduled;
if (pipeline?.schedule_count === 0) return false;
return null;
}
export function runScheduleState(run) {
if (run?.scheduled === true || (Number.isSafeInteger(run?.schedule_id) && run.schedule_id > 0)) return true;
return run?.scheduled === false ? false : null;
}
export function matchesScheduleState(state, filter) {
if (!filter || filter === "any") return true;
if (filter === "scheduled") return state === true;
if (filter === "unscheduled") return state === false;
return true;
}
export function pipelineScheduleLabel(pipeline) {
if (pipelineScheduleState(pipeline) !== true) return "";
const count = pipeline.schedule_count;
return Number.isSafeInteger(count) && count > 0 ? `${count} ${count === 1 ? "schedule" : "schedules"}` : "Has schedules";
}
export function scheduledRunLabel(run) {
if (runScheduleState(run) !== true) return "";
const name = String(run?.schedule_name ?? "").trim();
return name ? `Scheduled · ${name}` : "Scheduled";
}
+24 -7
View File
@@ -9,13 +9,14 @@ export function scheduleDraft({ pipeline, schedule = null, run = null, workspace
const { prompt = '', ...other } = input;
const rule = source.rule ?? {};
return {
name: schedule?.name ?? '', prompt, version: String(source.version ?? pipeline?.Version ?? pipeline?.version ?? pipeline?.Pipeline?.version ?? ''),
name: schedule?.name ?? run?.title ?? '', prompt, version: String(source.version ?? pipeline?.Version ?? pipeline?.version ?? pipeline?.Pipeline?.version ?? ''),
workspace: source.workspace ?? workspace, enabled: schedule?.enabled ?? true,
mode: rule.times?.length ? 'clock' : 'interval', every: rule.every ?? '24h',
times: (rule.times ?? []).join(', '), days: [...(rule.days ?? [])],
timezone: rule.timezone ?? (schedule ? '' : (timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone)),
model: source.model ?? '', stageModels: JSON.stringify(source.stage_models ?? {}, null, 2),
otherInput: JSON.stringify(other, null, 2), title: source.title ?? '',
writePaths: JSON.stringify(source.write_paths ?? [], null, 2), allowTools: source.allow_tools === true,
otherInput: JSON.stringify(other, null, 2), title: run?.title_source && !['explicit', 'user'].includes(run.title_source) ? '' : source.title ?? '',
notifyMode: source.notify_mode ?? 'auto', outputFormat: source.output_format ?? '',
};
}
@@ -39,6 +40,12 @@ export function serializeSchedule(draft, { pipelineId, schedule = null } = {}) {
if (!draft.workspace?.startsWith('/') || /[\0\r\n]/.test(draft.workspace)) throw new Error('Enter an absolute workspace path on the server.');
const input = parseScheduleObject(draft.otherInput, 'Other input');
const stageModels = parseScheduleObject(draft.stageModels, 'Stage models');
let writePaths;
try { writePaths = JSON.parse(draft.writePaths ?? '[]'); } catch { throw new Error('Write paths must be a JSON array.'); }
if (!Array.isArray(writePaths) || writePaths.length > 20 || writePaths.some(path =>
typeof path !== 'string' || !path || path.startsWith('/') || /[*?\\\0]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..'))) {
throw new Error('Write paths must be a JSON array of at most 20 exact server-workspace-relative paths.');
}
if (draft.model && !validScheduleModel(draft.model)) throw new Error('Model must be provider/model.');
for (const [key, model] of Object.entries(stageModels)) {
if (!key || !validScheduleModel(model)) throw new Error('Each stage model must be provider/model.');
@@ -60,9 +67,13 @@ export function serializeSchedule(draft, { pipelineId, schedule = null } = {}) {
if (!times.length || times.some(time => !/^([01]\d|2[0-3]):[0-5]\d$/.test(time)) || new Set(times).size !== times.length) throw new Error('Enter distinct 24-hour times, such as 09:00, 17:30.');
rule.times = times;
} else throw new Error('Choose an interval or clock times.');
if (draft.days.length) rule.days = [...draft.days];
if (draft.days.length) {
const prior = schedule?.rule?.days ?? [];
const unchanged = prior.length === draft.days.length && prior.every(day => draft.days.includes(day));
rule.days = unchanged ? [...prior] : [...draft.days];
}
if (draft.timezone.trim()) {
try { new Intl.DateTimeFormat('en', { timeZone: draft.timezone.trim() }); }
try { if (draft.timezone.trim() !== 'Local') new Intl.DateTimeFormat('en', { timeZone: draft.timezone.trim() }); }
catch { throw new Error('Enter a valid IANA timezone.'); }
rule.timezone = draft.timezone.trim();
}
@@ -70,6 +81,8 @@ export function serializeSchedule(draft, { pipelineId, schedule = null } = {}) {
name: draft.name.trim(), pipeline_id: schedule?.pipeline_id ?? pipelineId,
version, enabled: Boolean(draft.enabled), input: { ...input, prompt: draft.prompt },
workspace: draft.workspace, rule, notify_mode: draft.notifyMode };
if (writePaths.length) record.write_paths = writePaths; else delete record.write_paths;
if (draft.allowTools) record.allow_tools = true; else delete record.allow_tools;
for (const [key, value] of Object.entries({ model: draft.model, stage_models: stageModels, title: draft.title, output_format: draft.outputFormat })) {
if (typeof value === 'object' ? Object.keys(value).length : value !== '') record[key] = value;
else delete record[key];
@@ -79,11 +92,15 @@ export function serializeSchedule(draft, { pipelineId, schedule = null } = {}) {
export function scheduleRuleLabel(rule = {}) {
return [rule.every ? `Every ${rule.every}` : (rule.times ?? []).join(', '),
(rule.days ?? []).join(', '), rule.timezone || 'Server timezone'].filter(Boolean).join(' · ');
(rule.days ?? []).join(', '), rule.timezone && rule.timezone !== 'Local' ? rule.timezone : 'Server timezone'].filter(Boolean).join(' · ');
}
export function scheduleDueLabel(value) {
export function scheduleDueLabel(value, timeZone = '') {
if (!value) return 'Not scheduled';
const date = new Date(value);
return Number.isNaN(date.getTime()) ? 'Next time unavailable' : date.toLocaleString();
if (Number.isNaN(date.getTime())) return 'Next time unavailable';
if (timeZone && timeZone !== 'Local') {
try { return `${date.toLocaleString(undefined, { timeZone })} (${timeZone})`; } catch { /* Keep the absolute occurrence visible in local time. */ }
}
return `${date.toLocaleString()} (your local time)`;
}
+35
View File
@@ -8,6 +8,7 @@ import { describeError } from "../format.js";
import {
PIPELINE_SORTS,
PIPELINE_DETAIL_TABS,
PIPELINE_SCHEDULE_FILTERS,
RUN_PRESENCES,
RUN_STATUS_FILTERS,
EMPTY_PIPELINE_FILTERS,
@@ -30,6 +31,7 @@ import { statusIcon } from "../statusIcon.js";
import { writeGraphExpanded } from "../graphPrefs.js";
import { pendingRun, createRunIntent, saveRunIntent, clearRunIntent } from "../runIntent.js";
import { ProtocolError } from "../client.js";
import { pipelineScheduleLabel, pipelineScheduleState } from "../scheduleOrigin.js";
export function createPipelinesView(rt) {
const { state, repo, modal } = rt;
@@ -164,6 +166,23 @@ function renderFilterPanel() {
),
);
}
panel.append(h("div", { class: "filter-section", text: "Scheduling" }));
panel.append(h("div", { class: "muted", text: "Configured schedules, including paused." }));
for (const option of PIPELINE_SCHEDULE_FILTERS) {
panel.append(h("label", { class: "filter-item" }, h("input", {
type: "radio",
name: "pipelineScheduleFilter",
"data-pipeline-schedule": option.key,
checked: (filters.scheduled ?? "any") === option.key,
onchange: () => {
state.pipelineFilters = { ...state.pipelineFilters, scheduled: option.key };
renderContent();
},
}), h("span", { text: option.label })));
}
if (state.pipelines.some((pipeline) => pipelineScheduleState(pipeline) === null)) {
panel.append(h("p", { class: "muted", text: "Some records have no scheduling metadata; they stay unclassified." }));
}
panel.append(
h("div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Clear filters", onclick: clearPipelineFilters })),
);
@@ -263,6 +282,8 @@ function renderPipelineRow(pipeline, latestRuns, runsKnown, now) {
}),
);
const updated = pipelineUpdatedLine(pipeline);
const scheduled = pipelineScheduleLabel(pipeline);
if (scheduled) children.push(h("span", { class: "row-meta pipeline-schedule-meta", text: scheduled, title: "Configured schedules, including paused" }));
if (updated) children.push(h("span", { class: "row-meta", text: updated }));
if (runsKnown) {
const run = latestRuns.get(pipeline.id);
@@ -560,6 +581,16 @@ function renderPipelineDetail() {
applyRoute(route);
},
}),
rt.views?.schedules ? h("button", {
class: "pipeline-schedules",
type: "button",
text: "Schedules",
onclick: () => {
state.pipelineTab = "summary";
renderContent();
requestAnimationFrame(() => document.querySelector(".schedule-section")?.scrollIntoView({ block: "start" }));
},
}) : null,
),
);
// The Run dialog is an overlay; append it before the tab branches so Graph
@@ -599,6 +630,9 @@ function renderPipelineDetail() {
return pane;
}
if (state.pipelineTab === "source") {
if (Object.hasOwn(d, "schedule_count") && d.graph?.settings?.schedules?.length) {
pane.append(h("p", { class: "muted", text: "Legacy scheduling settings in this immutable source are inactive. Use Schedules to manage future runs." }));
}
pane.append(h("pre", { class: "source-code" }, h("code", { text: d.source || "" })));
return pane;
}
@@ -615,6 +649,7 @@ function renderPipelineDetail() {
);
}
pane.append(rows);
if (rt.views?.schedules) pane.append(rt.views.schedules.renderPipelineSchedules(d));
pane.append(
h(
"button",
+25 -5
View File
@@ -7,6 +7,7 @@ import { backChevronIcon, h, kvMono, canCopyLink, canShare, copyArtifactLink, sh
import { isExecuting, changeKindTone, describeError } from "../format.js";
import { resolveArtifactUrl } from "../serverUrl.js";
import { runStateOf, runStatusLabel } from "../runs.js";
import { scheduledRunLabel } from "../scheduleOrigin.js";
import { PIPELINE_GRAPH_EMPTY, RUN_GRAPH_MISSING, mount as mountGraph } from "../graph.js";
import { writeGraphExpanded } from "../graphPrefs.js";
import { definitionDocument } from "./stageDefinition.js";
@@ -216,7 +217,7 @@ function renderRunDetail(now = Date.now()) {
* The Graph tab (R5): the run's own guidance note plus the shared workflow graph
* mounted in run mode, or the app's exact missing-graph sentence when the server
* sent no stages. The active stage pulses with its elapsed time while the run
* executes; clicking a stage opens its authored definition without navigating.
* executes; clicking a stage opens the same recorded-visit pane as Timeline.
* The mount handle is tracked in `state.runGraph` so a re-render
* (or a tab/run change) always unmounts the previous wheel/pointer/resize
* listeners and the elapsed timer.
@@ -233,9 +234,7 @@ function renderRunGraphTab(d) {
state.runGraph = mountGraph(host, d.graph, {
runState: runGraphState(d),
expanded: state.runGraphExpanded,
onStageTap: (key) => rt.views.dialogs.openStageDefinition(
runDefinition(d), key, `Run ${d.id} · pipeline ${d.pipeline_id} · v${d.version}`,
),
onStageTap: (key) => openStagePane(key, latestVisitIndex(d, key)),
onExpandedChange: (value) => {
state.runGraphExpanded = value;
writeGraphExpanded(value);
@@ -418,6 +417,8 @@ function renderRunSummaryTab(d, now) {
const wrap = h("div", { class: "run-tab-body" });
wrap.append(renderRunTitleRow(d));
wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) }));
const origin = scheduledRunLabel(d);
if (origin) wrap.append(h("p", { class: "run-schedule-origin muted", text: origin }));
const rows = h("div", { class: "kv" });
for (const row of summaryRows(d, now)) {
@@ -970,9 +971,28 @@ function renderDecisionCard(decision) {
return card;
}
/** Cancel/Retry actions, shown exactly per the app's eligibility rules. */
/** Run controls plus an independent schedule seeded from the original RunInfo. */
function renderRunActions(d) {
const buttons = [];
if (rt.views?.schedules && Number(d.pipeline_id) > 0 && Number(d.version) > 0) {
buttons.push(h("button", {
class: "run-action schedule-run",
type: "button",
text: "Schedule this run",
title: "Save this run's prompt and options with an independent timer; does not rerun it now",
onclick: async (event) => {
const trigger = event.currentTarget;
trigger.disabled = true;
try {
const pipeline = await runDefinition(d);
if (state.runDetail?.id === d.id) rt.views.schedules.openScheduleEditor({ pipeline, run: d, trigger });
} catch (error) {
state.actionError = describeError(error);
renderContent();
} finally { trigger.disabled = false; }
},
}));
}
if (canCancel(d)) {
buttons.push(
h("button", {
+22
View File
@@ -5,9 +5,11 @@
import { h } from "../dom.js";
import { statusIcon } from "../statusIcon.js";
import { renderMiniGraph, createMiniGraphCache } from "../miniGraph.js";
import { scheduledRunLabel, runScheduleState } from "../scheduleOrigin.js";
import {
RUN_STATES,
RUN_TIME_RANGES,
RUN_SCHEDULE_FILTERS,
RUN_SORTS,
runStateOf,
runStatusLabel,
@@ -148,6 +150,8 @@ function renderRunRow(run, now) {
row.append(h("span", { class: "run-row-title", text: identity.label }));
}
const scheduled = scheduledRunLabel(run);
if (scheduled) row.append(h("span", { class: "run-row-schedule row-meta", text: scheduled }));
row.append(h("span", { class: "run-row-progress", text: progressText(run) }));
row.append(
h("span", {
@@ -236,6 +240,10 @@ function renderAppliedRunFilters() {
if (range && state.runFilters.timeRange !== defaultRunFilters().timeRange) {
applied.append(chip(range.label, () => setTimeRangeFilter(defaultRunFilters().timeRange)));
}
const scheduled = RUN_SCHEDULE_FILTERS.find((entry) => entry.value === state.runFilters.scheduled);
if (scheduled && scheduled.value !== "any") {
applied.append(chip(scheduled.label, () => setScheduleFilter("any"), "schedule-filter-chip"));
}
return applied;
}
@@ -275,6 +283,15 @@ function renderFilterMenu() {
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Trigger" }));
for (const option of RUN_SCHEDULE_FILTERS) {
menu.append(filterCheck(option.label, (filters.scheduled ?? "any") === option.value,
() => setScheduleFilter(option.value), { "data-run-schedule": option.value }));
}
if (state.runs.some((run) => runScheduleState(run) === null)) {
menu.append(h("p", { class: "muted", text: "Some records have no scheduling provenance; they stay unclassified." }));
}
menu.append(
h(
"div",
@@ -347,6 +364,11 @@ function setTimeRangeFilter(timeRange) {
closeMenu();
}
function setScheduleFilter(scheduled) {
state.runFilters = { ...state.runFilters, scheduled };
closeMenu();
}
function clearRunFilters() {
state.runFilters = defaultRunFilters();
if (state.selectedRunId == null) rt.pushRoute({ kind: "runs" });
+13 -7
View File
@@ -1,5 +1,6 @@
import { h } from '../dom.js';
import { SCHEDULE_DAYS, scheduleDraft, serializeSchedule, scheduleRuleLabel, scheduleDueLabel } from '../schedules.js';
import { newChatOperationId } from '../repository.js';
export function createSchedulesView(rt) {
const cache = new Map();
@@ -44,7 +45,9 @@ export function createSchedulesView(rt) {
const entry = cache.get(id);
const section = h('section', { class: 'schedule-section', 'aria-label': 'Schedules' },
h('div', { class: 'schedule-heading' }, h('h3', { text: `Schedules${entry && !entry.loading && !entry.error ? ` (${entry.items.length})` : ''}` }),
button('Add schedule', event => openScheduleEditor({ pipeline, trigger: event.currentTarget }), { class: 'schedule-add' })),
h('div', { class: 'schedule-actions' },
button('Refresh', () => { void loadPipelineSchedules(id, { force: true }); refresh(); }, { class: 'schedule-refresh' }),
button('Add schedule', event => openScheduleEditor({ pipeline, trigger: event.currentTarget }), { class: 'schedule-add' }))),
h('p', { class: 'schedule-muted', text: 'Independent prompts and timers for this pipeline. Schedules do not change its definition.' }));
if (entry.loading) section.append(h('p', { role: 'status', text: 'Loading schedules…' }));
if (entry.error) section.append(h('div', { class: 'schedule-error', role: 'alert' }, entry.error,
@@ -56,7 +59,7 @@ export function createSchedulesView(rt) {
h('div', { class: 'schedule-heading' }, h('strong', { text: schedule.name }), h('span', { class: 'schedule-badge', text: schedule.enabled ? 'Enabled' : 'Paused' })),
h('div', { class: 'schedule-muted', text: `Pinned v${schedule.version} · ${scheduleRuleLabel(schedule.rule)}` }),
h('p', { class: 'schedule-prompt', text: schedule.input?.prompt ?? '' }),
h('div', { class: 'schedule-muted', text: `Next: ${schedule.enabled ? scheduleDueLabel(schedule.next_due) : 'Paused'}` }), errorNode);
h('div', { class: 'schedule-muted', text: `Next: ${schedule.enabled ? scheduleDueLabel(schedule.next_due, schedule.rule?.timezone) : 'Paused'}` }), errorNode);
const actions = h('div', { class: 'schedule-actions' });
const edit = button('Edit', event => openScheduleEditor({ pipeline, schedule, trigger: event.currentTarget }));
const toggle = button(schedule.enabled ? 'Pause' : 'Enable', async () => {
@@ -96,10 +99,11 @@ export function createSchedulesView(rt) {
h('p', { text: 'Future runs only. Run history and active runs will not be deleted.' }), errorNode,
h('div', { class: 'schedule-actions' }, button('Keep schedule', close), confirm)));
rt.modal.open('schedule-delete', panel, { trigger, onClose: close, renderManaged: false, history: false,
fallbackSelectors: ['.schedule-add'] });
fallbackSelectors: ['.schedule-add', '.schedule-run', '#detailTitle', '#pane-main'] });
}
function openScheduleEditor({ pipeline, schedule = null, run = null, trigger = null }) {
const draft = scheduleDraft({ pipeline, schedule, run, workspace: rt.state.workspace });
const requestKey = schedule?.id ? undefined : `schedule:${newChatOperationId()}`;
let pending = false;
const close = () => { if (!pending) rt.modal.close('schedule-editor'); };
const fields = {};
@@ -130,10 +134,12 @@ export function createSchedulesView(rt) {
field('name', 'Name', { required: true }), field('prompt', 'Prompt', { textarea: true, required: true, rows: 5 }),
h('div', { class: 'schedule-grid' }, field('version', 'Pinned version', { inputmode: 'numeric' }), field('workspace', 'Server workspace', { required: true })),
h('label', { class: 'schedule-field' }, 'Timer', mode), interval, clock, days,
field('timezone', 'Timezone (blank uses server timezone)'), h('label', { class: 'schedule-check' }, enabled, 'Enabled'),
field('timezone', 'Timezone (blank uses server timezone)'), h('label', { class: 'schedule-check' }, enabled, 'Enabled'),
h('p', { class: 'schedule-muted', text: 'Enabled schedules start future runs automatically, including model usage and the workflow’s permitted tools.' }),
h('details', { class: 'schedule-advanced' }, h('summary', { text: 'Advanced run options' }),
field('model', 'Model (provider/model)'), field('stageModels', 'Stage models (JSON object)', { textarea: true, rows: 3 }),
field('otherInput', 'Other input (JSON object; prompt above wins)', { textarea: true, rows: 4 }),
field('otherInput', 'Other input (JSON object; prompt above wins)', { textarea: true, rows: 4 }),
field('writePaths', 'Write paths (JSON array; optional additional restriction)', { textarea: true, rows: 3 }),
field('title', 'Run title (optional)'), h('label', { class: 'schedule-field' }, 'Notifications', notify), field('outputFormat', 'Output format (optional)')),
errorNode, h('div', { class: 'schedule-actions schedule-footer' }, button('Cancel', close), save));
form.addEventListener('submit', async event => {
@@ -148,7 +154,7 @@ export function createSchedulesView(rt) {
} catch (error) { errorNode.textContent = message(error); errorNode.hidden = false; return; }
const controls = [...form.querySelectorAll('input, textarea, select, button')];
pending = true; controls.forEach(control => { control.disabled = true; }); save.textContent = 'Saving…';
try { await rt.repo.saveSchedule(record); }
try { await rt.repo.saveSchedule(record, { requestKey }); }
catch (error) {
errorNode.textContent = `${message(error)} Your draft is preserved. If this schedule changed elsewhere, reopen it before retrying.`;
errorNode.hidden = false; pending = false; controls.forEach(control => { control.disabled = false; }); save.textContent = 'Save schedule'; return;
@@ -158,7 +164,7 @@ export function createSchedulesView(rt) {
});
const overlay = h('div', { class: 'schedule-overlay', role: 'dialog', 'aria-modal': 'true', 'aria-label': schedule ? 'Edit schedule' : 'Add schedule' }, form);
rt.modal.open('schedule-editor', overlay, { trigger, onClose: close, renderManaged: false, history: false,
fallbackSelectors: ['.schedule-add'] });
fallbackSelectors: ['.schedule-add', '.schedule-run', '#detailTitle', '#pane-main'] });
return overlay;
}
return { renderPipelineSchedules, openScheduleEditor, loadPipelineSchedules, clearScheduleCache };
+1 -1
View File
@@ -1,7 +1,7 @@
// A shell cache for an installed Pipelines app. The API (the WebSocket proxy and
// artifact files) is never cached; static files prefer the network and fall back
// to the last good copy so an installed app still opens when the server is away.
const CACHE = "pipelines-shell-v12";
const CACHE = "pipelines-shell-v13";
const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/favicon.svg"];
self.addEventListener("install", (event) => {
+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));