// The Pipelines destination: the filterable/sortable list, the pipeline detail // (Summary / Graph / Source) and the list refresh used after a template create. // The pure models live in pipelines.js and graph.js; this module owns the DOM. import { h } from "../dom.js"; import { renderMiniGraph } from "../miniGraph.js"; import { describeError } from "../format.js"; import { PIPELINE_SORTS, PIPELINE_DETAIL_TABS, PIPELINE_SCHEDULE_FILTERS, RUN_PRESENCES, RUN_STATUS_FILTERS, EMPTY_PIPELINE_FILTERS, filterPipelines, graphNote, latestRunByPipeline, pipelineFilterCount, pipelineListEmptyState, pipelineSubtitle, pipelineUpdatedLine, runBadge, runBadgeMetaLine, sortPipelines, stageCountText, summaryFields, versionRow, } from "../pipelines.js"; import { PIPELINE_GRAPH_EMPTY, layoutGraph, mount as mountGraph } from "../graph.js"; 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; const renderContent = (...args) => rt.renderContent(...args); const selectPipeline = (...args) => rt.selectPipeline(...args); const pushRoute = (...args) => rt.pushRoute(...args); const applyRoute = (...args) => rt.applyRoute(...args); function renderPipelineList() { const list = h("div", { class: "list" }); list.append(renderPipelineControls()); const rows = h("div", { id: "pipelineRows", class: "list-scroll" }); fillPipelineRows(rows); list.append(rows); return list; } /** * The list's filter + sort toolbar and (when open) the matching menu panel. The * rows themselves live in the separate `#pipelineRows` container so a keystroke * in the name filter can refresh just the rows without rebuilding (and so * blurring) the input the operator is typing in. */ function renderPipelineControls() { const filters = state.pipelineFilters; const count = pipelineFilterCount(filters); const panel = state.pipelineMenu; const controls = h( "div", { class: "list-controls" }, h( "div", { class: "list-toolbar" }, h( "button", { id: "filterToggle", class: `control${panel === "filter" ? " active" : ""}`, onclick: () => { state.pipelineMenu = panel === "filter" ? null : "filter"; renderContent(); }, }, h("span", { text: "Filter" }), h("span", { id: "filterCount", class: "count", text: count ? ` (${count})` : "" }), ), h("button", { id: "sortToggle", class: `control${panel === "sort" ? " active" : ""}`, text: `Sort: ${pipelineSortLabel(state.pipelineSort)}`, onclick: () => { state.pipelineMenu = panel === "sort" ? null : "sort"; renderContent(); }, }), h("button", { id: "clearFilters", class: "ghost clear", text: "Clear filters", hidden: count === 0, onclick: clearPipelineFilters, }), ), ); if (panel === "filter") controls.append(renderFilterPanel()); if (panel === "sort") controls.append(renderSortPanel()); return controls; } function renderFilterPanel() { const filters = state.pipelineFilters; const panel = h("div", { class: "menu-panel filter-panel" }); panel.append(h("div", { class: "filter-section", text: "Name" })); panel.append( h( "label", { class: "filter-field" }, h("span", { class: "filter-field-label", text: "Pipeline name contains" }), h("input", { id: "pipelineNameFilter", type: "text", value: filters.name, spellcheck: "false", oninput: (e) => { state.pipelineFilters = { ...state.pipelineFilters, name: e.target.value }; // Targeted refresh: the input keeps focus and its value while the // list narrows behind it. refreshPipelineRows(); }, }), ), ); panel.append(h("div", { class: "filter-section", text: "Runs" })); for (const presence of RUN_PRESENCES) { panel.append( h( "label", { class: "filter-item" }, h("input", { type: "radio", name: "runPresence", checked: filters.presence === presence.key, onchange: () => { state.pipelineFilters = { ...state.pipelineFilters, presence: presence.key }; renderContent(); }, }), h("span", { text: presence.label }), ), ); } panel.append(h("div", { class: "filter-section", text: "Last run status" })); for (const status of RUN_STATUS_FILTERS) { panel.append( h( "label", { class: "filter-item" }, h("input", { id: `status-${status}`, type: "checkbox", checked: filters.lastRunStatuses.includes(status), onchange: (e) => { const next = e.target.checked ? [...state.pipelineFilters.lastRunStatuses, status] : state.pipelineFilters.lastRunStatuses.filter((s) => s !== status); state.pipelineFilters = { ...state.pipelineFilters, lastRunStatuses: next }; renderContent(); }, }), h("span", { text: status }), ), ); } 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 })), ); return panel; } function renderSortPanel() { const panel = h("div", { class: "menu-panel sort-panel" }); for (const option of PIPELINE_SORTS) { panel.append( h("button", { class: `sort-option${state.pipelineSort === option.key ? " active" : ""}`, text: option.label, onclick: () => { state.pipelineSort = option.key; state.pipelineMenu = null; renderContent(); }, }), ); } panel.append( h( "div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Reset", onclick: () => { state.pipelineSort = "server_order"; state.pipelineMenu = null; renderContent(); }, }), ), ); return panel; } /** Re-renders the rows and the toolbar's active-filter badge after a filter change. */ function refreshPipelineRows() { const rows = document.getElementById("pipelineRows"); if (rows) fillPipelineRows(rows); const count = pipelineFilterCount(state.pipelineFilters); const badge = document.getElementById("filterCount"); if (badge) badge.textContent = count ? ` (${count})` : ""; const clear = document.getElementById("clearFilters"); if (clear) clear.hidden = count === 0; } /** Sorts, filters and renders the pipeline rows (or the matching empty state) into `rowsEl`. */ function fillPipelineRows(rowsEl) { const latestRuns = latestRunByPipeline(state.runs); const runsKnown = state.runsLoaded; const now = Date.now(); const nodes = []; if (state.loading && !state.pipelines.length) { nodes.push(h("div", { class: "muted pad", text: "Loading pipelines…" })); } else if (!state.pipelinesLoaded) { nodes.push(h("div", { class: "muted pad", text: "Connect to the server to load pipelines." })); } else { const sorted = sortPipelines(state.pipelines, state.pipelineSort, latestRuns); const items = filterPipelines(sorted, state.pipelineFilters, latestRuns, runsKnown); if (items.length) { for (const pipeline of items) nodes.push(renderPipelineRow(pipeline, latestRuns, runsKnown, now)); } else { const empty = pipelineListEmptyState(state.pipelines, items, state.pipelineFilters); const box = h("div", { class: "empty pad" }, h("div", { class: "muted", text: empty.message })); if (empty.clearAction) { box.append(h("button", { class: "ghost", text: empty.clearAction, onclick: clearPipelineFilters })); } nodes.push(box); } } rowsEl.replaceChildren(...nodes); } function renderPipelineMiniGraph(pipeline) { return renderMiniGraph(pipeline.shape ?? pipeline.graph); } function renderPipelineRow(pipeline, latestRuns, runsKnown, now) { const children = [ h( "span", { class: "pipeline-head" }, pipelineGlyph(), h("span", { class: "row-title", text: pipeline.name || `pipeline ${pipeline.id}` }), ), ]; const mini = renderPipelineMiniGraph(pipeline); if (mini) children.push(mini); children.push( h("span", { class: "row-meta", text: stageCountText(pipeline.stages ?? pipeline.shape?.stages?.length ?? 0), }), ); 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); if (!run) { children.push(h("span", { class: "row-meta muted", text: "no runs recorded" })); } else { const badge = runBadge(run, now); children.push( h( "span", { class: "row-run" }, statusIcon(badge.state, badge.state.charAt(0).toUpperCase() + badge.state.slice(1)), h("span", { class: "row-meta", text: runBadgeMetaLine(badge) }), ), ); } } return h( "button", { class: `row${state.selectedPipelineId === pipeline.id ? " selected" : ""}`, "data-pipeline-id": String(pipeline.id), "data-animate-key": `pipeline:${pipeline.id}`, onclick: () => selectPipeline(pipeline), }, ...children, ); } /** A small flow glyph: the pipeline's own icon in lists and the collapsed strip. */ function pipelineGlyph() { const ns = "http://www.w3.org/2000/svg"; const svg = document.createElementNS(ns, "svg"); svg.setAttribute("class", "pipeline-glyph"); svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); svg.setAttribute("focusable", "false"); const path = document.createElementNS(ns, "path"); path.setAttribute("d", "M4 12h5V6h5M9 12v6h5"); path.setAttribute("fill", "none"); path.setAttribute("stroke", "currentColor"); path.setAttribute("stroke-width", "1.8"); path.setAttribute("stroke-linecap", "round"); path.setAttribute("stroke-linejoin", "round"); svg.append(path); for (const [cx, cy] of [[3, 12], [19, 6], [19, 18]]) { const dot = document.createElementNS(ns, "circle"); dot.setAttribute("cx", String(cx)); dot.setAttribute("cy", String(cy)); dot.setAttribute("r", "2"); dot.setAttribute("fill", "currentColor"); svg.append(dot); } return svg; } /** Open the Run pipeline dialog for [pipeline]. */ async function openRunDialog(pipeline) { const pipelineId = Number(pipeline?.id) || 0; if (pipelineId <= 0) return; const start = { pipelineId, version: Number(pipeline?.version) || Number(pipeline?.latest_version) || 0, name: String(pipeline?.name ?? ""), prompt: "", workspace: String(state.workspace ?? "").startsWith("/") ? state.workspace : "", notifyMode: "auto", outputFormat: "", directories: [], loading: true, sending: false, error: "", }; start.intent = pendingRun(globalThis.sessionStorage, state.url, start.pipelineId, start.version); if (start.intent) { start.prompt = start.intent.prompt; start.workspace = start.intent.workspace; start.notifyMode = start.intent.notifyMode; start.outputFormat = start.intent.outputFormat ?? ""; start.error = "A previous launch has an unknown result. Check/retry reconciles that same request; it will not start a duplicate."; } state.runStart = start; renderContent(); try { const directories = await repo.chatDirectories(); start.directories = Array.isArray(directories) ? directories.filter((entry) => typeof entry === "string" && entry.startsWith("/")) : []; } catch (error) { start.directories = []; start.error = describeError(error); } if (!start.workspace && start.directories.length) start.workspace = start.directories[0]; start.loading = false; if (state.runStart === start) renderContent(); } function closeRunDialog() { state.runStart = null; renderContent(); } async function startRun() { const start = state.runStart; if (!start || start.sending) return; const prompt = start.prompt.trim(); if (prompt === "") { start.error = "Enter a prompt for this run."; renderContent(); return; } if (!start.workspace.startsWith("/")) { start.error = "Choose an absolute working directory on the server."; renderContent(); return; } start.sending = true; start.error = ""; const recovering = start.intent != null; if (!start.intent) { start.intent = createRunIntent({ pipelineId: start.pipelineId, version: start.version, prompt, workspace: start.workspace, notifyMode: start.notifyMode, outputFormat: start.outputFormat, title: "", }); } saveRunIntent(globalThis.sessionStorage, state.url, start.intent); renderContent(); try { const existing = recovering ? await repo.runByRequestKey(start.intent.requestKey) : null; const run = existing ?? await repo.runPipeline(start.intent); clearRunIntent(globalThis.sessionStorage, state.url, start.intent); state.runStart = null; pushRoute({ kind: "run", id: run.id }); await applyRoute({ kind: "run", id: run.id }); } catch (error) { if (state.runStart !== start) return; // A confirmed refusal can be corrected, but only after a read proves no // run was admitted. A generic transport failure remains uncertain. if (error instanceof ProtocolError) { try { const existing = await repo.runByRequestKey(start.intent.requestKey); if (existing) { clearRunIntent(globalThis.sessionStorage, state.url, start.intent); state.runStart = null; pushRoute({ kind: "run", id: existing.id }); await applyRoute({ kind: "run", id: existing.id }); return; } clearRunIntent(globalThis.sessionStorage, state.url, start.intent); start.intent = null; } catch { /* Keep the launch immutable until admission can be checked. */ } } start.sending = false; start.error = describeError(error) + (start.intent ? ". Admission may be unknown. Check/retry uses the same request key." : ""); renderContent(); } } function renderRunStartDialog() { const start = state.runStart; const overlay = h("div", { class: "confirm-dialog run-start-dialog", role: "dialog", "aria-modal": "true", "aria-label": `Run ${start.name || "pipeline"}`, }); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeRunDialog(); }); const panel = h("div", { class: "confirm-panel" }); panel.append(h("h2", { class: "confirm-title", text: `Run ${start.name || "pipeline"}` })); const promptField = h("label", { class: "run-start-field", for: "runPrompt" }); promptField.append(h("span", { class: "run-start-label", text: "Prompt" })); const prompt = h("textarea", { id: "runPrompt", class: "run-start-prompt", rows: "5", placeholder: "What should this run do?", spellcheck: "false", disabled: start.intent != null, oninput: (event) => { start.prompt = event.target.value; }, }); prompt.value = start.prompt; promptField.append(prompt); panel.append(promptField); const listId = "runWorkspaceChoices"; const datalist = h("datalist", { id: listId }); for (const directory of start.directories) datalist.append(h("option", { value: directory })); const workField = h("label", { class: "run-start-field", for: "runWorkspace" }); workField.append(h("span", { class: "run-start-label", text: "Working directory (on the server)" })); const work = h("input", { id: "runWorkspace", type: "text", list: listId, value: start.workspace, disabled: start.intent != null, spellcheck: "false", autocomplete: "off", placeholder: "/absolute/path/on/the/server", oninput: (event) => { start.workspace = event.target.value; }, }); workField.append(work, datalist); workField.append(h("span", { class: "run-start-helper muted", text: "Choose a recent directory or type an absolute path." })); panel.append(workField); const notifyField = h("label", { class: "run-start-field", for: "runNotify" }); notifyField.append(h("span", { class: "run-start-label", text: "Notifications for this run" })); const notify = h("select", { id: "runNotify", disabled: start.intent != null, onchange: (event) => { start.notifyMode = event.target.value; } }); for (const [value, label] of [ ["auto", "Pipeline default"], ["on", "Notify me"], ["off", "Silent"], ]) { const option = h("option", { value, text: label }); option.selected = start.notifyMode === value; notify.append(option); } notifyField.append(notify); panel.append(notifyField); const outputField = h("label", { class: "run-start-field", for: "runOutputFormat" }); outputField.append(h("span", { class: "run-start-label", text: "Report format" })); const outputFormat = h("select", { id: "runOutputFormat", disabled: start.intent != null, onchange: (event) => { start.outputFormat = event.target.value; } }); for (const [value, label] of [["", "No report requirement"], ["html", "HTML report"], ["markdown", "Markdown report"]]) { const option = h("option", { value, text: label }); option.selected = start.outputFormat === value; outputFormat.append(option); } outputField.append(outputFormat); outputField.append(h("span", { class: "run-start-helper muted", text: "Requires a nonempty server-written report before success. Structure only; facts are not verified." })); panel.append(outputField); if (start.loading) panel.append(h("div", { class: "run-start-helper muted", text: "Loading directories…" })); if (start.error) panel.append(h("div", { class: "run-start-error", role: "alert", text: start.error })); const actions = h("div", { class: "confirm-actions" }); actions.append( h("button", { class: "ghost run-start-cancel", type: "button", text: "Cancel", disabled: start.sending, onclick: closeRunDialog, }), h("button", { class: "primary run-start-confirm", type: "button", text: start.sending ? "Starting…" : start.intent ? "Check / retry" : "Run", disabled: start.sending, onclick: startRun, }), ); panel.append(actions); overlay.append(panel); modal.stage("run-start", overlay, { onClose: closeRunDialog, triggerSelector: ".run-pipeline", fallbackSelectors: ["#detailTitle", "#pane-main"], }); return overlay; } function renderPipelineDetail() { const d = state.pipelineDetail; const pane = h("div", { class: "detail" }); if (!d) { pane.append(h("div", { class: "muted pad", text: "Select a pipeline." })); return pane; } pane.append(h("h1", { class: "detail-title", id: "detailTitle", tabindex: "-1", text: d.name || `pipeline ${d.id}` })); pane.append( h("div", { class: "pipeline-actions" }, h("button", { class: "primary run-pipeline", type: "button", text: "Run", onclick: () => openRunDialog(d), }), h("button", { class: "pipeline-runs", type: "button", text: "Runs", title: `View runs of ${d.name || "this pipeline"}`, onclick: () => { const route = { kind: "runs", pipelineId: d.id }; state.openMenu = null; pushRoute(route); 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 // and Source (which return early) still show it. if (state.runStart) pane.append(renderRunStartDialog()); if (state.pipelineTab === "graph") { pane.append(h("p", { class: "graph-note muted", text: graphNote() })); const stages = d.graph?.stages ?? []; if (!stages.length) { pane.append(h("div", { class: "muted pad", text: PIPELINE_GRAPH_EMPTY })); return pane; } const host = h("div", { class: "graph-host" }); pane.append(host); state.pipelineGraph = mountGraph(host, d.graph, { expanded: state.pipelineGraphExpanded, onStageTap: (key) => rt.views.dialogs.openStageDefinition(d, key, `${d.name || "Pipeline"} · v${d.version}`), selectedKey: state.pipelineGraphSelection, onSelectionChange: (key) => { // The graph has already opened or closed its own definition pane; record // the destination in the URL without rebuilding the graph. state.pipelineGraphSelection = key; const id = state.selectedPipelineId; if (!id) return; const version = state.pipelineRequestedVersion ?? 0; pushRoute( key ? { kind: "pipelineStage", id, version, stageKey: key } : { kind: "pipeline", id, version }, ); }, onExpandedChange: (value) => { state.pipelineGraphExpanded = value; writeGraphExpanded(value); }, }); 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; } pane.append(h("div", { class: "detail-subtitle muted", text: pipelineSubtitle({ ...d, stages: d.graph?.stages?.length ?? d.stages }) })); const rows = h("div", { class: "kv" }); for (const field of summaryFields(d)) { rows.append( h( "div", { class: "kv-row" }, h("span", { class: "kv-key", text: field.key }), h("span", { class: `kv-val${field.monospace ? " monospace" : ""}`, text: field.value }), ), ); } pane.append(rows); if (rt.views?.schedules) pane.append(rt.views.schedules.renderPipelineSchedules(d)); pane.append( h( "button", { class: "section-toggle", onclick: () => { state.versionsExpanded = !state.versionsExpanded; renderContent(); }, }, h("span", { class: "chevron", text: state.versionsExpanded ? "\u25be" : "\u25b8" }), h("span", { text: "Versions" }), ), ); if (state.versionsExpanded) { const versions = d.versions ?? []; const body = h("div", { class: "section-body versions-list" }); if (!versions.length) { body.append(h("div", { class: "muted", text: "No versions recorded." })); } else { for (const version of versions) { const row = versionRow(version); body.append( h( "div", { class: "version-row" }, h("span", { class: "version-title", text: row.versionLabel }), h("span", { class: "muted", text: row.stagesText }), row.createdText ? h("span", { class: "muted", text: row.createdText }) : null, ), ); } } pane.append(body); } return pane; } async function refreshPipelines() { try { state.pipelines = await repo.listPipelines(); state.pipelinesLoaded = true; } catch (error) { state.error = describeError(error); } } function pipelineSortLabel(key) { return (PIPELINE_SORTS.find((option) => option.key === key) ?? PIPELINE_SORTS[0]).label; } function clearPipelineFilters() { state.pipelineFilters = { ...EMPTY_PIPELINE_FILTERS }; renderContent(); } return { renderPipelineList, renderPipelineDetail, fillPipelineRows, clearPipelineFilters, refreshPipelines, }; }