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
+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 };