chore: remove the JavaScript web client and the Kotlin Android app; the Flutter app replaces both

This commit is contained in:
2026-10-23 21:46:58 +01:00
parent 7958d1830e
commit 8527506da1
373 changed files with 105 additions and 107868 deletions
-247
View File
@@ -1,247 +0,0 @@
// Pure, DOM-free logic for the run-level operator actions the browser client
// offers on a run detail: the pending human decision (R11), cancel (R12), retry
// / restart (R13) and rename (R14). Ported from the Android client so the
// browser asks for and shows exactly the same things:
// ui/Decision.kt PendingDecision, DecisionOption,
// pendingDecision, decisionTargetLabel,
// DecisionDraft
// data/protocol/HumanDecision.kt lastWaitingStep, waitingPrompt,
// waitingOptions, humanOptions
// ui/components/DecisionPrompt.kt the decision card and sheet wording
// ui/screens/RunDetailScreen.kt the cancel/retry dialogs, Action failed
//
// Nothing here touches the DOM or imports the app: the decision model, the
// action eligibility rules and every user-visible string are unit-tested without
// a browser. The caller sets each string with textContent, never innerHTML.
import { nodeLabel, resolveTarget, runLabelFor } from "./runDetail.js";
/** Run status while parked on a person (mirrors protocol.RunStatusWaiting). */
export const RUN_STATUS_WAITING = "waiting";
/** The waiting step's status, i.e. the step a decision answers. */
export const STEP_STATUS_WAITING = "waiting";
/** Run status a retry is offered for. */
export const RUN_STATUS_FAILED = "failed";
/** Waiting evidence keys, the wire contract the server records. */
export const WAITING_PROMPT_KEY = "prompt";
export const WAITING_OPTIONS_KEY = "options";
// ---------------------------------------------------------------------------
// Decision evidence (data/protocol/HumanDecision.kt)
// ---------------------------------------------------------------------------
function str(value) {
return value == null ? "" : String(value);
}
/**
* The most recent step a run is waiting on (the last waiting step), or null when
* no step is waiting. Mirrors `tui.lastWaitingStep` / `HumanDecision.kt`.
*/
export function lastWaitingStep(steps) {
const list = steps ?? [];
for (let index = list.length - 1; index >= 0; index -= 1) {
if (list[index]?.status === STEP_STATUS_WAITING) return list[index];
}
return null;
}
/**
* The recorded operator instructions from a waiting step's output, or "" when
* none were recorded. Mirrors `protocol.WaitingPrompt`.
*/
export function waitingPrompt(output) {
const value = output?.[WAITING_PROMPT_KEY];
return typeof value === "string" ? value : "";
}
/**
* The recorded selectable options from a waiting step's output, in recorded
* order. Strings only, a malformed/blank entry dropped, an absent key yields an
* empty list — exactly like `protocol.WaitingOptions` / `waitingOptions`.
*/
export function waitingOptions(output) {
const value = output?.[WAITING_OPTIONS_KEY];
if (!Array.isArray(value)) return [];
return value.filter((entry) => typeof entry === "string" && entry.trim() !== "");
}
/**
* A stage's selectable outcomes: its non-`error` edges in sorted order. Mirrors
* `stage.HumanOptions`, the fallback when a waiting step recorded no options.
*/
export function humanOptions(edges) {
return Object.keys(edges ?? {})
.filter((key) => key !== "error")
.sort();
}
/**
* The resolved target label for one option: the author's target with the `#`
* shorthand resolved and terminals named as the graph names them. Blank when the
* option's edge is not declared, so the sheet omits the detail.
*/
export function decisionTargetLabel(option, target) {
if (target == null || String(target).trim() === "") return "";
return nodeLabel(resolveTarget(option, target));
}
/**
* The pending decision a run is waiting on, or null when it is not waiting (or
* recorded no selectable options). The waiting step's own evidence wins over the
* pinned graph; the graph only supplies the target labels and, for a step from
* an older server, the option set itself. Mirrors `pendingDecision`.
*/
export function pendingDecision(run) {
if (run == null || run.status !== RUN_STATUS_WAITING) return null;
if (Number(run.export_pending_sequence) > 0) return null;
const step = lastWaitingStep(run.steps ?? []);
const stepStage = str(step?.stage).trim() !== "" ? String(step.stage) : "";
const runStage = str(run.current_stage).trim() !== "" ? String(run.current_stage) : "";
const stageKey = stepStage !== "" ? stepStage : runStage;
if (stageKey === "") return null;
const declared = (run.graph?.stages ?? []).find((candidate) => candidate?.key === stageKey) ?? null;
if (declared?.type && declared.type !== "human") return null;
const recorded = waitingOptions(step?.output);
const keys = recorded.length > 0 ? recorded : humanOptions(declared?.edges);
if (keys.length === 0) return null;
const edges = declared?.edges ?? {};
const options = keys.map((key) => ({ key, target: decisionTargetLabel(key, edges[key]) }));
const stepPrompt = waitingPrompt(step?.output);
const instructions = stepPrompt.trim() !== "" ? stepPrompt : str(declared?.prompt);
return {
runId: run.id,
runLabel: runLabelFor(run),
stageKey,
instructions,
options,
};
}
/**
* The operator's in-progress answer: the chosen option and optional feedback.
* Pure, so the deliberate-confirm rule (nothing is sent until an option is
* chosen and Confirm is pressed) is unit-tested without a device. Mirrors
* `DecisionDraft`.
*/
export class DecisionDraft {
constructor(selected = null, feedback = "") {
this.selected = selected;
this.feedback = feedback;
}
/** A decision is only sendable once the operator has chosen one option. */
get canSubmit() {
return typeof this.selected === "string" && this.selected.trim() !== "";
}
/** Selecting an option is not an answer: it only enables the confirm. */
select(option) {
return new DecisionDraft(option, this.feedback);
}
/** Feedback is optional and carried verbatim (trimmed by the sender). */
withFeedback(text) {
return new DecisionDraft(this.selected, String(text ?? ""));
}
}
// ---------------------------------------------------------------------------
// Action eligibility (RunDetailScreen.kt)
// ---------------------------------------------------------------------------
/** Cancel is offered only while the run is executing. */
export function canCancel(run) {
return (Boolean(run?.executing) || (run?.status === RUN_STATUS_WAITING && Number(run.export_pending_sequence) > 0)) && !run.cancel_requested && !run.cleanup_unconfirmed;
}
/** Retry is offered only for a loaded, non-executing, `failed` run. */
export function canRetry(run) {
return run != null && !run.executing && run.status === RUN_STATUS_FAILED;
}
/** The retry modes available for a run: resume (default) and restart. */
export function retryModes(run) {
return canRetry(run) ? ["resume", "restart"] : [];
}
/**
* A fresh idempotency key for a retry request. The server requires one and caps
* it at 128 characters (PipelinesRepository.MAX_REQUEST_KEY); this stays well
* inside that bound and unique per attempt.
*/
export function retryRequestKey(runId, now = Date.now(), random = Math.random) {
const suffix = Math.floor((Number(random()) || 0) * 1e9).toString(36);
return `web-retry-${runId}-${now}-${suffix}`;
}
// ---------------------------------------------------------------------------
// Wording (DecisionPrompt.kt / RunDetailScreen.kt), verbatim
// ---------------------------------------------------------------------------
export const DECISION_CARD_TITLE = "Waiting for your decision";
export const DECISION_ACTION = "Decide";
export const FEEDBACK_LABEL = "Feedback (optional)";
export const DECISION_CANCEL = "Cancel";
export const DECISION_CONFIRM = "Confirm decision";
export const DECISION_SENDING = "Sending…";
export const CANCEL_DIALOG_MESSAGE = "This asks the server to stop the active run.";
export const CANCEL_CONFIRM = "Cancel run";
export const RETRY_DIALOG_MESSAGE =
"Only failed runs can be retried. The server starts a new run from the same input.";
export const RETRY_CONFIRM = "Retry";
export const DISMISS_KEEP = "Keep";
// The restart confirm is browser-only (Android exposes resume alone): it states
// plainly that it replays the whole pipeline instead of resuming the failed
// stage, so the more destructive choice is never ambiguous.
export const RESTART_CONFIRM = "Restart from start";
export const RESTART_DIALOG_MESSAGE =
"This replays the whole pipeline from the start instead of resuming the failed stage.";
export const RENAME_ACTION = "Rename";
export const RENAME_SAVE = "Save";
export const RENAME_CANCEL = "Cancel";
export const RENAME_FIELD_LABEL = "Run title";
export const ACTION_FAILED_TITLE = "Action failed";
export const ACTION_FAILED_OK = "OK";
/** The decision card's meta line: `{stage} · run {id} · {runLabel}`. */
export function decisionCardMeta(decision) {
return `${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}`;
}
/** The sheet title: `Decide {stage}`. */
export function decisionSheetTitle(stageKey) {
return `Decide ${stageKey}`;
}
/** The sheet meta line: `run {id} · {runLabel}`. */
export function decisionSheetMeta(decision) {
return `run ${decision.runId} · ${decision.runLabel}`;
}
/** The option's target line, `→ {target}`, or "" when the target is unknown. */
export function optionTargetText(target) {
return String(target ?? "").trim() === "" ? "" : `→ ${target}`;
}
/** The cancel dialog's title: `Cancel run {id}?`. */
export function cancelDialogTitle(runId) {
return `Cancel run ${runId}?`;
}
/** The retry dialog's title: `Retry run {id}?`. */
export function retryDialogTitle(runId) {
return `Retry run ${runId}?`;
}
/** The restart dialog's title: `Restart run {id}?`. */
export function restartDialogTitle(runId) {
return `Restart run ${runId}?`;
}
-2716
View File
File diff suppressed because it is too large Load Diff
-45
View File
@@ -1,45 +0,0 @@
// Artifacts are documents, not app destinations. Android can capture even
// _blank links inside an installed PWA's scope; use an explicit VIEW hand-off
// there, retaining ordinary URLs for copy/share and every other environment.
export function artifactBrowserLinkProps(value, environment = globalThis) {
if (typeof value !== "string" || value.trim() === "") return null;
let url;
try {
url = new URL(String(value ?? ""), environment.location?.href);
} catch {
return null;
}
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;
const standalone = environment.navigator?.standalone === true ||
environment.matchMedia?.("(display-mode: standalone)")?.matches === true ||
environment.matchMedia?.("(display-mode: fullscreen)")?.matches === true;
const userAgent = environment.navigator?.userAgent ?? "";
const android = /Android/i.test(userAgent);
// An implicit HTTPS VIEW intent can resolve straight back to this WebAPK.
// Pin the browser family, never the installed app's link-capturing package.
const browserPackage = /EdgA\//i.test(userAgent) ? "com.microsoft.emmx"
: /SamsungBrowser\//i.test(userAgent) ? "com.sec.android.app.sbrowser"
: /OPR\//i.test(userAgent) ? "com.opera.browser"
: /Firefox\//i.test(userAgent) ? "org.mozilla.firefox"
: "com.android.chrome";
// Intent.parseUri uses the LAST #Intent marker, so an original document
// fragment remains data. Every field after our marker is fixed or encoded;
// untrusted artifact names/fragments cannot inject intent extras or packages.
const href = android && standalone
? `intent:${url.href.slice(url.protocol.length)}#Intent;scheme=${url.protocol.slice(0, -1)};action=android.intent.action.VIEW;category=android.intent.category.BROWSABLE;package=${browserPackage};S.browser_fallback_url=${encodeURIComponent(url.href)};end`
: url.href;
return { href, target: "_blank", rel: "external noopener noreferrer", referrerpolicy: "no-referrer" };
}
/** Recognize same-origin artifacts, including root-relative Markdown links;
* never turn arbitrary SPA paths or javascript/data URLs into navigation. */
export function isLocalArtifactLink(value, base) {
if (!String(value ?? "").startsWith("/artifacts/") && !/^https?:\/\//i.test(String(value ?? ""))) return false;
try {
const url = new URL(value, base);
return url.origin === new URL(base).origin && url.pathname.startsWith("/artifacts/");
} catch {
return false;
}
}
-52
View File
@@ -1,52 +0,0 @@
// File sharing never falls back to sending a private artifact URL. Keep prepared
// files local to the owning button so a slow fetch can be shared on a fresh tap.
const prepared = new WeakMap();
const pending = new WeakSet();
export function canShareFiles(environment = globalThis) {
return typeof environment.navigator?.share === "function" &&
typeof environment.navigator?.canShare === "function" &&
typeof environment.File === "function";
}
export async function shareArtifactFile(resolved, artifact, owner, environment = globalThis) {
if (!resolved || !canShareFiles(environment)) return { state: "error", message: "File sharing is not supported in this browser. Use Open in browser to save the file." };
if (pending.has(owner)) return { state: "busy", message: "Preparing file…" };
pending.add(owner);
try {
let entry = prepared.get(owner);
if (!entry || entry.url !== resolved) {
const response = await environment.fetch(resolved, { credentials: "same-origin", redirect: "error" });
if (!response.ok) throw new Error(`Could not fetch the artifact (HTTP ${response.status}).`);
const blob = await response.blob();
const name = String(artifact?.name || new URL(resolved).pathname.split("/").pop() || "artifact")
.split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f]/g, "_") || "artifact";
const file = new environment.File([blob], name, { type: blob.type || artifact?.content_type || "application/octet-stream" });
entry = { url: resolved, file };
if (!environment.navigator.canShare({ files: [file] })) {
return { state: "error", message: "This browser cannot share this file type. Use Open in browser to save the file." };
}
prepared.set(owner, entry);
}
if (owner.isConnected === false) {
prepared.delete(owner);
return { state: "canceled", message: "Sharing canceled." };
}
// Fetching may outlast the browser's transient activation. Do not attempt a
// doomed share or substitute a URL: the next tap uses the prepared file.
if (environment.navigator.userActivation?.isActive === false) {
return { state: "ready", message: "File ready. Tap Share again to choose where to send it." };
}
await environment.navigator.share({ files: [entry.file] });
prepared.delete(owner);
return { state: "shared", message: "File shared." };
} catch (error) {
if (error?.name === "AbortError") return { state: "canceled", message: "Sharing canceled." };
if (error?.name === "NotAllowedError" && prepared.has(owner)) {
return { state: "ready", message: "Sharing was blocked. Tap Share again, or use Open in browser to save the file." };
}
return { state: "error", message: "Could not share the file. Use Open in browser to save it, or try Share again." };
} finally {
pending.delete(owner);
}
}
-20
View File
@@ -1,20 +0,0 @@
// The run artifacts' view preference: a gallery of tiles (the default) or a
// compact list. It belongs to the operator, not the run, so it survives reloads.
export const ARTIFACT_VIEW_KEY = "pipelines.web.artifactView.v1";
export function readArtifactView(storage = globalThis.localStorage) {
try {
return storage?.getItem(ARTIFACT_VIEW_KEY) === "list" ? "list" : "gallery";
} catch {
return "gallery";
}
}
export function writeArtifactView(value, storage = globalThis.localStorage) {
try {
storage?.setItem(ARTIFACT_VIEW_KEY, value === "list" ? "list" : "gallery");
} catch {
// Storage may be unavailable; the in-memory choice still applies.
}
}
-530
View File
@@ -1,530 +0,0 @@
// Pure, DOM-free artifact derivation for the run detail, ported from the Android
// client so the browser says and does exactly the same thing:
// ui/ArtifactGroups.kt presentedArtifacts, runArtifactGroups, artifactsEmptyMessage
// ui/Format.kt artifactsSummary, artifactCaptureNotes, humanBytes, content-type tests
// ui/graph/ArtifactType.kt artifactKind, artifactKindLabel
// ui/graph/Artifacts.kt the gallery's group/visit/tile vocabulary
// ui/graph/ArtifactViewer.kt pagedArtifacts, viewerIndexByUrl, pagedIndex, position label
// ui/graph/SessionExport.kt sessionExportFile
// ui/screens/Timeline.kt the display visit number (control.visit, else position + 1)
// ui/ArtifactType.kt the file-kind classification vocabulary
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// wording, ordering, counting and formatting can be unit-tested without a browser.
// The tile/overlay wiring lives in app.js.
import { resolveArtifactUrl } from "./serverUrl.js";
/**
* The retired markdown session export file name. Nothing writes it any more, but
* a run recorded before the HTML-only change still lists `session.md`: it is
* dated evidence that is never presented, so it is hidden from every artifact
* listing rather than shown beside the session html. Mirrors
* ArtifactGroups.kt LEGACY_SESSION_MARKDOWN_ARTIFACT.
*/
export const LEGACY_SESSION_MARKDOWN_ARTIFACT = "session.md";
/**
* The "capture pending" wording shared by a running visit's summary and the
* run-level empty state, so the two never spell it differently.
*/
export const ARTIFACT_CAPTURE_PENDING = "capture pending";
/**
* What an artifact's file type is, from the app's point of view: the two media
* kinds the gallery previews (image, video) and the file kinds it labels with a
* type glyph. Mirrors graph/ArtifactType.kt ArtifactKind.
*/
export const ArtifactKind = Object.freeze({
Image: "Image",
Video: "Video",
Audio: "Audio",
Pdf: "Pdf",
Json: "Json",
Archive: "Archive",
Spreadsheet: "Spreadsheet",
Log: "Log",
Code: "Code",
Document: "Document",
Other: "Other",
});
const ARCHIVE_EXTENSIONS = new Set([
"zip", "tar", "gz", "tgz", "bz2", "xz", "rar", "7z", "jar", "war",
]);
const ARCHIVE_MIMES = new Set([
"application/zip",
"application/gzip",
"application/x-tar",
"application/x-7z-compressed",
"application/x-rar-compressed",
"application/java-archive",
]);
const SPREADSHEET_EXTENSIONS = new Set(["csv", "tsv", "xls", "xlsx", "ods"]);
const SPREADSHEET_MIMES = new Set([
"text/csv",
"text/tab-separated-values",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
]);
const CODE_EXTENSIONS = new Set([
"kt", "kts", "java", "go", "py", "rb", "php", "rs", "c", "h", "cc", "cpp",
"hpp", "cs", "js", "jsx", "ts", "tsx", "mjs", "cjs", "swift", "scala", "sh",
"bash", "zsh", "fish", "ps1", "sql", "yaml", "yml", "toml", "ini", "xml",
"gradle", "properties", "proto",
]);
const CODE_MIMES = new Set([
"application/xml",
"application/x-yaml",
"application/javascript",
"text/javascript",
"text/x-python",
"text/x-java-source",
"text/x-kotlin",
"application/x-sh",
"application/x-httpd-php",
"application/sql",
]);
const DOCUMENT_EXTENSIONS = new Set([
"txt", "md", "markdown", "rst", "doc", "docx", "odt", "rtf", "html", "htm",
]);
/** The text file kinds the browser can render in the artifact viewer. */
const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "txt"]);
const DOCUMENT_MIMES = new Set([
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/rtf",
]);
const KIND_LABELS = Object.freeze({
[ArtifactKind.Image]: "Image",
[ArtifactKind.Video]: "Video",
[ArtifactKind.Audio]: "Audio",
[ArtifactKind.Pdf]: "PDF",
[ArtifactKind.Json]: "JSON",
[ArtifactKind.Archive]: "Archive",
[ArtifactKind.Spreadsheet]: "Spreadsheet",
[ArtifactKind.Log]: "Log",
[ArtifactKind.Code]: "Code",
[ArtifactKind.Document]: "Document",
[ArtifactKind.Other]: "File",
});
/** Whether an artifact's content type is an image the gallery can preview. */
export function isImageContentType(contentType) {
return String(contentType ?? "").startsWith("image/");
}
/**
* Whether an artifact's content type is a video. Videos are shown in the gallery
* as a poster-style tile with a play marker; they are never decoded inline and
* never autoplay.
*/
export function isVideoContentType(contentType) {
return String(contentType ?? "").startsWith("video/");
}
/**
* The artifacts of one visit as the operator sees them: the recorded files with
* the retired markdown session export filtered out. Every artifact listing
* derives from this one function, so a visit never shows a session markdown
* beside the session html and the recorded counts can never disagree with the
* tiles. Duplicate names are kept, not deduped: an artifact's identity is its
* recorded url, not its name. Mirrors ArtifactGroups.kt presentedArtifacts.
*/
export function presentedArtifacts(step) {
return (step?.artifacts ?? []).filter(
(artifact) => artifact?.name !== LEGACY_SESSION_MARKDOWN_ARTIFACT,
);
}
/**
* The files the turn protocol itself writes for every visit. They are audit
* evidence, not stage output: the artifact surfaces lead with what the stage
* actually produced, and these live behind Audit & debug. Names are the exact
* server-recorded ones.
*/
export const SYSTEM_ARTIFACT_NAMES = Object.freeze([
"input.md",
"memory.md",
"output.md",
"session.html",
]);
/** True for a turn-owned file (input/memory/output/session). Pure. */
export function isSystemArtifact(artifact) {
return SYSTEM_ARTIFACT_NAMES.includes(String(artifact?.name ?? ""));
}
/** A visit's stage-produced artifacts: everything except the system files. */
export function stageArtifacts(step) {
const repairs = new Set((step?.session_export_repairs ?? []).map((entry) => entry?.html).filter(Boolean));
return presentedArtifacts(step).filter((artifact) => !isSystemArtifact(artifact) && !repairs.has(artifact?.name));
}
/** A visit's system files, newest-listing order preserved. */
export function systemArtifacts(step) {
const repairs = new Set((step?.session_export_repairs ?? []).map((entry) => entry?.html).filter(Boolean));
return presentedArtifacts(step).filter((artifact) => isSystemArtifact(artifact) || repairs.has(artifact?.name));
}
/** How many files the capture excluded for `step` (absent means none). */
export function artifactsSkipped(step) {
return Number(step?.artifacts_skipped ?? 0) || 0;
}
/** How many files the capture omitted for `step` (absent means none). */
export function artifactsTruncated(step) {
return Number(step?.artifacts_truncated ?? 0) || 0;
}
/** The extension of `name` (lowercased), or "" when it carries none. */
function extensionOf(name) {
const text = String(name ?? "");
const dot = text.lastIndexOf(".");
return dot === -1 ? "" : text.slice(dot + 1).toLowerCase();
}
/**
* The gallery kind of an artifact from its `contentType` (server-sniffed, may
* carry parameters) and its `name` (the extension is the fallback when the sniff
* is a generic text/plain or application/octet-stream). Image and video come
* straight from the content type; the rest match the normalised mime first, then
* the name's extension. Pure and total. Mirrors graph/ArtifactType.kt artifactKind.
*/
export function artifactKind(contentType, name) {
if (isImageContentType(contentType)) return ArtifactKind.Image;
if (isVideoContentType(contentType)) return ArtifactKind.Video;
const ct = String(contentType ?? "");
const mime = ct.split(";")[0].trim().toLowerCase();
const ext = extensionOf(name);
if (mime.startsWith("audio/")) return ArtifactKind.Audio;
if (mime === "application/pdf" || ext === "pdf") return ArtifactKind.Pdf;
if (mime.includes("json") || ext === "json") return ArtifactKind.Json;
if (ARCHIVE_MIMES.has(mime) || ARCHIVE_EXTENSIONS.has(ext)) return ArtifactKind.Archive;
if (SPREADSHEET_MIMES.has(mime) || SPREADSHEET_EXTENSIONS.has(ext)) return ArtifactKind.Spreadsheet;
if (ext === "log") return ArtifactKind.Log;
if (mime === "text/html") return ArtifactKind.Document;
if (CODE_MIMES.has(mime) || CODE_EXTENSIONS.has(ext)) return ArtifactKind.Code;
if (mime.startsWith("text/") || DOCUMENT_MIMES.has(mime) || DOCUMENT_EXTENSIONS.has(ext)) {
return ArtifactKind.Document;
}
return ArtifactKind.Other;
}
/**
* The word that names `kind` where the gallery shows its glyph but must also say
* the type in prose (a screen reader cannot read an icon). The same
* classification `artifactKind` draws from, so glyph and word never disagree.
*/
export function artifactKindLabel(kind) {
return KIND_LABELS[kind] ?? "File";
}
/**
* Whether an artifact is text the reader can render as markdown in the viewer:
* `text/markdown` or `text/plain` (parameters ignored), or a `.md`, `.markdown`
* or `.txt` name. The viewer uses the page's existing markdown renderer, so these
* are the text files it is allowed to fetch and draw. Pure and total, mirroring
* the content-type tests above.
*/
export function isMarkdownArtifact(contentType, name) {
const mime = String(contentType ?? "").split(";")[0].trim().toLowerCase();
if (mime === "text/markdown" || mime === "text/plain") return true;
return MARKDOWN_EXTENSIONS.has(extensionOf(name));
}
/**
* Whether an artifact opens inside the full-screen viewer: the two media kinds
* the gallery already previewed, plus the markdown/text documents it now renders
* itself. The kind gate keeps a `text/plain` `.log`, `.py` or `.csv` an external
* file: those are evidence, not prose. This is the one predicate the grid tiles,
* paging and the viewer share, so they cannot disagree about the list.
*/
export function isViewerArtifact(contentType, name) {
if (isImageContentType(contentType) || isVideoContentType(contentType)) return true;
return artifactKind(contentType, name) === ArtifactKind.Document && isMarkdownArtifact(contentType, name);
}
/**
* Human-readable byte size, matching Android Format.kt humanBytes (and the TUI):
* whole bytes under 1 KiB, otherwise one decimal with a binary unit
* (KiB/MiB/GiB/TiB/PiB/EiB).
*/
export function humanBytes(size) {
const value = Math.trunc(Number(size) || 0);
const unit = 1024;
if (value < unit) return `${value} B`;
let div = unit;
let exp = 0;
let scaled = Math.trunc(value / unit);
while (scaled >= unit) {
div *= unit;
exp++;
scaled = Math.trunc(scaled / unit);
}
return `${(value / div).toFixed(1)} ${"KMGTPE"[exp]}iB`;
}
/**
* The display visit number for a step at `index` within its stage's ordered
* visits: the recorded control visit when positive, otherwise the position
* within the stage. Mirrors Timeline.kt (`control.visit > 0 ? visit : index + 1`).
*/
export function displayVisit(step, index) {
const visit = step?.control?.visit;
return Number(visit) > 0 ? Number(visit) : index + 1;
}
/** True for a shared public file's recorded name (`public/...`). */
function isPublicName(name) {
return String(name ?? "").startsWith("public/");
}
/**
* A visit's stage artifacts, with each shared public file attributed to the first
* visit that recorded it. The server records the whole public directory on every
* model visit so a resume can rebuild each turn's file list; the artifact surface
* must not repeat every shared file once per later stage.
*/
export function visitArtifacts(step, runSteps) {
const all = stageArtifacts(step);
if (!step || !runSteps?.length) return all;
const seen = new Set();
const ordered = [...runSteps].sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0));
for (const candidate of ordered) {
if (candidate === step || candidate?.sequence === step.sequence) break;
for (const artifact of stageArtifacts(candidate)) {
if (isPublicName(artifact?.name)) seen.add(artifact.name);
}
}
return all.filter((artifact) => !isPublicName(artifact?.name) || !seen.has(artifact.name));
}
/**
* Groups a run's artifacts by stage and visit, attributing each shared public file
* to the visit that first recorded it. Stages keep first-appearance
* order and each stage's visits are ordered by sequence, with the display visit
* number above. Only visits that recorded at least one presented artifact
* produce a group, so an empty capture never yields an empty group and an
* artifact-less run yields an empty list. Mirrors ArtifactGroups.kt
* runArtifactGroups + Timeline.kt runTimeline.
*/
export function artifactGroups(steps) {
const list = steps ?? [];
if (list.length === 0) return [];
// groupBy(stage) keeps first-appearance order (a Map preserves insertion
// order); each stage's visits are then ordered by sequence.
const orderedSteps = [...list].sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0));
const attributed = new Map();
const seenPublic = new Set();
for (const step of orderedSteps) {
const artifacts = stageArtifacts(step).filter((artifact) => {
if (!isPublicName(artifact?.name)) return true;
if (seenPublic.has(artifact.name)) return false;
seenPublic.add(artifact.name);
return true;
});
attributed.set(step, artifacts);
}
const visitsByStage = new Map();
for (const step of list) {
const stage = step?.stage ?? "";
if (!visitsByStage.has(stage)) visitsByStage.set(stage, []);
visitsByStage.get(stage).push(step);
}
const groups = [];
for (const [stageKey, visits] of visitsByStage) {
const ordered = [...visits].sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0));
ordered.forEach((step, index) => {
const artifacts = attributed.get(step) ?? [];
if (artifacts.length === 0) return;
groups.push({ stageKey, visit: displayVisit(step, index), artifacts });
});
}
return groups;
}
/**
* The explicit message shown where the run's artifacts gallery would be when
* there are none: while the run is executing it uses the same "capture pending"
* wording as a running visit, otherwise it says plainly that nothing was
* recorded. Mirrors ArtifactGroups.kt artifactsEmptyMessage.
*/
export function artifactsEmptyMessage(executing) {
return executing
? `Artifacts · ${ARTIFACT_CAPTURE_PENDING}`
: "No artifacts recorded for this run.";
}
/**
* The run summary's Artifacts section header: the title, how many artifacts the
* run recorded (the title takes its singular form for exactly one) and
* "partial capture" when any visit excluded or omitted files. It reuses the
* shared empty message, so a run with nothing recorded still gets a
* self-describing header. The recorded count is exactly the number of tiles
* `artifactGroups` yields. Mirrors ArtifactGroups.kt runArtifactsHeader.
*/
export function artifactsHeader(steps, executing) {
const list = steps ?? [];
const recorded = artifactGroups(list).reduce((sum, group) => sum + group.artifacts.length, 0);
if (recorded === 0) return artifactsEmptyMessage(executing);
const partial = list.some((step) => artifactsSkipped(step) > 0 || artifactsTruncated(step) > 0);
let label = `${recorded === 1 ? "Artifact" : "Artifacts"} · ${recorded} recorded`;
if (partial) label += " · partial capture";
return label;
}
/**
* The per-visit artifacts summary label: "capture pending" while the visit runs,
* "not recorded for this visit" for a finished visit with no artifacts,
* otherwise the recorded count plus " · partial capture" when files were
* excluded or omitted. Mirrors Format.kt artifactsSummary.
*/
export function artifactsSummary(step, count = null) {
const recorded = count ?? stageArtifacts(step).length;
if (recorded === 0) {
const state = step?.status === "running" ? ARTIFACT_CAPTURE_PENDING : "not recorded for this visit";
return `Artifacts · ${state}`;
}
let label = `Artifacts · ${recorded} recorded`;
if (artifactsSkipped(step) > 0 || artifactsTruncated(step) > 0) label += " · partial capture";
return label;
}
/**
* The partial-capture notes, one line per non-zero count and nothing when the
* capture was complete. An empty artifact list yields no notes at all, so the
* notes never accompany the empty-state summary. Mirrors Format.kt
* artifactCaptureNotes.
*/
export function artifactCaptureNotes(step) {
const notes = [];
if (presentedArtifacts(step).length === 0) return notes;
const skipped = artifactsSkipped(step);
const truncated = artifactsTruncated(step);
if (skipped > 0) notes.push(`${skipped} files excluded from artifact capture.`);
if (truncated > 0) notes.push(`${truncated} files omitted by artifact capture limits.`);
return notes;
}
/**
* The artifacts `groups` hold that the full-screen viewer can page through, in
* the exact order the gallery draws them (group by group, each group's images,
* videos and markdown/text documents in recorded order): the neighbours a
* swipe/keyboard step visits, so the viewer walks the same list the grid showed.
* Other artifacts open externally and are not part of it. Mirrors
* ArtifactViewer.kt pagedArtifacts, extended for markdown-first stage turns.
*/
export function pagedArtifacts(groups) {
const viewable = [];
for (const group of groups ?? []) {
for (const artifact of group?.artifacts ?? []) {
if (isViewerArtifact(artifact?.content_type, artifact?.name)) viewable.push(artifact);
}
}
return viewable;
}
/**
* Each viewer-selectable artifact's url mapped to its position in
* `pagedArtifacts`, the same ordered list the viewer pages through. The grid's
* tiles resolve their viewer index here, so tile and viewer derive from one
* source and cannot drift. The first occurrence of a url wins. Mirrors
* ArtifactViewer.kt viewerIndexByUrl.
*/
export function viewerIndexByUrl(groups) {
const indices = new Map();
pagedArtifacts(groups).forEach((artifact, index) => {
if (!indices.has(artifact.url)) indices.set(artifact.url, index);
});
return indices;
}
/**
* The index paging from `current` by `delta` within a list of `count`, clamped
* at both ends so a page never wraps (and an empty list is index 0). The one
* paging rule the viewer's buttons share. Mirrors ArtifactViewer.kt pagedIndex.
*/
export function pagedIndex(current, delta, count) {
if (count <= 0) return 0;
return Math.min(Math.max(current + delta, 0), count - 1);
}
/** The viewer's position label, e.g. `2 of 5 · image/png`. Mirrors ArtifactViewer.kt. */
export function artifactViewerPositionLabel(index, count, contentType) {
const type = String(contentType ?? "").split(";")[0].trim() || "artifact";
return `${index + 1} of ${count} · ${type}`;
}
/**
* The html session export `step` recorded, matched to the visit's recorded
* artifacts by exact name, or null when the visit has no export to open. A visit
* that recorded no export, whose export name is blank, or whose file is missing
* from a truncated listing yields null. Mirrors SessionExport.kt sessionExportFile.
*/
export function effectiveSessionExport(step) {
const recorded = step?.session_export ?? null;
const id = String(step?.session_id || recorded?.session_id || "");
const original = recorded?.session_id && id && recorded.session_id !== id ? null : recorded;
const repairs = [...(step?.session_export_repairs ?? [])].reverse()
.filter((entry) => id !== "" && entry?.session_id === id &&
(!original?.backend || entry.backend === original.backend) &&
(!original?.directory || entry.directory === original.directory));
const hasFile = (entry) => Boolean(entry?.html) && (step?.artifacts ?? []).some((file) =>
file?.name === entry.html && file.size_bytes > 0 &&
(!(entry.html_bytes > 0) || file.size_bytes === entry.html_bytes));
// A failed later attempt must not hide an earlier, verified full repair.
const isComplete = (entry) => entry?.status === "complete" && entry.messages > 0 &&
entry.html_bytes > 0 && !entry.truncated && !entry.diagnostic && hasFile(entry);
return repairs.find(isComplete) ?? (isComplete(original) ? original : null) ?? repairs.find(hasFile) ?? (hasFile(original) ? original : null) ?? repairs[0] ?? original ?? null;
}
export function sessionExportArtifact(step) {
const evidence = effectiveSessionExport(step);
const html = evidence?.html;
if (typeof html !== "string" || html.trim() === "") return null;
return (step?.artifacts ?? []).find((artifact) => artifact?.name === html &&
(!(evidence.html_bytes > 0) || artifact.size_bytes === evidence.html_bytes)) ?? null;
}
/** A recorded ID and an exported document are different facts. Never call a
* recorded session "not recorded" just because its export is missing. */
export function sessionCaptureState(step) {
const evidence = effectiveSessionExport(step);
const sessionId = String(step?.session_id || evidence?.session_id || "");
const artifact = sessionExportArtifact(step);
if (artifact) return { sessionId, evidence, artifact, message: "" };
if (sessionId) {
const recovery = step?.session_export_recovery;
const status = recovery?.status === "pending" || recovery?.status === "running"
? "pending recovery" : evidence?.status === "complete" ? "not available in the artifact inventory" : evidence?.status || "not yet available";
return { sessionId, evidence, artifact: null,
message: `Session ${sessionId} is recorded. Its export is ${status}.${evidence?.diagnostic ? ` ${evidence.diagnostic}` : ""}` };
}
const model = Boolean(step?.model || step?.provider);
const skipped=step?.status==="skipped" || step?.outcome==="skipped";
const stopped=["canceled","interrupted"].includes(step?.status);
return { sessionId, evidence, artifact: null, message: skipped ? "This visit was skipped; no harness session was started." : stopped ? "The stage stopped before a harness session was recorded." : model
? step?.status === "running" ? "The stage session is being created."
: step?.status === "failed" ? `The stage did not create a harness session.${step?.diagnostic ? ` ${step.diagnostic}` : ""}`
: "Runtime error: this model stage has no recorded session identity."
: "This visit has no harness session." };
}
/**
* The absolute url a gallery artifact can be opened at, or null when it cannot
* be resolved against the configured server (blank or invalid). The one place a
* gallery artifact url is resolved, so tiles and the viewer never disagree.
* Re-exported here so callers derive tiles from this module alone.
*/
export function resolvedArtifactUrl(artifact, configuredServerUrl) {
return resolveArtifactUrl(configuredServerUrl, artifact?.url);
}
-224
View File
@@ -1,224 +0,0 @@
// Pure, DOM-free model for the browser client's attention / "Needs you" surface
// (R15). It mirrors android/.../ui/Attention.kt and the wording shown by
// ui/components/AttentionSurface.kt, so the browser's bell, its badge and the
// sheet read exactly what the app reads.
//
// The surface is derived here from the same `list_runs` summaries the runs list
// is folded from (and from any run state already in the page). R10's live
// `run_event` fold feeds these same pure functions the pushed summaries, so the
// ordering and the wording are identical whether a row arrived from a read or a
// push.
//
// Everything in this file is pure: no DOM, no clock, no storage. app.js keeps the
// wiring; a malformed stored value can never throw into the page because decode
// is total. Every server-provided string is only ever compared or rendered,
// never parsed as markup; the caller sets it with textContent.
// ---------------------------------------------------------------------------
// Kinds and qualification
// ---------------------------------------------------------------------------
/**
* The two things the attention surface ranks, most important first. The rank is
* what orders the list; the name is what a dismissal identity is keyed by.
*/
export const AttentionKind = Object.freeze({
Decision: Object.freeze({ name: "Decision", rank: 0 }),
Failed: Object.freeze({ name: "Failed", rank: 1 }),
});
/**
* The attention kind a run status maps to, or null when the run needs nobody. It
* reads the server's own words only (trimmed/lowercased `waiting` and `failed`),
* so queued, running, succeeded, canceled, interrupted and any unknown status
* can never invent an entry.
*/
export function attentionKindOf(status, exportPendingSequence = 0) {
if (Number(exportPendingSequence) > 0 && String(status ?? "").trim().toLowerCase() === "waiting") return null;
switch (String(status ?? "").trim().toLowerCase()) {
case "waiting":
return AttentionKind.Decision;
case "failed":
return AttentionKind.Failed;
default:
return null;
}
}
// ---------------------------------------------------------------------------
// Identity and wording
// ---------------------------------------------------------------------------
/** The identity of one run+kind entry; the unit an explicit dismissal removes. */
export function attentionKey(runId, kind) {
return `${runId}:${kind.name}`;
}
/**
* What one entry asks of the operator, in the operator's words. A failed run
* shows the server's own diagnostic when it recorded one so the line is
* actionable rather than a bare "failed".
*/
export function attentionDetail(kind, run) {
if (kind === AttentionKind.Decision) return "Waiting for your decision";
const diagnostic = String(run?.diagnostic ?? "").trim();
return diagnostic !== "" ? diagnostic : "Run failed";
}
/**
* The one-line secondary text for a row: the pipeline the run belongs to, then
* what it needs. Exactly `{pipeline} · {detail}`, as AttentionSurface.kt draws.
*/
export function attentionRowDescription(entry) {
return `${entry.pipeline} · ${entry.detail}`;
}
/**
* The bell action's accessible name: the bare `Notifications` when nothing needs
* the operator, else the count. The visible badge is drawn only in the second
* case, from the same count.
*/
export function attentionBadgeLabel(count) {
const n = Number(count) || 0;
return n > 0 ? `Notifications, ${n} needing attention` : "Notifications";
}
// ---------------------------------------------------------------------------
// The ordered list
// ---------------------------------------------------------------------------
/**
* The ordered attention list. Every run that needs the operator becomes one
* entry, ranked by kind (decision, then failure), then newest-first within a
* kind (its finish time else its creation time, as the server wrote it), then by
* run id descending so the order is stable and never reshuffles between reads.
* An entry the operator explicitly dismissed never returns. A run status that
* asks nobody is dropped, so the surface can only ever hold actionable work.
*/
export function attentionEntries(runs, dismissed, { since = 0 } = {}) {
const dismissedKeys =
dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []);
return (runs ?? [])
.map((run) => {
const kind = attentionKindOf(run?.status, run?.export_pending_sequence);
if (!kind) return null;
const key = attentionKey(run.id, kind);
if (dismissedKeys.has(key)) return null;
const title = String(run.title ?? "").trim();
const finished = String(run.finished_at ?? "");
const recency = finished.trim() !== "" ? finished : String(run.created_at ?? "");
const at = Date.parse(recency);
if (since > 0 && Number.isFinite(at) && at < since) return null;
return {
runId: run.id,
pipeline: String(run.name ?? ""),
label: title !== "" ? title : String(run.name ?? ""),
kind,
detail: attentionDetail(kind, run),
recency,
key,
};
})
.filter((entry) => entry != null)
.sort(
(a, b) =>
a.kind.rank - b.kind.rank ||
descendingText(a.recency, b.recency) ||
(b.runId > a.runId ? 1 : b.runId < a.runId ? -1 : 0),
);
}
/**
* The start of the operator's local day in epoch ms. "Needs you" is a to-do list
* for what changed now; yesterday's failures are history, not a badge that
* follows every device and browser session for ever.
*/
export function startOfLocalDay(now = Date.now()) {
const date = new Date(now);
date.setHours(0, 0, 0, 0);
return date.getTime();
}
/**
* Captures the entries shown when the sheet opens. Bulk dismissal uses this
* snapshot so entries that arrive while the sheet is open are not removed. A
* defensive copy, so the live list can never mutate what Clear all will apply.
*/
export function attentionDismissalSnapshot(entries) {
return [...(entries ?? [])];
}
// ---------------------------------------------------------------------------
// Dismissal bookkeeping
// ---------------------------------------------------------------------------
/** Adds one identity to the dismissed set, ignoring a blank or already-present key. */
export function attentionDismiss(dismissed, key) {
const next = new Set(dismissed instanceof Set ? dismissed : []);
if (String(key ?? "") !== "") next.add(key);
return next;
}
/**
* Unions a snapshot's identities into the dismissed set. Only the identities in
* the snapshot are added, so an entry that arrived after the sheet opened (and
* is therefore not in the snapshot) is left alone. This is what Clear all does.
*/
export function attentionDismissAll(dismissed, snapshot) {
const next = new Set(dismissed instanceof Set ? dismissed : []);
for (const entry of snapshot ?? []) {
if (entry?.key) next.add(entry.key);
}
return next;
}
// ---------------------------------------------------------------------------
// Persistence
// ---------------------------------------------------------------------------
/**
* The single localStorage key the dismissed identities live under: one JSON
* array of `{runId}:{kind}` strings, with no expiry or TTL of any kind.
*/
export const ATTENTION_STORAGE_KEY = "pipelines.web.attention.v1";
/**
* The one-line JSON a dismissed set is stored as: a JSON array of strings. The
* array is sorted so an unchanged set always encodes to the same bytes.
*/
export function encodeAttentionDismissals(dismissed) {
const keys = [...(dismissed instanceof Set ? dismissed : [])].filter(
(key) => typeof key === "string" && key !== "",
);
keys.sort();
return JSON.stringify(keys);
}
/**
* Decodes a stored value into a dismissed set. Total: blank, unreadable JSON, a
* non-array value and non-string members all decode to empty, so a malformed
* value can never throw into the page.
*/
export function decodeAttentionDismissals(stored) {
const text = stored == null ? "" : String(stored).trim();
if (text === "") return new Set();
let parsed;
try {
parsed = JSON.parse(text);
} catch {
return new Set();
}
if (!Array.isArray(parsed)) return new Set();
return new Set(parsed.filter((key) => typeof key === "string" && key !== ""));
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** Descending compare of two strings, matching the app's `thenByDescending`. */
function descendingText(a, b) {
if (a < b) return 1;
if (a > b) return -1;
return 0;
}
-570
View File
@@ -1,570 +0,0 @@
// Pure, DOM-free logic for the run summary's final-state Changes section and its
// diff viewer, ported from the Android client so the browser says and shows
// exactly the same things (the aggregate is last-visit-wins rather than a sum):
// ui/changes/RunChanges.kt changeKind, changeKindLabel, parseUnifiedPatch,
// runChanges, runChangesHeader, runChangesNote,
// changesListSummary, noChangeDetail,
// patchUnavailableReason, changeEntryTags,
// changeRowMeta, changePositionLabel, gutterWidth
// ui/changes/ChangeDiffViewer.kt the file row, the viewer header/controls/body
// and the honest no-diff/reason wording
// ui/chat/ChatDiffCard.kt diffLineSymbol / diffLineColor (the one diff
// line language shared with the chat edit card)
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// wording, ordering, counting and patch parsing can be unit-tested without a
// browser. The section/viewer wiring lives in app.js. Every server-provided
// string is only ever compared or rendered, never parsed as markup; the caller
// sets it with textContent.
// ---------------------------------------------------------------------------
// Change kind
// ---------------------------------------------------------------------------
/** The three recorded kinds plus the safe `other` fallback for anything else. */
export const ChangeKind = Object.freeze({
Added: "added",
Modified: "modified",
Deleted: "deleted",
Other: "other",
});
/**
* Maps the server's kind token to a ChangeKind. The token is trimmed and
* lowercased; an unrecognised or blank kind stays `other` rather than being
* guessed, so a future server value is shown read-only instead of mislabelled.
* Pure.
*/
export function changeKind(kind) {
switch (str(kind).trim().toLowerCase()) {
case "added":
return ChangeKind.Added;
case "modified":
return ChangeKind.Modified;
case "deleted":
return ChangeKind.Deleted;
default:
return ChangeKind.Other;
}
}
/** The word a file's kind is named by in the list and the diff header. */
export function changeKindLabel(kind) {
switch (kind) {
case ChangeKind.Added:
return "added";
case ChangeKind.Modified:
return "modified";
case ChangeKind.Deleted:
return "deleted";
default:
return "changed";
}
}
/** The kind word as the viewer header shows it, first letter capitalised. */
export function changeKindTitle(kind) {
const label = changeKindLabel(kind);
return label.charAt(0).toUpperCase() + label.slice(1);
}
// ---------------------------------------------------------------------------
// Unified patch parsing
// ---------------------------------------------------------------------------
/** Which kind of line this is within a unified patch. */
export const ChangeLineKind = Object.freeze({
Context: "context",
Add: "add",
Remove: "remove",
});
/**
* Parses a server-recorded unified patch into hunks, lines, line numbers and
* the true `+N -M` stat. The server builds these patches with a Go unified-diff
* writer (internal/filediff), so the shape is a standard `---`/`+++` header,
* optional metadata lines, `@@ -a,b +c,d @@` hunk headers and a ` `/`+`/`-`
* body. Anything unrecognised (a truncated tail, an exotic header) is carried
* verbatim in `headerLines` when it sits before the first hunk, and otherwise
* kept as an unnumbered context line, so the raw view always has the exact
* source while the rendered view shows only lines it can stand behind. A blank
* patch parses to an empty result rather than a fabricated one.
*/
export function parseUnifiedPatch(patch) {
const text = patch == null ? "" : String(patch);
if (text.trim() === "") {
return { raw: "", headerLines: [], hunks: [], added: 0, removed: 0 };
}
const rawLines = text.split("\n");
const headers = [];
const hunks = [];
let current = null;
for (const line of rawLines) {
const hunkStart = parseHunkHeader(line);
if (hunkStart != null) {
if (current) hunks.push(current.build());
current = new HunkBuilder(line, hunkStart.oldStart, hunkStart.oldCount, hunkStart.newStart, hunkStart.newCount);
} else if (line.startsWith("--- ") || line.startsWith("+++ ")) {
// An aggregated entry can contain one complete patch from each
// contributing stage. A new file header closes the preceding hunk
// instead of being rendered as an unnumbered context line in it.
if (current) {
hunks.push(current.build());
current = null;
}
headers.push(line);
} else if (current == null) {
headers.push(line);
} else {
current.lines.push(parseBodyLine(line, current));
}
}
if (current) hunks.push(current.build());
let added = 0;
let removed = 0;
for (const hunk of hunks) {
for (const line of hunk.lines) {
if (line.kind === ChangeLineKind.Add) added++;
else if (line.kind === ChangeLineKind.Remove) removed++;
}
}
return { raw: text, headerLines: headers, hunks, added, removed };
}
/**
* Mutable accumulator for one hunk as it is parsed, carrying the running old/new
* line counters so each body line gets its gutter numbers without a second pass.
*/
class HunkBuilder {
constructor(header, oldStart, oldCount, newStart, newCount) {
this.header = header;
this.oldStart = oldStart;
this.oldCount = oldCount;
this.newStart = newStart;
this.newCount = newCount;
this.lines = [];
this.oldLine = oldStart;
this.newLine = newStart;
}
build() {
return {
header: this.header,
oldStart: this.oldStart,
oldCount: this.oldCount,
newStart: this.newStart,
newCount: this.newCount,
lines: this.lines,
};
}
nextOld() {
return this.oldLine++;
}
nextNew() {
return this.newLine++;
}
}
/**
* The parsed `@@ -oldStart,oldCount +newStart,newCount @@` of a hunk header, or
* null when `line` is not one. A missing count defaults to 1 (the unified-diff
* rule) so a single-line hunk header is still read exactly. Pure.
*/
function parseHunkHeader(line) {
if (!line.startsWith("@@")) return null;
const end = line.indexOf("@@", 2);
if (end < 0) return null;
const ranges = tokenizeRanges(line.substring(2, end));
return ranges == null ? null : { oldStart: ranges[0], oldCount: ranges[1], newStart: ranges[2], newCount: ranges[3] };
}
/** The four numbers of a hunk header's range text, or null when malformed. Pure. */
function tokenizeRanges(body) {
const plus = body.indexOf("+");
const old = plus === -1 ? body : body.slice(0, plus);
const next = plus === -1 ? "" : body.slice(plus + 1);
if (old === "" || next === "") return null;
const oldRange = parseRange(old);
if (oldRange == null) return null;
const newRange = parseRange(next);
if (newRange == null) return null;
return [oldRange[0], oldRange[1], newRange[0], newRange[1]];
}
/** One `-start,count` / `+start,count` side of a hunk header. Pure. */
function parseRange(text) {
let trimmed = text.trim();
if (trimmed.startsWith("-")) trimmed = trimmed.slice(1);
else if (trimmed.startsWith("+")) trimmed = trimmed.slice(1);
if (trimmed === "") return null;
const comma = trimmed.indexOf(",");
const startText = (comma === -1 ? trimmed : trimmed.slice(0, comma)).trim();
const start = intOrNull(startText);
if (start == null) return null;
const countText = (comma === -1 ? "" : trimmed.slice(comma + 1)).trim();
const count = countText === "" ? 1 : intOrNull(countText);
if (count == null) return null;
return [start, count];
}
/** One body line of a hunk, tagged and numbered from `builder`'s counters. */
function parseBodyLine(line, builder) {
if (line.startsWith("+")) {
return { kind: ChangeLineKind.Add, text: line.slice(1), oldLine: 0, newLine: builder.nextNew(), noNewlineMarker: false };
}
if (line.startsWith("-")) {
return { kind: ChangeLineKind.Remove, text: line.slice(1), oldLine: builder.nextOld(), newLine: 0, noNewlineMarker: false };
}
if (line.startsWith("\\")) {
return { kind: ChangeLineKind.Context, text: line, oldLine: 0, newLine: 0, noNewlineMarker: true };
}
if (line.startsWith(" ")) {
return { kind: ChangeLineKind.Context, text: line.slice(1), oldLine: builder.nextOld(), newLine: builder.nextNew(), noNewlineMarker: false };
}
if (line === "") {
return { kind: ChangeLineKind.Context, text: "", oldLine: builder.nextOld(), newLine: builder.nextNew(), noNewlineMarker: false };
}
// A truncated tail or an unexpected marker: keep the text, don't number it.
return { kind: ChangeLineKind.Context, text: line, oldLine: 0, newLine: 0, noNewlineMarker: false };
}
/** The widest line number in a hunk, so its gutter lines up across every row. */
export function gutterWidth(hunk) {
let widest = 0;
for (const line of hunk?.lines ?? []) {
widest = Math.max(widest, Math.max(line.oldLine, line.newLine));
}
return String(Math.max(widest, 1)).length;
}
/** One gutter number padded to `width`; 0 means no number on that side. */
export function gutterText(value, width) {
return value > 0 ? String(value).padStart(width) : " ".repeat(width);
}
// ---------------------------------------------------------------------------
// Change aggregation (ui/changes/RunChanges.kt runChanges)
// ---------------------------------------------------------------------------
/**
* Whether the Summary tab may present the run-wide aggregated Changes section.
* The operator decision is final-state-only: a failed run has no settled final
* workspace, so its evidence stays in each visit's own recorded capture. The
* Android client shows the aggregate for failed runs too; this is a deliberate
* browser divergence, recorded in PARITY.md R4. Pure.
*/
export function showRunChangesSummary(status) {
return str(status).trim().toLowerCase() === "succeeded";
}
/**
* Aggregates a run's stage steps into its final-state Changes view. Pure and
* total over its input: a null `file_changes` on a step is a historical (or
* non-capturing) step and contributes nothing (it is never "no changes"); a
* present capture with no files is a real, observed no-change. Steps are read in
* numeric sequence order (stable for ties), and files are keyed by path and keep
* first-seen order, so a path several steps changed is one entry naming all of
* them. The last recorded step for a path supplies its kind, patch, added/removed
* counts, binary/truncated flags and modes: the summary describes the state the
* run left, never a sum of intermediate visits. Run-wide capture counters and
* caveats still describe every contributing step.
*/
export function runChanges(steps) {
const entries = new Map();
let stepsWithChanges = 0;
let stepsPending = 0;
let partial = false;
let unavailable = false;
let missingCaptures = 0;
let skipped = 0;
let omitted = 0;
let truncatedSeen = false;
const diagnostics = new Set();
const orderedSteps = (steps ?? [])
.map((step, index) => ({ step, index }))
.sort((a, b) => sequenceOf(a.step) - sequenceOf(b.step) || a.index - b.index)
.map((entry) => entry.step);
for (const step of orderedSteps) {
const changes = step?.file_changes;
if (changes == null) {
if (step?.status === "running" || step?.status === "waiting") stepsPending++;
else missingCaptures++;
continue;
}
stepsWithChanges++;
if (changes.status === "unavailable") unavailable = true;
if (changes.status === "partial") partial = true;
if (str(changes.diagnostic).trim() !== "") diagnostics.add(str(changes.diagnostic).trim());
skipped += Number(changes.skipped) || 0;
omitted += Number(changes.omitted) || 0;
const stageText = str(step?.stage);
const stage = stageText.trim() === "" ? "stage" : stageText;
for (const file of changes.files ?? []) {
const path = str(file?.path);
if (path.trim() === "") continue;
if (file?.truncated === true) truncatedSeen = true;
const kind = changeKind(file?.kind);
const parsed = parseUnifiedPatch(file?.patch);
const existing = entries.get(path);
const mergedSteps = existing ? [...existing.steps] : [];
if (!mergedSteps.includes(stage)) mergedSteps.push(stage);
// The last recorded step wins every per-file fact: the summary is the
// final state, not an accumulation of the visits on the way there.
entries.set(path, {
path,
kind,
added: parsed.added,
removed: parsed.removed,
binary: file?.binary === true,
truncated: file?.truncated === true,
beforeMode: nullable(file?.before_mode),
afterMode: nullable(file?.after_mode),
otherModeChange:
file?.before_mode != null &&
file?.after_mode != null &&
file.before_mode !== file.after_mode &&
!file.binary &&
parsed.added === 0 &&
parsed.removed === 0,
steps: mergedSteps,
patch: typeof file?.patch === "string" && file.patch.trim() !== "" ? file.patch : null,
});
}
}
const files = [...entries.values()];
const pending = stepsWithChanges === 0 && stepsPending > 0;
const totalPartial = partial || truncatedSeen || omitted > 0;
return {
files,
stepsWithChanges,
stepsPending,
added: files.reduce((sum, file) => sum + file.added, 0),
removed: files.reduce((sum, file) => sum + file.removed, 0),
partial: totalPartial,
unavailable,
pending,
missingCaptures,
skipped,
omitted,
diagnostic: [...diagnostics].join(" "),
};
}
// ---------------------------------------------------------------------------
// Entry helpers (FileChangeEntry derived properties)
// ---------------------------------------------------------------------------
/** True when a patch the operator can read is present. */
export function entryHasPatch(entry) {
return !!(entry && entry.patch != null && entry.patch.trim() !== "" && !entry.binary);
}
/** True when the recorded permissions differ and no content change explains it. */
export function entryModeChanged(entry) {
return !!(entry && entry.beforeMode != null && entry.afterMode != null && entry.beforeMode !== entry.afterMode);
}
/** The number of stages that changed this file. */
export function entryStepCount(entry) {
return (entry?.steps ?? []).length;
}
// ---------------------------------------------------------------------------
// Wording (ui/changes/RunChanges.kt + ChangeDiffViewer.kt)
// ---------------------------------------------------------------------------
/**
* The Changes section header's one-line summary: the observed file count, the
* total `+N -M`, and the honest capture caveats. Wording never implies the
* server proved authorship — it reports the workspace change it observed. A run
* with no recorded change, an unavailable capture and a still-running one each
* say exactly that rather than showing a fabricated zero.
*/
export function runChangesHeader(changes) {
if (changes.unavailable) return "Changes · capture unavailable";
if (changes.files.length === 0) {
if (changes.pending) return "Changes · capture pending";
if (changes.partial) return "Changes · partial capture";
if (changes.stepsWithChanges === 0) return "Changes · not recorded for this run";
if (changes.missingCaptures > 0) return "Changes · capture incomplete";
return "Changes · no changes observed";
}
const stat = changeStat(changes.added, changes.removed);
const count = changes.files.length;
const label =
stat === ""
? `${count} ${count === 1 ? "file" : "files"} changed`
: `${count} ${count === 1 ? "file" : "files"} changed · ${stat}`;
if (changes.partial) return `${label} · partial capture`;
if (changes.missingCaptures > 0) return `${label} · capture incomplete`;
return label;
}
/**
* The honest one-line note under the header for a capture that is not complete,
* or "" when the capture was. The wording distinguishes an unavailable capture, a
* partial one (with its counts) and a capture that has recorded nothing yet.
*/
export function runChangesNote(changes) {
if (changes.unavailable) {
return str(changes.diagnostic).trim() !== ""
? str(changes.diagnostic)
: "The workspace snapshot could not be compared; the changes below may be incomplete.";
}
let out = "";
if (changes.partial) {
out = "Partial capture: some changes may be missing.";
const caveats = [];
if (changes.skipped > 0) caveats.push(`${changes.skipped} files skipped`);
if (changes.omitted > 0) caveats.push(`${changes.omitted} omitted`);
const truncated = changes.files.filter((file) => file.truncated).length;
if (truncated > 0) caveats.push(`${truncated} truncated`);
if (caveats.length > 0) out += ` (${caveats.join(", ")})`;
if (str(changes.diagnostic).trim() !== "") out += ` ${str(changes.diagnostic)}`;
}
if (changes.missingCaptures > 0) {
if (out !== "") out += " ";
out += `Missing capture: ${changes.missingCaptures} `;
out += changes.missingCaptures === 1 ? "stage did" : "stages did";
out += " not record changes.";
}
return out.trim();
}
/** The `+N -M` stat, or "" when both counts are zero. Shared by header and row. */
export function changeStat(added, removed) {
let out = "";
if (added > 0) out += `+${added}`;
if (removed > 0) {
if (out !== "") out += " ";
out += `-${removed}`;
}
return out;
}
/**
* The tags shown beside a file row: the traits that change how the entry must be
* read (binary, truncated, a mode-only change), never a fabricated diff.
*/
export function changeEntryTags(entry) {
const tags = [];
if (entry?.binary) tags.push("binary");
if (entry?.truncated) tags.push("truncated");
if (entry?.otherModeChange && !entry.binary) tags.push("mode change");
return tags;
}
/** The row's secondary line: which stage(s) changed it, and how to read it. */
export function changeRowMeta(entry) {
let out = `changed by ${(entry?.steps ?? []).join(" → ")}`;
for (const tag of changeEntryTags(entry)) out += ` · ${tag}`;
if (entryModeChanged(entry) && !entry.binary) {
out += ` · mode ${entry.beforeMode ?? ""}→${entry.afterMode ?? ""}`;
}
return out;
}
/**
* The file list's own summary line: the observed file count and the aggregate
* stat, with the same ambiguity-free wording as the header.
*/
export function changesListSummary(changes) {
const count = `${changes.files.length} ${changes.files.length === 1 ? "file" : "files"} changed`;
const stat = changeStat(changes.added, changes.removed);
return stat === "" ? count : `${count} · ${stat}`;
}
/** Why no change is listed: a pending capture, an unavailable one, or a recorded none. */
export function noChangeDetail(changes) {
if (changes.pending) return "The capture runs after the stage finishes; nothing is recorded yet.";
if (changes.unavailable) return "The workspace snapshot could not be compared, so no changes can be shown.";
if (changes.stepsWithChanges === 0) {
return "This run recorded no change capture (a historical step, or a stage that does not capture).";
}
return "The captured snapshots were identical: the workspace was unchanged.";
}
/** Why a file has no patch to render, in the entry's own recorded terms. */
export function patchUnavailableReason(entry) {
if (entry?.truncated) {
return "The server truncated this file's patch at its capture limit; no diff text was recorded.";
}
if (entry?.otherModeChange) {
return `Only the file's mode changed (${entry.beforeMode ?? ""}→${entry.afterMode ?? ""}); the server recorded no text diff.`;
}
return "The server recorded this change without a patch.";
}
/** The `N of M` position label the viewer shows for its open file. Pure. */
export function changePositionLabel(index, count) {
return `${index + 1} of ${count}`;
}
// The viewer's honest messages, exported so the renderer and the tests share one
// spelling of each.
export const BINARY_DIFF_MESSAGE =
"This is a binary file: the server recorded the change but has no textual diff to show.";
export const TRUNCATED_PATCH_NOTE =
"The server truncated this patch at its capture limit; the raw text is the whole record.";
export const NO_LINE_CHANGES_MESSAGE = "no line changes recorded";
// ---------------------------------------------------------------------------
// Diff line language (ui/chat/ChatDiffCard.kt diffLineSymbol/diffLineColor)
// ---------------------------------------------------------------------------
/** The gutter symbol one line kind is drawn with (`+`/`-`/space). Pure. */
export function diffLineSymbol(kind) {
switch (kind) {
case ChangeLineKind.Add:
return "+";
case ChangeLineKind.Remove:
return "-";
default:
return " ";
}
}
/**
* The CSS class one line kind is drawn in: the app's success hue for an addition,
* its failure hue for a removal and the secondary on-surface role for context.
* The one place a diff line's class is decided, shared by every renderer.
*/
export function diffLineClass(kind) {
switch (kind) {
case ChangeLineKind.Add:
return "diff-add";
case ChangeLineKind.Remove:
return "diff-remove";
default:
return "diff-context";
}
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** A step's numeric sequence for ordering, with a missing/invalid value as 0. */
function sequenceOf(step) {
const value = Number(step?.sequence);
return Number.isFinite(value) ? value : 0;
}
/** An integer parsed from a strictly-numeric string, or null. */
function intOrNull(text) {
return /^[+-]?\d+$/.test(text) ? Number.parseInt(text, 10) : null;
}
/** A value kept as itself when present, else null (`?:` over nullable fields). */
function nullable(value) {
return value == null ? null : value;
}
/** A nullable value as a string ("" for null/undefined), for blank checks. */
function str(value) {
return value == null ? "" : String(value);
}
-2400
View File
File diff suppressed because it is too large Load Diff
-45
View File
@@ -1,45 +0,0 @@
/** Preserve protocol types; false and zero are valid answers, not missing input. */
export function formFieldVisible(field, answers) {
return field?.hidden !== true && (field?.when ?? []).every((condition) =>
condition.op === 'neq' ? answers[condition.key] !== condition.value : answers[condition.key] === condition.value);
}
export function formFieldValue(field, raw) {
if (raw === '') return undefined;
if (field.type === 'boolean') return raw === 'true';
if (field.type === 'number' || field.type === 'integer') return Number(raw);
return raw;
}
export function formAnswerError(fields, answers) {
for (const field of fields ?? []) {
if (!formFieldVisible(field, answers) || field.type === 'external') continue;
const value = answers[field.key];
const missing = value == null || value === '' || (Array.isArray(value) && !value.length);
const label = field.title || field.key;
if (missing) { if (field.required) return `Answer ${label} before sending.`; continue; }
if (['number', 'integer'].includes(field.type)) {
if (typeof value !== 'number' || !Number.isFinite(value) || (field.type === 'integer' && !Number.isInteger(value))) return `${label} needs a valid ${field.type}.`;
if (typeof field.minimum === 'number' && value < field.minimum) return `${label} must be at least ${field.minimum}.`;
if (typeof field.maximum === 'number' && value > field.maximum) return `${label} must be at most ${field.maximum}.`;
}
if (field.type === 'boolean' && typeof value !== 'boolean') return `${label} needs Yes or No.`;
if (typeof value === 'string') {
if (field.min_length != null && value.length < field.min_length) return `${label} is too short.`;
if (field.max_length != null && value.length > field.max_length) return `${label} is too long.`;
}
if (Array.isArray(value)) {
if (field.min_items != null && value.length < field.min_items) return `Select at least ${field.min_items} choices for ${label}.`;
if (field.max_items != null && value.length > field.max_items) return `Select at most ${field.max_items} choices for ${label}.`;
}
}
return '';
}
export function visibleFormAnswers(fields, answers) {
return Object.fromEntries((fields ?? []).filter(f => formFieldVisible(f,answers) && f.type !== 'external' && answers[f.key] !== undefined).map(f => [f.key, answers[f.key]]));
}
export function safeFormURL(raw) {
try { const url=new URL(raw); return ['http:','https:'].includes(url.protocol) ? url.href : null; } catch { return null; }
}
-20
View File
@@ -1,20 +0,0 @@
/** Harnesses with a verified catalog and model-selection path. */
export function supportsChatModels(backend) {
return ["", "opencode", "codex", "claude"].includes(String(backend ?? "").trim());
}
/** Never turn an unknown remote model into an invented model name. */
export function chatModelLabel(session) {
const model = String(session?.model ?? "").trim() || "Model";
return session?.model_selection === "next_turn" ? `${model} · next turn` : model;
}
export function chatModelSelectionNote(backend) {
if (backend === "codex") {
return "Saved by Pipelines for the next turn you send. Does not resume this thread or edit global Codex configuration.";
}
if (backend === "claude") {
return "Saved by Pipelines for the next turn you send. Does not edit your global Claude Code configuration.";
}
return "Applies to the next turn in this chat.";
}
-22
View File
@@ -1,22 +0,0 @@
// The operator's starred chats. A star is a local preference, not part of the
// server's chat record, so it survives reloads on this device and never mutates
// the session. Starred sessions sort above everything else.
export const CHAT_STARS_KEY = "pipelines.web.chatStars.v1";
export function readChatStars(storage = globalThis.localStorage) {
try {
const parsed = JSON.parse(storage?.getItem(CHAT_STARS_KEY) ?? "[]");
return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string" && id !== "") : []);
} catch {
return new Set();
}
}
export function writeChatStars(stars, storage = globalThis.localStorage) {
try {
storage?.setItem(CHAT_STARS_KEY, JSON.stringify([...stars]));
} catch {
// Storage may be unavailable; the in-memory choice still applies.
}
}
-51
View File
@@ -1,51 +0,0 @@
// Native snapshots, not tokenizers, pricing estimates, or accumulated deltas.
const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? (value === 0 ? 0 : value) : null;
const amount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? (value === 0 ? 0 : value) : null;
export function normalizeChatUsage(usage) {
if (!usage || typeof usage !== "object" || Array.isArray(usage)) return null;
const window = count(usage.context_window);
const result = {
scope: ["session", "turn"].includes(usage.scope) ? usage.scope : "",
total_tokens: count(usage.total_tokens),
context_tokens: count(usage.context_tokens),
context_window: window > 0 ? window : null,
cost_usd: amount(usage.cost_usd),
output_tokens_per_second: amount(usage.output_tokens_per_second),
rate_basis: ["generation", "turn"].includes(usage.rate_basis) ? usage.rate_basis : "",
};
// Legacy input/output counters do not prove a total that includes cache and
// reasoning; legacy zero-valued costs cannot distinguish unknown from free.
return result.scope || Object.entries(result).some(([key, value]) => key !== "scope" && key !== "rate_basis" && value !== null) ? result : null;
}
export function chatUsageMetrics(value, locale) {
const usage = normalizeChatUsage(value);
const integer = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });
const decimal = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 });
const dollars = new Intl.NumberFormat(locale, { style: "currency", currency: "USD", minimumFractionDigits: 4, maximumFractionDigits: 6 });
const metric = (key, label, number, format, title) => ({ key, label, available: number !== null && number !== undefined,
value: number === null || number === undefined ? "Unavailable" : format(number), title });
const rateTitle = usage?.rate_basis === "turn"
? "Average output tokens per second over the measured turn, including tools and waiting."
: usage?.rate_basis === "generation"
? "Non-reasoning output tokens per second over the latest native request-to-stream-completion interval, including request latency but excluding tool execution."
: "Native output-token rate when reported; never estimated from text length.";
const used = usage?.context_tokens ?? null;
const limit = usage?.context_window ?? null;
const context = used !== null && limit !== null ? `${integer.format(used)} / ${integer.format(limit)}`
: limit !== null ? `${integer.format(limit)} limit`
: used !== null ? `${integer.format(used)} used` : "Unavailable";
return [
metric("rate", usage?.rate_basis === "turn" ? "Avg output rate" : "Output rate", usage?.output_tokens_per_second,
(number) => `${number > 0 && number < 0.1 ? "<" + decimal.format(0.1) : decimal.format(number)} tok/s`, rateTitle),
metric("tokens", usage?.scope === "turn" ? "Turn tokens" : "Total tokens", usage?.total_tokens,
(number) => integer.format(number), usage?.scope === "turn" ? "Reported token total for the measured turn. Snapshots are not added together."
: "Reported token total across the conversation's model calls, not the current context size. Snapshots are not added together."),
{ key: "context", label: "Context", available: used !== null || limit !== null, value: context,
title: "Latest reported prompt/context usage / model context-window limit. Harness accounting may differ; cumulative processed tokens are not context usage." },
metric("cost", "Reported cost", usage?.cost_usd,
(number) => number > 0 && number < 0.000001 ? "<" + dollars.format(0.000001) : dollars.format(number),
"USD cost reported by the harness, not a subscription invoice. We do not estimate unreported costs or infer subscription billing."),
];
}
-280
View File
@@ -1,280 +0,0 @@
// A single, reused WebSocket connection to /connect, mirroring
// android/.../data/transport/PipelinesClient.kt: requests are serialized, each
// carries a client-generated stable id, replies are matched by id, and an
// unsolicited envelope is surfaced as a DOM-free `frame` event (the app folds the
// frames it cares about) rather than misattributed to a request. There is no
// authentication of any kind.
//
// DOM-free on purpose: the browser app and the Node smoke test share this exact
// module, so the smoke test exercises the real client, not a re-implementation.
import { Protocol } from "./protocol.js";
/** A server `type:"error"` reply, surfaced with the server's own text. */
export class ProtocolError extends Error {
constructor(message) {
super(message);
this.name = "ProtocolError";
}
}
/** No live WebSocket connection is available for the request. */
export class NotConnectedError extends Error {
constructor(message = "Not connected to the Pipelines server") {
super(message);
this.name = "NotConnectedError";
}
}
const IDLE = "idle";
const CONNECTING = "connecting";
const CONNECTED = "connected";
const DISCONNECTED = "disconnected";
const NORMAL_CLOSURE = 1000;
export class PipelinesClient extends EventTarget {
#WebSocketImpl;
#backoffBaseMs;
#backoffMaxMs;
#requestTimeoutMs;
#random;
#ws = null;
#endpoint = null;
#manualClose = false;
#attempt = 0;
#seq = 0;
#pending = new Map(); // id -> { resolve, reject, timer }
#queue = Promise.resolve();
#reconnectTimer = null;
#state = { kind: IDLE, attempt: 0, reason: "", retrying: false };
constructor({
WebSocketImpl = globalThis.WebSocket,
backoffBaseMs = 1000,
backoffMaxMs = 30000,
requestTimeoutMs = 30000,
random = Math.random,
} = {}) {
super();
if (typeof WebSocketImpl !== "function") {
throw new Error("No WebSocket implementation available");
}
this.#WebSocketImpl = WebSocketImpl;
this.#backoffBaseMs = backoffBaseMs;
this.#backoffMaxMs = backoffMaxMs;
this.#requestTimeoutMs = requestTimeoutMs;
this.#random = random;
}
get state() {
return { ...this.#state };
}
#setState(next) {
this.#state = next;
this.dispatchEvent(new CustomEvent("state", { detail: this.state }));
}
/** Opens (or re-opens) the connection to a validated server URL. */
connect(validated) {
if (!validated || !validated.valid) {
throw new Error("server URL is not valid");
}
this.#endpoint = validated.wsUrl;
this.#manualClose = false;
this.#attempt = 0;
this.#clearReconnect();
this.#open();
}
/** Explicit user disconnect: stops reconnection and closes the socket. */
disconnect() {
this.#manualClose = true;
this.#clearReconnect();
const socket = this.#ws;
this.#ws = null;
try {
socket?.close(NORMAL_CLOSURE, "client closing");
} catch {
/* already closed */
}
this.#failPending("Disconnected");
this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false });
}
/**
* Sends one request and awaits the reply with the matching id. Serialized by a
* promise chain so concurrent screens cannot interleave frames.
*/
async call(request) {
const run = this.#queue.then(() => this.#doCall(request));
// Keep the chain alive even when a call rejects.
this.#queue = run.then(
() => undefined,
() => undefined,
);
return run;
}
/**
* Sends one request without awaiting a reply, returning the generated id
* (mirrors the Android `PipelinesClient.sendOnly`). Used for the run-event
* watch: `subscribe` may never be acknowledged, so registering a pending entry
* would leave it to time out, and `unsubscribe` has nothing to read back.
*
* The send is synchronous so back-to-back frames (`unsubscribe` then
* `subscribe`) keep their order on the wire; the id is still available so a
* server that does ack (or refuses) has its reply surface as an unsolicited
* `frame` event with that id. A call before the socket is connected is refused
* with `NotConnectedError`, exactly like `call`.
*/
sendOnly(request) {
const socket = this.#ws;
if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError();
const id = `web-${++this.#seq}`;
socket.send(JSON.stringify({ ...request, id }));
return id;
}
async #doCall(request) {
const socket = this.#ws;
if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError();
const id = `web-${++this.#seq}`;
const payload = JSON.stringify({ ...request, id });
const reply = new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.#pending.delete(id);
reject(new Error(`request timed out after ${this.#requestTimeoutMs}ms`));
}, this.#requestTimeoutMs);
this.#pending.set(id, { resolve, reject, timer });
});
try {
socket.send(payload);
const response = await reply;
if (response.type === Protocol.ERROR) {
throw new ProtocolError((response.error || "").trim() || "server error");
}
return response;
} finally {
const entry = this.#pending.get(id);
if (entry) {
clearTimeout(entry.timer);
this.#pending.delete(id);
}
}
}
#open() {
const current = this.#endpoint;
if (!current) return;
this.#attempt += 1;
this.#setState({
kind: CONNECTING,
attempt: this.#attempt,
reason: "",
retrying: false,
});
const socket = new this.#WebSocketImpl(current);
const superseded = this.#ws;
this.#ws = socket;
// Replace the current socket, then close the one it superseded (mirrors
// PipelinesClient.openLocked). Its callbacks are ignored from then on, so a
// failure the old socket reports late can neither clear the new socket nor
// schedule a reconnect that would undo it. A request already sent on the old
// socket cannot receive a reply from the replacement, so fail it now rather
// than leaving a view waiting for the ordinary request timeout.
if (superseded) {
this.#failPending("Connection replaced");
try {
superseded.close(NORMAL_CLOSURE, "superseded");
} catch {
/* already closed */
}
}
socket.onopen = () => {
if (this.#ws !== socket) return;
this.#attempt = 0;
this.#setState({ kind: CONNECTED, attempt: 0, reason: "", retrying: false });
};
socket.onmessage = (event) => {
if (this.#ws !== socket) return;
this.#onMessage(event.data);
};
socket.onclose = (event) => {
if (this.#ws !== socket) return;
this.#handleClosed(`Connection closed (${event.code ?? "?"})`);
};
socket.onerror = () => {
// Browsers withhold detail here; onclose carries the outcome.
};
}
#onMessage(data) {
if (typeof data !== "string") return; // the server is text-only
let message;
try {
message = JSON.parse(data);
} catch {
return; // malformed frame: never misattribute it to a request
}
const entry = message.id ? this.#pending.get(message.id) : null;
if (entry) {
this.#pending.delete(message.id);
clearTimeout(entry.timer);
entry.resolve(message);
return;
}
// No pending request matches: the envelope is unsolicited — the connection's
// initial `pipeline_list`, or a server push such as a `chat_event` frame or a
// `run_event` — and is surfaced as a DOM-free `frame` event for a view to fold;
// with no listener it is simply dropped. It is never misattributed to a
// request, which is still matched by id.
this.dispatchEvent(new CustomEvent("frame", { detail: message }));
}
#failPending(reason) {
for (const [id, entry] of this.#pending) {
this.#pending.delete(id);
clearTimeout(entry.timer);
entry.reject(new Error(reason));
}
}
#handleClosed(reason) {
this.#ws = null;
this.#failPending(reason);
if (this.#manualClose) {
this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false });
return;
}
this.#scheduleReconnect(reason);
}
#scheduleReconnect(reason) {
if (this.#reconnectTimer) return;
this.#setState({
kind: DISCONNECTED,
attempt: this.#attempt,
reason,
retrying: true,
});
const shift = Math.min(Math.max(this.#attempt - 1, 0), 6);
const backoff = Math.min(this.#backoffBaseMs << shift, this.#backoffMaxMs);
const jitter = Math.floor(this.#random() * 400);
this.#reconnectTimer = setTimeout(() => {
this.#reconnectTimer = null;
if (!this.#manualClose && this.#endpoint) this.#open();
}, backoff + jitter);
}
#clearReconnect() {
if (this.#reconnectTimer) {
clearTimeout(this.#reconnectTimer);
this.#reconnectTimer = null;
}
}
}
-196
View File
@@ -1,196 +0,0 @@
// Pure connection helpers for the browser client: how the persistent connection
// banner reads, what the page does the moment it becomes visible again, whether
// the ping reply's protocol/build can be trusted, and what the live badge says.
//
// Deliberately free of DOM, sockets and timers, so every branch is unit-testable
// in Node and renders identically in the page. The wording and colour roles are
// the Android client's own:
// ui/components/ConnectionBanner.kt — banner copy and container colours
// data/transport/ConnectionRecovery.kt — the foregroundAction policy
// data/ForegroundReconnector.kt — order and liveness check
// ui/components/LiveBadge.kt, ui/RunStream.kt — the live badge words
// ui/screens/SettingsScreen.kt — the built "Connected" line
/** The reconnect affordance, exactly as ConnectionBanner.kt names it. */
export const RECONNECT_LABEL = "Reconnect";
/**
* The one definition of the connecting line: `Connecting (attempt N)…`, shared by
* the persistent banner and the Settings status card so the same app sentence can
* never drift between the two.
*/
export function connectingLabel(attempt) {
return `Connecting (attempt ${attempt ?? 0})\u2026`;
}
/** Idle banner copy, verbatim from ConnectionBanner.kt. */
export const IDLE_BANNER_TEXT =
"Not connected. Enter the server URL in Settings, then connect.";
/** ConnectionBanner.kt's suffix while the client has a retry scheduled. */
export const RETRYING_SUFFIX = " \u00b7 retrying with backoff";
/** What the app does with the connection the moment it becomes visible again. */
export const ForegroundAction = Object.freeze({
/** Leave the connection exactly as it is. */
LeaveAlone: "LeaveAlone",
/** Reconnect now, cancelling any pending reconnect delay. */
Reconnect: "Reconnect",
});
/**
* Derive the persistent banner from the client's connection state.
*
* `tone` names the Material container role the stylesheet paints
* (surfaceVariant for idle/connecting, errorContainer for disconnected,
* primary/ok for connected); `text` is the app's own copy; `action` is the
* reconnect affordance, offered only while idle or disconnected and only when an
* endpoint is configured (ConnectionBanner.kt's `actionEnabled`). ConnectionBanner.kt
* renders nothing once connected, so the page's explicit green "Connected" (the
* primary-coloured state SettingsScreen.kt shows) is the one visible difference.
*
* The disconnected copy is verbatim ConnectionBanner.kt: `Disconnected:
* {message}` plus ` · retrying with backoff` while a retry is scheduled. That
* banner text deliberately omits the attempt number (Android only names it while
* Connecting), so the page surfaces the retry attempt in its header state badge
* instead — see `stateBadge` — rather than diverging from the banner wording.
*/
export function bannerState(connection, { hasEndpoint = false } = {}) {
const c = connection ?? {};
switch (c.kind) {
case "connected":
return { tone: "ok", text: "Connected", action: null };
case "connecting":
return {
tone: "connecting",
text: connectingLabel(c.attempt),
action: null,
};
case "disconnected": {
const reason = String(c.reason ?? "").trim() || "connection closed";
const retry = c.retrying ? RETRYING_SUFFIX : "";
return {
tone: "error",
text: `Disconnected: ${reason}${retry}`,
action: hasEndpoint ? RECONNECT_LABEL : null,
};
}
default:
return {
tone: "idle",
text: IDLE_BANNER_TEXT,
action: hasEndpoint ? RECONNECT_LABEL : null,
};
}
}
/**
* The app's return-to-foreground policy in one place (ConnectionRecovery.kt).
*
* A deliberate Disconnect is the only way the client reaches Idle, so Idle is
* left alone; every other state reconnects. A still-Connected socket is not
* trusted on return — a frozen process or a suspended tab can leave it claiming
* Connected while it answers nothing — so the caller probes it and passes the
* verdict as `confirmedAlive`, which is consulted only for Connected.
*/
export function foregroundAction(state, confirmedAlive) {
switch (state?.kind) {
case "idle":
return ForegroundAction.LeaveAlone;
case "connected":
return confirmedAlive ? ForegroundAction.LeaveAlone : ForegroundAction.Reconnect;
default:
// Connecting and Disconnected both carry their own answer; an unknown state
// is never trusted, so it reconnects like the app's non-Connected states.
return ForegroundAction.Reconnect;
}
}
/**
* Compare the page's protocol with the server's `pong.protocol`. Returns null
* unless both values are present and differ, because a server that omits the
* field (older build) must not be flagged; otherwise a warning naming both.
*/
export function protocolMismatch(clientProtocol, serverProtocol) {
if (!isProtocol(clientProtocol) || !isProtocol(serverProtocol)) return null;
if (Number(clientProtocol) === Number(serverProtocol)) return null;
return `Protocol mismatch: this page speaks protocol ${clientProtocol}, the server reports ${serverProtocol}.`;
}
function isProtocol(value) {
return value !== null && value !== undefined && value !== "" && !Number.isNaN(Number(value));
}
/**
* The compact connection state helper behind the shell's dot+word control and
* the Settings status card. It is the page's own indicator (Android renders the
* same facts in SettingsScreen.kt's connection card): the one job it does that
* ConnectionBanner.kt's banner text does not is name the retry attempt while
* disconnected, so "reason + retrying + attempt" are all visible at a glance.
* `tone` names the dot colour class (ok/warn/bad/idle).
*/
export function stateBadge(connection) {
const c = connection ?? {};
switch (c.kind) {
case "connected":
return { tone: "ok", text: "connected" };
case "connecting":
return { tone: "warn", text: `connecting\u2026 (attempt ${c.attempt ?? 0})` };
case "disconnected": {
const reason = String(c.reason ?? "").trim();
const retry = c.retrying ? (c.attempt ? `attempt ${c.attempt}, retrying` : "retrying") : c.attempt ? `attempt ${c.attempt}` : "";
return { tone: "bad", text: `disconnected${reason ? ` \u2014 ${reason}` : ""}${retry ? ` (${retry})` : ""}` };
}
default:
return { tone: "idle", text: "idle" };
}
}
/**
* Render the server's `pong.build` (version/commit/dirty) for the banner, so a
* stale server is visible at a glance. The shape is SettingsScreen.kt's exactly:
* `Server build {version} ({commit})`. Missing fields are tolerated: nothing is
* shown when there is nothing to say.
*
* No separate dirty marker: internal/buildinfo already folds a dirty tree into
* `version` as a `-dirty` suffix (buildinfo.go), so `Server build v1-dirty (abc)`
* is the honest, non-duplicated form (Android renders no dirty marker either).
*/
export function serverBuildLabel(build) {
const info = build && typeof build === "object" ? build : {};
const version = String(info.version ?? "").trim();
const commit = String(info.commit ?? "").trim();
const parts = [];
if (version) parts.push(version);
if (commit) parts.push(`(${commit})`);
if (!parts.length) return "";
return `Server build ${parts.join(" ")}`;
}
/**
* The live-stream states, exactly RunStream.kt's three words. The page tracks
* this itself (it owns the subscription), so the badge says whether the pushes
* are arriving rather than guessing from whether a run happens to be executing.
*/
export const RunStream = Object.freeze({
Live: "live",
Connecting: "connecting",
Offline: "offline",
});
/**
* The live-stream badge, mirroring LiveBadge.kt / RunStream.kt: the explicit
* stream state maps to the app's own word and dot ("live" / "reconnecting" /
* "not live"). The word always carries the meaning, so colour is never the only
* signal, and the badge is independent of whether any run is executing.
*/
export function liveBadgeState(streamState) {
switch (streamState) {
case RunStream.Live:
return { tone: "live", label: "live" };
case RunStream.Connecting:
return { tone: "reconnecting", label: "reconnecting" };
default:
return { tone: "not-live", label: "not live" };
}
}
-121
View File
@@ -1,121 +0,0 @@
// Shared DOM construction and small browser helpers. The page builds every
// node with these functions; server-derived text is always assigned through
// textContent, never innerHTML.
import { artifactBrowserLinkProps } from "./artifactNavigation.js";
import { canShareFiles, shareArtifactFile } from "./artifactSharing.js";
export { artifactBrowserLinkProps } from "./artifactNavigation.js";
export function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value == null || value === false) continue;
if (key === "class") node.className = value;
else if (key === "text") node.textContent = value;
else if (key.startsWith("on") && typeof value === "function") {
node.addEventListener(key.slice(2).toLowerCase(), value);
} else node.setAttribute(key, value === true ? "" : String(value));
}
for (const child of children.flat()) {
if (child == null || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
/** Run synchronously inside a click/keyboard gesture: Android rejects intents
* launched from timers. Never fall back to replacing the app's own location. */
export function openArtifactInBrowser(resolved) {
const props = artifactBrowserLinkProps(resolved);
if (!props) return false;
const link = h("a", { ...props, hidden: true });
document.body.append(link);
link.click();
link.remove();
return true; // A hand-off was requested; the OS decides which browser handles it.
}
/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */
export function renderLiveBadge(info) {
return h(
"span",
{ class: `live-badge live-${info.tone}`, title: info.title ?? "Live run stream" },
h("span", { class: "live-dot", "aria-hidden": "true" }),
h("span", { class: "live-word", text: info.label }),
);
}
/** Whether the Clipboard API can be used for a copy control. */
export function canCopyLink() {
return typeof navigator !== "undefined" && Boolean(navigator.clipboard?.writeText);
}
/** Whether the browser exposes file sharing (not just URL sharing). */
export function canShare() {
return canShareFiles();
}
export async function copyText(text) {
if (!text || !canCopyLink()) return;
try {
await navigator.clipboard.writeText(text);
} catch {
// Clipboard permission may be denied; the patch is still readable.
}
}
export async function copyArtifactLink(resolved) {
if (!resolved || !canCopyLink()) return;
try {
await navigator.clipboard.writeText(resolved);
} catch {
// Clipboard permission may be denied; the link is still openable.
}
}
export async function shareArtifact(resolved, artifact, trigger) {
if (!trigger || trigger.getAttribute("aria-busy") === "true") return;
const host = trigger.closest(".artifact-tile-wrap, .artifact-list-row, .viewer-panel");
let status = host?.querySelector(".artifact-share-status");
if (!status && host) {
status = h("div", { class: "artifact-share-status muted", role: "status", "aria-live": "polite" });
host.append(status);
}
if (status) status.textContent = "Preparing file…";
trigger.setAttribute("aria-busy", "true");
try {
const result = await shareArtifactFile(resolved, artifact, trigger);
if (status && trigger.isConnected) status.textContent = result.message;
} finally {
trigger.removeAttribute("aria-busy");
}
}
/** A key/value row whose value is monospace (a key, an id) rather than prose. */
export function kvMono(key, value) {
return h(
"div",
{ class: "kv-row" },
h("span", { class: "kv-key", text: key }),
h("span", { class: "kv-val" }, h("code", { text: value })),
);
}
/** A 24px chevron-left for the one Back control every detail screen uses. */
export function backChevronIcon(className = "back-chevron") {
const NS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("class", className);
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", "M15 5 8 12l7 7");
path.setAttribute("fill", "none");
path.setAttribute("stroke", "currentColor");
path.setAttribute("stroke-width", "2");
path.setAttribute("stroke-linecap", "round");
path.setAttribute("stroke-linejoin", "round");
svg.append(path);
return svg;
}
-19
View File
@@ -1,19 +0,0 @@
// Shared display formatting and small status helpers used by the view modules.
// The date, duration and size formatters themselves live in their pure modules
// (runs.js, artifacts.js); this module owns the DOM-facing status mapping.
import { ChangeKind } from "./changes.js";
export function isExecuting(run) {
return Boolean(run && run.executing);
}
export function changeKindTone(kind) {
if (kind === ChangeKind.Added) return "ok";
if (kind === ChangeKind.Deleted) return "bad";
return "muted";
}
export function describeError(error) {
return error?.message || String(error);
}
-1578
View File
File diff suppressed because it is too large Load Diff
-22
View File
@@ -1,22 +0,0 @@
// The workflow graph's expansion preference. The graph is expanded by default;
// collapsing it is a deliberate choice and is remembered across reloads, so the
// operator's next visit opens the graph the way they left it.
export const GRAPH_EXPANDED_KEY = "pipelines.web.graphExpanded.v1";
/** True unless the operator collapsed the graph (a missing value means default). */
export function readGraphExpanded(storage = globalThis.localStorage) {
try {
return storage?.getItem(GRAPH_EXPANDED_KEY) !== "0";
} catch {
return true;
}
}
export function writeGraphExpanded(value, storage = globalThis.localStorage) {
try {
storage?.setItem(GRAPH_EXPANDED_KEY, value ? "1" : "0");
} catch {
// Storage may be unavailable; the in-memory choice still applies.
}
}
-75
View File
@@ -1,75 +0,0 @@
// A small, dependency-free syntax colourer for fenced code in chat. It returns
// tokens, never HTML: the renderer appends spans with text nodes, so no model
// output can inject markup. Unknown languages still get strings, comments and
// numbers highlighted with the generic keyword set.
const KEYWORDS = {
go: "break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var true false nil iota",
javascript:
"async await break case catch class const continue debugger default delete do else export extends finally for from function get if import in instanceof let new of return set static super switch this throw try typeof var void while with yield true false null undefined",
typescript:
"abstract any as asserts async await boolean break case catch class const constructor continue declare default delete do else enum export extends false finally for from function get if implements import in infer instanceof interface is keyof let module namespace never new null number object of package private protected public readonly require return set static string super switch symbol this throw true try type typeof undefined unique unknown var void while with yield",
kotlin:
"as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while by catch constructor delegate dynamic field file finally get import init param property receiver set setparam where actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg",
java: "abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null",
shell:
"if then else elif fi for while until do done case esac function in select time coproc break continue return exit export readonly local declare typeset unset shift source alias echo cd pwd set true false",
bash:
"if then else elif fi for while until do done case esac function in select time coproc break continue return exit export readonly local declare typeset unset shift source alias echo cd pwd set true false",
python:
"and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield match case",
rust:
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while",
sql: "select from where insert into values update set delete create table alter drop index join left right inner outer group by order having limit offset as and or not null true false distinct union all",
json: "true false null",
};
const HASH_COMMENT = new Set(["shell", "bash", "python", "ruby", "yaml", "toml"]);
function languageKey(language) {
const key = String(language ?? "").trim().toLowerCase().split(/[\s:]/)[0];
if (key === "js" || key === "jsx") return "javascript";
if (key === "ts" || key === "tsx") return "typescript";
if (key === "sh" || key === "zsh") return "shell";
if (key === "py") return "python";
if (key === "kt") return "kotlin";
if (key === "rs") return "rust";
return key;
}
/**
* Tokenize one code block into `{text, kind}` with kind plain|comment|string|
* number|keyword|literal. Total and deterministic.
*/
export function highlight(code, language = "") {
const key = languageKey(language);
const keywords = new Set((KEYWORDS[key] ?? KEYWORDS.javascript).split(/\s+/).filter(Boolean));
const commentPattern = HASH_COMMENT.has(key) ? "#[^\\n]*" : key === "sql" ? "--[^\\n]*" : "\\/\\/[^\\n]*";
const pattern = new RegExp(
`(\\/\\*[\\s\\S]*?\\*\\/|${commentPattern}|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\b\\d+(?:\\.\\d+)?\\b|[A-Za-z_$][\\w$]*)`,
"g",
);
const text = String(code ?? "");
const tokens = [];
let last = 0;
for (const match of text.matchAll(pattern)) {
if (match.index > last) tokens.push({ text: text.slice(last, match.index), kind: "plain" });
const value = match[0];
let kind = "plain";
if (value.startsWith("//") || value.startsWith("#") || value.startsWith("--") || value.startsWith("/*")) {
kind = "comment";
} else if (/^["'`]/.test(value)) {
kind = "string";
} else if (/^\d/.test(value)) {
kind = "number";
} else if (keywords.has(value)) {
kind = value === "true" || value === "false" || value === "null" || value === "None" ||
value === "nil" || value === "True" || value === "False"
? "literal"
: "keyword";
}
tokens.push({ text: value, kind });
last = match.index + value.length;
}
if (last < text.length) tokens.push({ text: text.slice(last), kind: "plain" });
return tokens;
}
-30
View File
@@ -1,30 +0,0 @@
// The shell's two layout preferences: a collapsed destination rail and a
// collapsed list pane. Per-device, so they survive reloads.
export const LAYOUT_KEY = "pipelines.web.layout.v1";
export function readLayoutPrefs(storage = globalThis.localStorage) {
try {
const parsed = JSON.parse(storage?.getItem(LAYOUT_KEY) ?? "{}");
return {
railCollapsed: parsed?.railCollapsed === true,
listCollapsed: parsed?.listCollapsed === true,
};
} catch {
return { railCollapsed: false, listCollapsed: false };
}
}
export function writeLayoutPrefs(prefs, storage = globalThis.localStorage) {
try {
storage?.setItem(
LAYOUT_KEY,
JSON.stringify({
railCollapsed: prefs?.railCollapsed === true,
listCollapsed: prefs?.listCollapsed === true,
}),
);
} catch {
// Storage may be unavailable; the in-memory choice still applies.
}
}
-341
View File
@@ -1,341 +0,0 @@
// Pure, DOM-free CommonMark subset for assistant prose (C7), ported from the
// Android client's ui/chat/Markdown.kt so the browser renders exactly the same
// blocks and inline spans. The brokered protocol carries assistant text as
// markdown, and the reference experience renders it:
// paragraphs, `#`..`######` headings, fenced code (``` / ~~~, language label
// else `code`), block quotes, bullet and ordered lists, `|` tables with a
// `---` delimiter row, thematic rules, and inline code / bold / italic /
// links / bare http(s) autolinks.
//
// Anything outside the subset renders as plain text and is never dropped. There
// is deliberately no HTML, no reference links, no nested lists and no
// strikethrough — the same subset the app implements.
//
// The parser is pure (no DOM, no transport) so it is unit-testable; the caller
// turns the same blocks into text nodes with textContent, never innerHTML.
/**
* Decodes the HTML entities an assistant message can carry. The server's own
* session export escapes text with Go's `html.EscapeString`, so a message that
* quotes an export arrives with `&#x27;`, `&quot;`, `&amp;` and friends still in
* it. The common named entities plus numeric decimal and hex references are
* decoded; an unknown or malformed reference is left exactly as written so no
* visible text is invented. A single left-to-right pass never re-decodes an
* entity produced by decoding another (`&amp;lt;` stays `&lt;`).
*/
const NAMED_ENTITIES = {
amp: "&",
lt: "<",
gt: ">",
quot: '"',
apos: "'",
nbsp: "\u00A0",
hellip: "\u2026",
mdash: "\u2014",
ndash: "\u2013",
lsquo: "\u2018",
rsquo: "\u2019",
ldquo: "\u201C",
rdquo: "\u201D",
};
const HTML_ENTITY = /&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/g;
export function decodeHtmlEntities(text) {
if (!text.includes("&")) return text;
return text.replace(HTML_ENTITY, (match, body) => {
if (Object.prototype.hasOwnProperty.call(NAMED_ENTITIES, body)) return NAMED_ENTITIES[body];
return numericReference(body) ?? match;
});
}
/** The character one numeric entity's body (`#27`/`#x1b`) names, or null. */
function numericReference(body) {
let codePoint = null;
if (body.startsWith("#x") || body.startsWith("#X")) {
if (/^#x[0-9A-Fa-f]+$/.test(body)) codePoint = parseInt(body.slice(2), 16);
} else if (body.startsWith("#")) {
if (/^#[0-9]+$/.test(body)) codePoint = parseInt(body.slice(1), 10);
}
if (codePoint == null || !Number.isFinite(codePoint)) return null;
if (codePoint < 1 || codePoint > 0x10ffff) return null;
return String.fromCodePoint(codePoint);
}
// ---- Blocks -----------------------------------------------------------------
/**
* Parses [source] into the block list the renderer walks. Never throws. Blocks:
* {kind:"heading", level, text} {kind:"paragraph", text}
* {kind:"code", language, code} {kind:"quote", lines}
* {kind:"list", ordered, items} {kind:"table", header, rows}
* {kind:"rule"}
*/
export function parseMarkdown(source) {
const lines = decodeHtmlEntities(String(source ?? ""))
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
.split("\n");
const blocks = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
const trimmed = line.trim();
if (trimmed === "") {
i += 1;
continue;
}
const fence = fenceRun(trimmed);
if (fence != null) {
const language = trimmed.slice(fence.length).trim().split(" ")[0];
const code = [];
i += 1;
while (i < lines.length && fenceRun(lines[i].trim()) == null) {
code.push(lines[i]);
i += 1;
}
if (i < lines.length) i += 1; // consume the closing fence
blocks.push({ kind: "code", language, code: code.join("\n") });
continue;
}
const level = headingLevel(trimmed);
if (level > 0) {
blocks.push({ kind: "heading", level, text: trimEndHashes(trimmed.slice(level).trim()) });
i += 1;
continue;
}
if (isRule(trimmed)) {
blocks.push({ kind: "rule" });
i += 1;
continue;
}
if (trimmed.startsWith(">")) {
const quote = [];
while (i < lines.length && lines[i].trim().startsWith(">")) {
quote.push(lines[i].trim().replace(/^>/, "").replace(/^ /, "").replace(/\s+$/, ""));
i += 1;
}
blocks.push({ kind: "quote", lines: quote });
continue;
}
if (isTableStart(lines, i)) {
const header = splitRow(lines[i]);
i += 2; // header + delimiter row
const rows = [];
while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
rows.push(fitRow(splitRow(lines[i]), header.length));
i += 1;
}
blocks.push({ kind: "table", header, rows });
continue;
}
const marker = listMarker(line);
if (marker != null) {
const ordered = marker.ordered;
const items = [];
while (i < lines.length && listMarker(lines[i])?.ordered === ordered) {
items.push(listMarker(lines[i]).text);
i += 1;
}
blocks.push({ kind: "list", ordered, items });
continue;
}
const paragraph = [line.trim()];
i += 1;
while (i < lines.length && lines[i].trim() !== "" && !startsBlock(lines, i)) {
paragraph.push(lines[i].trim());
i += 1;
}
blocks.push({ kind: "paragraph", text: paragraph.join(" ") });
}
return blocks;
}
/** The fence run (` ``` ` / `~~~`) a line opens or closes with, or null. */
function fenceRun(trimmed) {
const first = trimmed[0];
if (first !== "`" && first !== "~") return null;
let run = "";
for (const char of trimmed) {
if (char !== first) break;
run += char;
}
return run.length >= 3 ? run : null;
}
function headingLevel(trimmed) {
let hashes = 0;
while (hashes < trimmed.length && trimmed[hashes] === "#") hashes += 1;
if (hashes === 0 || hashes > 6) return 0;
return trimmed.length === hashes || trimmed[hashes] === " " ? hashes : 0;
}
function trimEndHashes(text) {
return text.replace(/#+$/, "");
}
function isRule(trimmed) {
if (trimmed.length < 3) return false;
const first = trimmed[0];
if (!"-*_".includes(first)) return false;
for (const char of trimmed) if (char !== first) return false;
return true;
}
/** True when [lines] at [index] is a table header followed by a `---` delimiter row. */
function isTableStart(lines, index) {
if (index + 1 >= lines.length || !lines[index].includes("|")) return false;
const delimiter = splitRow(lines[index + 1]);
if (delimiter.length === 0 || splitRow(lines[index]).length < 2) return false;
return delimiter.every(
(cell) => cell.length > 0 && [...cell].every((char) => char === "-" || char === ":") && cell.includes("-"),
);
}
/** Splits a table row on unescaped `|`, dropping the leading/trailing empty cell. */
function splitRow(line) {
return line
.trim()
.replace(/^\|/, "")
.replace(/\|$/, "")
.split("|")
.map((cell) => cell.replace(/\\\|/g, "|").trim());
}
function fitRow(row, size) {
return Array.from({ length: size }, (_, index) => row[index] ?? "");
}
const ORDERED_ITEM = /^(\d{1,9})[.)]\s+(.*)$/;
const BULLET_ITEM = /^([-*+])\s+(.*)$/;
/** The ordered flag and item text of a list line, or null for a non-item line. */
function listMarker(line) {
const trimmed = line.replace(/^\s+/, "");
const orderedMatch = ORDERED_ITEM.exec(trimmed);
if (orderedMatch) return { ordered: true, text: orderedMatch[2] };
const bulletMatch = BULLET_ITEM.exec(trimmed);
if (bulletMatch) return { ordered: false, text: bulletMatch[2] };
return null;
}
/** True when [lines] at [index] begins a block that must interrupt a paragraph. */
function startsBlock(lines, index) {
const trimmed = lines[index].trim();
return (
fenceRun(trimmed) != null ||
headingLevel(trimmed) > 0 ||
isRule(trimmed) ||
trimmed.startsWith(">") ||
listMarker(lines[index]) != null ||
isTableStart(lines, index)
);
}
// ---- Inline -----------------------------------------------------------------
const WORD_CHAR = /[\p{L}\p{N}]/u;
/**
* Parses inline markup in [text] into a flat span tree. Handles `` `code` ``,
* `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
* `http(s)://` autolinks; everything else stays plain text. Underscore emphasis
* requires word boundaries so `snake_case` is never italicised.
*/
export function parseInline(text) {
const source = String(text ?? "");
const spans = [];
let buffer = "";
let i = 0;
const flush = () => {
if (buffer.length > 0) {
spans.push({ kind: "plain", text: buffer });
buffer = "";
}
};
while (i < source.length) {
const c = source[i];
if (c === "`") {
const end = source.indexOf("`", i + 1);
if (end > i) {
flush();
spans.push({ kind: "code", text: source.slice(i + 1, end) });
i = end + 1;
} else {
buffer += c;
i += 1;
}
} else if (c === "*" || c === "_") {
const doubled = i + 1 < source.length && source[i + 1] === c;
const marker = doubled ? c + c : c;
const boundOk = c !== "_" || i === 0 || !WORD_CHAR.test(source[i - 1]);
const end = boundOk ? source.indexOf(marker, i + marker.length) : -1;
const closes =
end > i + marker.length &&
(c !== "_" || end + 1 >= source.length || !WORD_CHAR.test(source[end + 1]));
if (closes) {
flush();
const inner = parseInline(source.slice(i + marker.length, end));
spans.push(doubled ? { kind: "strong", spans: inner } : { kind: "emphasis", spans: inner });
i = end + marker.length;
} else {
buffer += c;
i += 1;
}
} else if (c === "[") {
const close = source.indexOf("]", i + 1);
if (close > i && close + 1 < source.length && source[close + 1] === "(") {
const urlEnd = source.indexOf(")", close + 2);
const url = urlEnd > close ? source.slice(close + 2, urlEnd).trim() : "";
if (url !== "") {
flush();
spans.push({ kind: "link", spans: parseInline(source.slice(i + 1, close)), url });
i = urlEnd + 1;
} else {
buffer += c;
i += 1;
}
} else {
buffer += c;
i += 1;
}
} else {
const url = autolinkAt(source, i);
if (url != null) {
flush();
spans.push({ kind: "link", spans: [{ kind: "plain", text: url }], url });
i += url.length;
} else {
buffer += c;
i += 1;
}
}
}
flush();
return spans;
}
/** A bare `http(s)://` URL starting exactly at [index], trailing punctuation trimmed. */
function autolinkAt(text, index) {
if (!text.startsWith("http://", index) && !text.startsWith("https://", index)) return null;
let end = index;
while (end < text.length && !/\s/.test(text[end]) && !"<>\"'".includes(text[end])) end += 1;
let url = text.slice(index, end);
while (url.length > 0 && ".,;:!?)]}".includes(url[url.length - 1])) url = url.slice(0, -1);
return url.length > "https://".length ? url : null;
}
/** The label a fenced code block shows: its language, or `code` when unnamed. */
export function codeBlockLabel(language) {
const value = String(language ?? "").trim();
return value === "" ? "code" : value;
}
-103
View File
@@ -1,103 +0,0 @@
// Label-free list cue, sharing the detail graph's layout and route evidence.
import { h } from "./dom.js";
import { layoutGraph, edgeIsExecuted, edgeStrokeColor } from "./graph.js";
import { runGraphState } from "./runDetail.js";
const METRICS = Object.freeze({ nodeWidth: 26, nodeHeight: 12, hGap: 12, pad: 2,
laneSpacing: 8, terminalGap: 8, trackStep: 6, portSpacing: 4,
labelCharWidth: 0, labelPadding: 0, labelHeight: 0, labelGap: 0 });
const NS = "http://www.w3.org/2000/svg";
const STATUSES = new Set(["succeeded", "failed", "running", "waiting", "queued",
"interrupted", "canceled", "blocked", "skipped"]);
export function miniatureColor(status) {
if (status === "waiting") return "var(--warn)";
if (status === "running") return "var(--accent)";
return `var(--status-${STATUSES.has(status) ? status : "unknown"})`;
}
export function miniatureModel(graph, run = null) {
const stages = graph?.stages ?? [];
const keys = new Set(stages.map((stage) => stage.key));
const shape = { stages: stages.map((stage) => ({ ...stage,
edges: Object.fromEntries(Object.entries(stage.edges ?? {}).filter(([, target]) => keys.has(target))),
})) };
const layout = layoutGraph(shape, METRICS);
const steps = Array.isArray(run?.steps) ? run.steps : run?.graph_evidence?.visits;
const evidence = Array.isArray(steps) ? runGraphState({ ...run, steps }) : null;
const visits = new Map((steps ?? []).map((step) => [step.stage, step]));
return { ...layout, evidence: evidence != null,
complete: Array.isArray(run?.steps) || run?.graph_evidence?.complete === true,
nodes: layout.nodes.map((node) => {
const step = visits.get(node.key);
// A recorded current stage is evidence even in a compact list summary.
const current = run?.executing && run.current_stage === node.key;
const status = step?.status ?? (current ? run.status : null);
// Custom outcome names do not override a recorded terminal verdict.
const color = step?.target === "#failure" ? "var(--bad)"
: step?.target === "#success" ? "var(--ok)"
: status === "completed" ? edgeStrokeColor(step.outcome) : status ? miniatureColor(status) : null;
return { ...node, color,
untaken: Boolean(run) && !step && !current };
}),
edges: layout.edges.map((edge) => ({ ...edge,
untaken: Boolean(run) && (!evidence || !edgeIsExecuted(edge, evidence)),
color: evidence && edgeIsExecuted(edge, evidence) ? edgeStrokeColor(edge.outcome) : null,
})),
};
}
export function renderMiniGraph(graph, run = null) {
if (!graph?.stages?.length) return null;
const model = miniatureModel(graph, run);
if (!model.nodes.length || !model.width || !model.height) return null;
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("class", "pipeline-mini-graph");
svg.setAttribute("viewBox", `0 0 ${Math.ceil(model.width)} ${Math.ceil(model.height)}`);
svg.setAttribute("preserveAspectRatio", "xMaxYMid meet");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
for (const edge of model.edges) {
if (edge.points.length < 2) continue;
const line = document.createElementNS(NS, "polyline");
line.setAttribute("class", `pipeline-mini-edge${edge.untaken ? " mini-untaken" : ""}`);
line.setAttribute("data-route", `${edge.source}:${edge.outcome}:${edge.target}`);
line.setAttribute("points", edge.points.map((p) => `${p.x},${p.y}`).join(" "));
if (edge.color) line.style.color = edge.color;
svg.append(line);
}
for (const node of model.nodes) {
const rect = document.createElementNS(NS, "rect");
rect.setAttribute("class", `pipeline-mini-node${node.untaken ? " mini-untaken" : ""}`);
rect.setAttribute("data-stage", node.key);
for (const key of ["x", "y", "width", "height"]) rect.setAttribute(key, String(node[key]));
rect.setAttribute("rx", "3");
if (node.color) rect.style.color = node.color;
svg.append(rect);
}
const wrap = h("span", { class: `pipeline-mini${run ? " run-mini" : ""}`,
"aria-hidden": "true", "data-evidence": model.evidence ? model.complete ? "visits" : "partial" : "unknown" }, svg);
// Unknown/unvisited graph elements must never inherit the aggregate result.
if (run) wrap.style.color = "var(--color-muted)";
return wrap;
}
/** One read per pinned pipeline version, never get_run per row or latest fallback. */
export function createMiniGraphCache(readPipeline, changed) {
const cache = new Map();
return (run, pipelines = [], scope = "") => {
if (run.graph?.stages?.length) return run.graph;
if (!(run.pipeline_id > 0 && run.version > 0)) return null;
const summary = pipelines.find((p) => p.id === run.pipeline_id && p.version === run.version);
if (summary?.shape?.stages?.length) return summary.shape;
const key = JSON.stringify([scope, run.pipeline_id, run.version]);
if (!cache.has(key)) {
cache.set(key, null);
Promise.resolve().then(() => readPipeline(run.pipeline_id, run.version)).then((detail) => {
if (detail?.version !== run.version) return;
cache.set(key, detail.graph ?? null);
changed();
}).catch(() => { /* Missing topology stays absent, never invented. */ });
}
return cache.get(key);
};
}
-60
View File
@@ -1,60 +0,0 @@
// CSS viewport units account for browser toolbars, not reliably for the soft
// keyboard. Use the visual viewport only for a substantial keyboard-sized
// reduction; do not fight pinch zoom, small toolbar changes or user scrolling.
export function mobileViewportState({ width, height, layoutHeight, baselineHeight, scale = 1, offsetTop = 0, editing = false, wasOpen = false }) {
const visible = Number(height);
const baseline = Math.max(Number(layoutHeight) || 0, Number(baselineHeight) || 0);
const keyboard = (editing || wasOpen) && width < 600 && Math.abs(scale - 1) < 0.01 &&
visible > 0 && baseline - visible >= Math.max(100, baseline * 0.2);
return { keyboard, height: keyboard ? Math.round(visible) : null, top: keyboard ? Math.max(0, Math.round(offsetTop)) : 0 };
}
/** Update geometry only: never rebuild DOM, blur an input, or scroll the page. */
export function installMobileViewport(win = window, doc = document) {
const viewport = win.visualViewport;
if (!viewport) return () => {};
const root = doc.documentElement;
let baseline = win.innerHeight;
let width = win.innerWidth;
let open = false;
let frame = null;
function update() {
frame = null;
const active = doc.activeElement;
const editing = Boolean(active?.matches?.("textarea, input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]), [contenteditable=true]"));
if (width !== win.innerWidth) {
width = win.innerWidth;
baseline = win.innerHeight;
} else if (!editing && !open) {
baseline = Math.max(win.innerHeight, viewport.height);
}
const state = mobileViewportState({ width, height: viewport.height, layoutHeight: win.innerHeight, baselineHeight: baseline, scale: viewport.scale, offsetTop: viewport.offsetTop, editing, wasOpen: open });
open = state.keyboard;
root.classList.toggle("keyboard-open", open);
if (open) {
root.style.setProperty("--keyboard-visible-height", `${state.height}px`);
root.style.setProperty("--keyboard-viewport-top", `${state.top}px`);
} else {
root.style.removeProperty("--keyboard-visible-height");
root.style.removeProperty("--keyboard-viewport-top");
}
}
function schedule() {
if (frame == null) frame = win.requestAnimationFrame(update);
}
for (const event of ["resize", "scroll"]) viewport.addEventListener(event, schedule);
win.addEventListener("resize", schedule);
doc.addEventListener("focusin", schedule);
doc.addEventListener("focusout", schedule);
update();
return () => {
for (const event of ["resize", "scroll"]) viewport.removeEventListener(event, schedule);
win.removeEventListener("resize", schedule);
doc.removeEventListener("focusin", schedule);
doc.removeEventListener("focusout", schedule);
if (frame != null) win.cancelAnimationFrame(frame);
root.classList.remove("keyboard-open");
root.style.removeProperty("--keyboard-visible-height");
root.style.removeProperty("--keyboard-viewport-top");
};
}
-694
View File
@@ -1,694 +0,0 @@
// The shared modal controller: one focus trap, one background-inert rule and
// one Escape/close path for every role="dialog" surface in the web client.
//
// It is deliberately DOM-only and dependency-free. Views keep owning their
// markup, copy and state transitions: a view stage()s the dialog it built (or
// open()s an imperative viewer) and gives the controller the callback that
// closes it. The controller never mutates view state itself.
//
// The dialog layer lives outside .app-root (see app.js): inert inherits, so a
// panel inside the inert root could not become interactive. Every active panel
// is re-parented into #modalLayer, the app root gets native `inert` (or the
// aria-hidden + tabindex fallback), and only the top panel owns Tab/Escape.
/** The selectors a focusable candidate can match, in DOM order at discovery. */
export const FOCUSABLE_SELECTOR = [
"a[href]",
"area[href]",
"button",
"input",
"select",
"textarea",
"iframe",
"object",
"embed",
"summary",
"audio[controls]",
"video[controls]",
"[contenteditable]",
"[tabindex]",
].join(",");
const NATIVE_FOCUSABLE = new Set([
"button",
"input",
"select",
"textarea",
"iframe",
"object",
"embed",
"summary",
]);
function attr(node, name) {
return typeof node.getAttribute === "function" ? node.getAttribute(name) : null;
}
function hasAttr(node, name) {
return typeof node.hasAttribute === "function" ? node.hasAttribute(name) : attr(node, name) != null;
}
function tagName(node) {
return String(node.tagName ?? "").toLowerCase();
}
function computedStyle(node) {
try {
return node.ownerDocument?.defaultView?.getComputedStyle?.(node) ?? null;
} catch {
return null;
}
}
function hiddenBySelf(node) {
if (node.hidden) return true;
if (attr(node, "aria-hidden") === "true") return true;
if (hasAttr(node, "inert")) return true;
const style = computedStyle(node);
return Boolean(style && (style.display === "none" || style.visibility === "hidden"));
}
function hiddenByAncestor(node, root) {
let current = node;
while (current) {
if (hiddenBySelf(current)) return true;
if (current === root) break;
current = current.parentElement ?? null;
}
return false;
}
/** Whether one node is a reachable control (not disabled, hidden or removed). */
export function isFocusable(node, { root = null } = {}) {
if (!node || (node.nodeType != null && node.nodeType !== 1)) return false;
if (node.disabled === true || hasAttr(node, "disabled")) return false;
if (hiddenByAncestor(node, root)) return false;
const tabindex = attr(node, "tabindex");
if (tabindex != null && Number(tabindex) < 0) return false;
if (node.isContentEditable === true) return true;
const tag = tagName(node);
if (tag === "input" && String(attr(node, "type") ?? "").toLowerCase() === "hidden") return false;
if (tag === "a" || tag === "area") return hasAttr(node, "href");
if (NATIVE_FOCUSABLE.has(tag)) return true;
if (tag === "audio" || tag === "video") return hasAttr(node, "controls");
if (tag === "" && typeof node.focus === "function") return true;
// A div/span with a non-negative tabindex is focusable even though it is not
// a native control (the change/timeline rows use exactly this form).
return tabindex != null && Number(tabindex) >= 0;
}
/** Every reachable control inside [panel], in DOM order. */
export function focusableElements(panel) {
if (!panel || typeof panel.querySelectorAll !== "function") return [];
return [...panel.querySelectorAll(FOCUSABLE_SELECTOR)].filter((node) =>
isFocusable(node, { root: panel }),
);
}
/** The wrapped index for one Tab/Shift+Tab step; -1 when there is no control. */
export function wrapFocusIndex(index, direction, count) {
if (count <= 0) return -1;
if (!Number.isInteger(index) || index < 0) return direction < 0 ? count - 1 : 0;
return ((index + direction) % count + count) % count;
}
/** The initial focus target is the first control, else the panel itself (-1). */
export function initialFocusIndex(count) {
return count > 0 ? 0 : -1;
}
function supportsNativeInert() {
try {
return typeof HTMLElement !== "undefined" && "inert" in HTMLElement.prototype;
} catch {
return false;
}
}
function isConnected(node) {
return Boolean(node) && node.isConnected !== false;
}
function contains(root, node) {
if (!root || !node) return false;
return root === node || root.contains?.(node) === true;
}
function inInertSubtree(node, document_) {
let current = node;
while (current) {
if (hasAttr(current, "inert")) return true;
current = current.parentElement ?? null;
}
return false;
}
function focusElement(element) {
if (!element || typeof element.focus !== "function") return false;
try {
element.focus({ preventScroll: true });
} catch {
try {
element.focus();
} catch {
return false;
}
}
return true;
}
/**
* Create one controller for the page. Options are injectable for the unit tests:
* a document, a layer, the background element/skip links, and whether native
* inert exists. Production passes none of them and uses the real document.
*/
export function createModalController(options = {}) {
const document_ = options.document ?? globalThis.document;
const window_ = options.window ?? globalThis.window;
const getLayer =
typeof options.layer === "function"
? options.layer
: () => options.layer ?? document_?.getElementById?.("modalLayer") ?? document_?.body;
const getBackground =
typeof options.background === "function"
? options.background
: () => document_?.querySelector?.(".app-root") ?? null;
const getSkipLinks =
typeof options.skipLinks === "function"
? options.skipLinks
: () =>
options.skipLinks ??
(document_?.querySelectorAll ? [...document_.querySelectorAll(".skip-link")] : []);
const nativeInert =
typeof options.supportsInert === "function" ? options.supportsInert : () => supportsNativeInert();
const defaultFallbackSelectors = options.fallbackSelectors ?? [
"#detailTitle",
"#listTitle",
".detail-pane h1",
".list-pane .pane-title",
"#pane-main",
];
/** @type {Array<object>} active entries, bottom first */
const stack = [];
/** @type {Map<string, object>} dialogs staged during the current render */
const pending = new Map();
let backgroundState = null;
let keydownBound = false;
let focusinBound = false;
let fallbackMode = false;
// One history entry per open modal, so the browser Back button closes it the
// same way Escape and the backdrop do. A modal that closes through the UI
// pops its own entry instead of leaving a dead one behind.
let historyPushed = false;
let historyClosing = false;
function pushModalHistory(id) {
if (historyPushed || !window_?.history) return;
try {
window_.history.pushState(
{ ...(window_.history.state ?? {}), pipelinesModal: id },
"",
);
historyPushed = true;
} catch {
// A history-refusing environment simply keeps the UI close paths.
}
}
function popModalHistory() {
if (!historyPushed || historyClosing) return;
historyPushed = false;
try {
// Only pop our own entry. If the app navigated while the dialog was open,
// its route entry is on top now; calling back() here would undo that
// navigation (the dialog's own entry is buried under it).
if (window_.history?.state?.pipelinesModal == null) return;
window_.history.back();
} catch {
// Nothing to pop.
}
}
if (window_?.addEventListener) {
window_.addEventListener("popstate", () => {
if (!historyPushed) return;
historyPushed = false;
const entry = top();
if (!entry) return;
historyClosing = true;
closeEntry(entry, { restore: true });
historyClosing = false;
});
}
function layer() {
return getLayer() ?? document_?.body ?? null;
}
function top() {
return stack.length ? stack[stack.length - 1] : null;
}
function find(id) {
return stack.find((entry) => entry.id === id) ?? null;
}
function normalizeTrigger(candidate, panel) {
if (!candidate || candidate === document_?.body) return null;
if (candidate.nodeType != null && candidate.nodeType !== 1) return null;
if (contains(panel, candidate)) return null;
return candidate;
}
/**
* Capture the opener now, before the view's state render replaces the trigger.
* A stage for an already-open id deliberately keeps the original trigger.
*/
function stage(id, panel, entryOptions = {}) {
if (!panel) return;
const existing = find(id);
pending.set(id, {
panel,
options: entryOptions,
trigger: existing
? existing.trigger
: normalizeTrigger(entryOptions.trigger ?? document_?.activeElement, panel),
});
}
function ensureEntryBackground(entry) {
const root = getBackground();
const skip = getSkipLinks();
const targets = [root, ...skip].filter(Boolean);
if (!targets.length) return;
if (!backgroundState) {
fallbackMode = !nativeInert();
backgroundState = {
mode: fallbackMode ? "fallback" : "inert",
targets: targets.map((element) => ({
element,
inert: attr(element, "inert"),
ariaHidden: attr(element, "aria-hidden"),
})),
tabindexes: fallbackMode ? new Map() : null,
};
}
if (backgroundState.mode === "inert") {
for (const state of backgroundState.targets) {
state.element.setAttribute("inert", "");
if (state.element !== root) state.element.setAttribute("aria-hidden", "true");
}
return;
}
for (const state of backgroundState.targets) {
state.element.setAttribute("aria-hidden", "true");
}
const focusables = [];
for (const state of backgroundState.targets) {
const element = state.element;
if (element.matches?.(FOCUSABLE_SELECTOR) || isFocusable(element)) focusables.push(element);
if (element.querySelectorAll) focusables.push(...element.querySelectorAll(FOCUSABLE_SELECTOR));
}
for (const element of focusables) {
if (!isConnected(element)) continue;
if (!backgroundState.tabindexes.has(element)) {
backgroundState.tabindexes.set(element, attr(element, "tabindex"));
}
element.setAttribute("tabindex", "-1");
}
if (entry && !focusinBound) {
document_.addEventListener("focusin", onFocusIn, true);
focusinBound = true;
}
}
function restoreBackground() {
const state = backgroundState;
backgroundState = null;
fallbackMode = false;
if (!state) return;
for (const target of state.targets) {
if (target.inert == null) target.element.removeAttribute?.("inert");
else target.element.setAttribute("inert", target.inert);
if (target.ariaHidden == null) target.element.removeAttribute?.("aria-hidden");
else target.element.setAttribute("aria-hidden", target.ariaHidden);
}
if (state.tabindexes) {
for (const [element, value] of state.tabindexes) {
if (!isConnected(element)) continue;
if (value == null) element.removeAttribute("tabindex");
else element.setAttribute("tabindex", value);
}
}
}
function setLowerInert(entry, inert) {
if (!entry) return;
if (inert) {
if (entry.inertedByStack) return;
entry.inertedByStack = true;
entry.inertPrior = attr(entry.panel, "inert");
entry.panel.setAttribute("inert", "");
return;
}
if (!entry.inertedByStack) return;
entry.inertedByStack = false;
if (entry.inertPrior == null) entry.panel.removeAttribute?.("inert");
else entry.panel.setAttribute("inert", entry.inertPrior);
entry.inertPrior = null;
}
function focusPanel(panel) {
if (!panel) return;
if (!hasAttr(panel, "tabindex")) panel.setAttribute("tabindex", "-1");
focusElement(panel);
}
function focusInside(panel, index = -1) {
const focusables = focusableElements(panel);
if (!focusables.length) {
focusPanel(panel);
return;
}
const target = focusables[initialFocusIndex(focusables.length)];
focusElement(target);
}
function rememberFocus(panel) {
const active = document_?.activeElement ?? null;
if (!active) return { wasPanel: false, index: -1 };
if (active === panel) return { wasPanel: true, index: -1 };
const index = focusableElements(panel).indexOf(active);
return { wasPanel: false, index };
}
function updateEntry(entry, staged) {
entry.options = { ...entry.options, ...staged.options };
if (entry.trigger == null && staged.trigger) entry.trigger = staged.trigger;
if (entry.panel === staged.panel) return false;
// A stable dialog keeps its mounted panel across streaming re-renders. A
// rebuild would restart the modal-in animation (the rename dialog visibly
// blinked/reappeared on every chat frame) and discard whatever the operator
// had typed into it.
if (
entry.panel?.getAttribute?.("data-modal-stable") === "true" &&
staged.panel?.getAttribute?.("data-modal-stable") === "true"
) {
return false;
}
const remembered = rememberFocus(entry.panel);
const oldPanel = entry.panel;
if (typeof oldPanel.replaceWith === "function" && oldPanel.parentElement) {
oldPanel.replaceWith(staged.panel);
} else {
oldPanel.remove?.();
layer()?.append(staged.panel);
}
entry.panel = staged.panel;
if (entry.inertedByStack) staged.panel.setAttribute("inert", "");
if (remembered.wasPanel) {
focusPanel(staged.panel);
} else if (remembered.index >= 0) {
const focusables = focusableElements(staged.panel);
if (!focusables.length) focusPanel(staged.panel);
else focusElement(focusables[Math.min(remembered.index, focusables.length - 1)]);
}
return true;
}
function openEntry(id, staged, renderManaged) {
const previous = top();
if (previous) setLowerInert(previous, true);
const entry = {
id,
panel: staged.panel,
options: staged.options,
trigger: staged.trigger ?? null,
renderManaged,
inertedByStack: false,
inertPrior: null,
};
stack.push(entry);
const host = layer();
if (host && staged.panel.parentElement !== host) host.append(staged.panel);
return entry;
}
function resolveReturnTarget(entry) {
const options = entry.options ?? {};
if (typeof options.restore === "function") {
const explicit = options.restore();
if (explicit) return explicit;
}
if (entry.trigger && isConnected(entry.trigger) && !inInertSubtree(entry.trigger)) {
return entry.trigger;
}
const selectors = [];
if (options.triggerSelector) selectors.push(options.triggerSelector);
if (Array.isArray(options.fallbackSelectors)) selectors.push(...options.fallbackSelectors);
selectors.push(...defaultFallbackSelectors);
for (const selector of selectors) {
if (!selector) continue;
let target = null;
try {
target = document_?.querySelector?.(selector) ?? null;
} catch {
target = null;
}
if (target && isConnected(target) && !inInertSubtree(target)) return target;
}
const pane = document_?.getElementById?.("pane-main") ?? null;
if (pane) return pane;
return document_?.body ?? null;
}
function restoreFocus(entry) {
if (entry.options?.restoreFocus === false) return;
const target = resolveReturnTarget(entry);
if (!target) return;
if (target === document_?.body) {
const pane = document_?.getElementById?.("pane-main");
if (pane) {
if (!hasAttr(pane, "tabindex")) pane.setAttribute("tabindex", "-1");
focusElement(pane);
}
return;
}
if (!hasAttr(target, "tabindex") && !NATIVE_FOCUSABLE.has(tagName(target)) && tagName(target) !== "a") {
target.setAttribute("tabindex", "-1");
}
focusElement(target);
// The rebuilt background may still be mid-layout at this synchronous point
// (Chrome can refuse focus while the freshly inserted pane has no boxes yet).
// One next-frame retry re-resolves the trigger, so a re-render between the
// close and the frame cannot leave focus on <body>.
if (document_.activeElement !== target) {
const frame = document_.defaultView?.requestAnimationFrame ?? globalThis.requestAnimationFrame;
if (typeof frame === "function") {
frame(() => {
if (document_.activeElement !== document_?.body) return;
const current = resolveReturnTarget(entry);
if (current && current !== document_?.body) focusElement(current);
});
}
}
}
function releaseIfEmpty() {
if (stack.length) return;
restoreBackground();
if (keydownBound) {
document_.removeEventListener("keydown", onKeyDown, false);
keydownBound = false;
}
if (focusinBound) {
document_.removeEventListener("focusin", onFocusIn, true);
focusinBound = false;
}
}
function closeEntry(entry, { restore = true } = {}) {
const index = stack.indexOf(entry);
if (index === -1) return false;
const wasTop = index === stack.length - 1;
stack.splice(index, 1);
if (entry.panel?.parentElement) entry.panel.remove();
// Lifecycle cleanup also runs for browser Back and programmatic closeAll,
// not just the owner's Escape/backdrop request handler.
entry.options?.onClosed?.();
if (wasTop) {
const next = top();
if (next) setLowerInert(next, false);
}
if (stack.length) {
ensureEntryBackground(top());
} else {
releaseIfEmpty();
}
if (restore && wasTop) restoreFocus(entry);
if (!stack.length) popModalHistory();
return true;
}
function ensureListeners() {
if (!stack.length) return;
if (!keydownBound) {
document_.addEventListener("keydown", onKeyDown, false);
keydownBound = true;
}
if (fallbackMode && !focusinBound) {
document_.addEventListener("focusin", onFocusIn, true);
focusinBound = true;
}
}
function onKeyDown(event) {
const entry = top();
if (!entry) return;
if (event.key === "Escape") {
if (event.defaultPrevented) return;
event.preventDefault();
event.stopPropagation();
entry.options?.onClose?.();
return;
}
if (event.key !== "Tab") return;
const focusables = focusableElements(entry.panel);
if (!focusables.length) {
event.preventDefault();
focusPanel(entry.panel);
return;
}
const active = document_?.activeElement ?? null;
const current = focusables.indexOf(active);
if (current === -1) {
event.preventDefault();
focusElement(focusables[event.shiftKey ? focusables.length - 1 : 0]);
return;
}
if (event.shiftKey && current === 0) {
event.preventDefault();
focusElement(focusables[focusables.length - 1]);
return;
}
if (!event.shiftKey && current === focusables.length - 1) {
event.preventDefault();
focusElement(focusables[0]);
}
}
function onFocusIn(event) {
const entry = top();
if (!entry) return;
if (contains(entry.panel, event.target)) return;
focusInside(entry.panel);
}
function applyStackState() {
if (!stack.length) {
releaseIfEmpty();
return;
}
ensureEntryBackground(top());
ensureListeners();
}
/**
* Open (or update) one dialog immediately. Imperative viewers call this
* directly; render-managed dialogs stage() during a render and reconcile().
*/
function open(id, panel, entryOptions = {}) {
if (!panel) return null;
const existing = find(id);
if (existing) {
updateEntry(existing, { panel, options: entryOptions, trigger: existing.trigger });
applyStackState();
return existing.panel;
}
const entry = openEntry(
id,
{
panel,
options: entryOptions,
trigger: normalizeTrigger(entryOptions.trigger ?? document_?.activeElement, panel),
},
entryOptions.renderManaged !== false,
);
applyStackState();
// Only overlays that act as their own view carry a history entry (the
// viewers). A transient sheet must not, or closing it while the app
// navigates would undo that navigation with history.back().
if (entryOptions.history !== false) pushModalHistory(id);
if (entryOptions.focus !== false) focusInside(entry.panel);
return entry.panel;
}
/**
* Reconcile the dialogs a view built this render. Same-id elements replace
* their panel and keep focus; render-managed ids that disappeared close and
* return focus; staged ids in order become the stack.
*/
function reconcile() {
if (!pending.size) {
// Nothing staged is a real state when no render-managed dialog is open;
// persistent (imperative) entries are untouched.
if (stack.some((entry) => entry.renderManaged)) {
const missing = stack.filter((entry) => entry.renderManaged).reverse();
for (const entry of missing) closeEntry(entry, { restore: stack[stack.length - 1] === entry });
}
applyStackState();
return;
}
const staged = new Map(pending);
pending.clear();
const missing = stack.filter((entry) => entry.renderManaged && !staged.has(entry.id)).reverse();
for (const entry of missing) {
closeEntry(entry, { restore: stack[stack.length - 1] === entry });
}
let opened = null;
for (const [id, item] of staged) {
const existing = find(id);
if (existing) {
updateEntry(existing, item);
} else {
opened = openEntry(id, item, true);
}
}
applyStackState();
if (opened && top() === opened) focusInside(opened.panel);
}
/** Close one dialog by id (used by the imperative viewers and the sheet). */
function close(id, { restoreFocus: restore = true } = {}) {
const entry = find(id);
if (!entry) return false;
return closeEntry(entry, { restore });
}
function closeAll() {
while (stack.length) {
const entry = stack[stack.length - 1];
closeEntry(entry, { restore: false });
}
}
return {
stage,
open,
reconcile,
close,
closeAll,
top,
isOpen: (id) => Boolean(find(id)),
stackIds: () => stack.map((entry) => entry.id),
pendingCount: () => pending.size,
// Exposed for focused tests: the listener state must return to zero after
// the last dialog closes.
listenerState: () => ({ keydown: keydownBound, focusin: focusinBound }),
};
}
-329
View File
@@ -1,329 +0,0 @@
// Pure, DOM-free notification model. Auto retains failed/waiting alerts;
// per-run on also alerts terminal success and off suppresses every tray alert.
//
// Everything here is pure: no DOM, no clock, no storage access. The page owns
// the Notification constructor, the permission request gesture and localStorage;
// the unit tests own the state machine. The attention model in `attention.js`
// is the single authority for which runs qualify and for the dismissal identity,
// so the in-page "Needs you" surface and the tray can never disagree.
import { AttentionKind, attentionKey, attentionKindOf } from "./attention.js";
// ---------------------------------------------------------------------------
// Kinds, headlines and the run line
// ---------------------------------------------------------------------------
/** Notification kinds; success does not create a Needs you entry. */
export const RunAlertKind = Object.freeze({
Decision: AttentionKind.Decision,
Failed: AttentionKind.Failed,
Succeeded: Object.freeze({ name: "Succeeded" }),
});
/** `alertKindOf`: an attention kind is already exactly the notification kind. */
export function alertKindOf(kind) {
if (kind?.name === "Succeeded") return RunAlertKind.Succeeded;
if (kind === AttentionKind.Decision || kind?.name === AttentionKind.Decision.name) {
return AttentionKind.Decision;
}
if (kind === AttentionKind.Failed || kind?.name === AttentionKind.Failed.name) {
return AttentionKind.Failed;
}
return null;
}
/** The short headline one kind shows (RunAlerts.alertTitle). */
export function alertTitle(kind) {
switch (alertKindOf(kind)?.name) {
case "Decision":
return "A run needs your decision";
case "Failed":
return "A run failed";
case "Succeeded":
return "A run succeeded";
default:
return "";
}
}
/** The stable run+kind identity, the unit of dedupe (RunAlerts.alertKey). */
export function alertKey(runId, kind) {
const resolved = alertKindOf(kind);
return resolved ? attentionKey(runId, resolved) : "";
}
/**
* The line naming the run (RunAlerts.alertText): the attention label, then the
* pipeline it belongs to. The label is the run's trimmed title, falling back to
* the pipeline name; a blank or equal pipeline is never repeated, so there is no
* trailing separator.
*/
export function alertBody(run) {
const pipeline = String(run?.pipeline ?? run?.name ?? "");
const title = String(run?.label ?? run?.title ?? "").trim();
const label = title !== "" ? title : pipeline;
if (pipeline === "" || pipeline === label) return label;
return `${label} \u00b7 ${pipeline}`;
}
// ---------------------------------------------------------------------------
// The ledger: seed, observe, dedupe
// ---------------------------------------------------------------------------
/**
* Tracks the last status seen for every run and the run+kind alerts already
* raised in this page session.
*
* - `seed(runs)` records the authoritative list without raising anything, so a
* run that was already failed/waiting when the page loaded (or when the socket
* reconnected) never notifies.
* - `beginSeed()`/`endSeed()` bracket the `subscribe` snapshot: the server writes
* the current state of every watched run before its ack, and those frames are
* seeds too, not transitions.
* - `observe(frame)` raises only when a known run's status changes *into*
* `failed` or `waiting`. A duplicate frame (same status), an unchanged
* qualifying state, an unknown status and a first-seen run all return null.
* - A run+kind key is forgotten when the run leaves that qualifying state, so a
* genuinely new transition (for example failed -> running -> failed again) can
* notify once more; the same transition can never repeat.
* - A key present in the attention surface's dismissed set is suppressed. The
* dismissal is the attention model's own `{runId}:{kind}` identity.
* - `reset()` drops the status baseline on a socket drop but keeps the notified
* keys, so a gap that swallows a transition cannot raise a notification after
* the reconnect; the next seed establishes the new baseline.
*/
export function createAlertLedger() {
const lastStatus = new Map();
const modes = new Map();
const notified = new Set();
let seeding = false;
function seed(runs) {
const next = new Map();
modes.clear();
for (const run of runs ?? []) {
const runId = runIdOf(run?.id ?? run?.run_id);
if (runId == null) continue;
next.set(runId, normalizeStatus(run?.status));
modes.set(runId, normalizeStatus(run?.notify_mode) || "auto");
}
lastStatus.clear();
for (const [runId, status] of next) lastStatus.set(runId, status);
pruneNotified(next);
}
function observe(frame, { dismissed } = {}) {
const runId = runIdOf(frame?.run_id ?? frame?.runId ?? frame?.id);
const status = normalizeStatus(frame?.status);
if (runId == null || status === "") return null;
const previous = lastStatus.get(runId);
lastStatus.set(runId, status);
if (frame?.notify_mode != null) modes.set(runId, normalizeStatus(frame.notify_mode));
const mode = modes.get(runId) || "auto";
const kind = status === "succeeded" && mode === "on" ? RunAlertKind.Succeeded : attentionKindOf(status, frame?.export_pending_sequence);
if (!kind) {
forget(runId, AttentionKind.Decision);
forget(runId, AttentionKind.Failed);
forget(runId, RunAlertKind.Succeeded);
return null;
}
// A run can only be in one qualifying state; forget the other kind's key so
// a later transition back into it is a new event.
for (const other of Object.values(RunAlertKind)) {
if (other !== kind) forget(runId, other);
}
if (seeding) return null;
if (mode === "off") return null;
if (previous === undefined || previous === status) return null;
const key = alertKey(runId, kind);
if (notified.has(key)) return null;
notified.add(key);
const dismissedKeys =
dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []);
if (dismissedKeys.has(key)) return null;
return {
runId,
kind,
key,
title: alertTitle(kind),
body: alertBody(frame),
};
}
function reset() {
lastStatus.clear();
modes.clear();
seeding = false;
}
function beginSeed() {
seeding = true;
}
function endSeed() {
seeding = false;
}
function forget(runId, kind) {
const key = alertKey(runId, kind);
if (key !== "") notified.delete(key);
}
function pruneNotified(statuses) {
for (const key of [...notified]) {
const split = key.lastIndexOf(":");
if (split < 0) continue;
const runId = runIdOf(key.slice(0, split));
const kindName = key.slice(split + 1);
const status = runId == null ? undefined : statuses.get(runId);
// A run that is absent from this read tells us nothing; keep its key.
if (status === undefined) continue;
const kind = attentionKindOf(status);
if (!kind || kind.name !== kindName) notified.delete(key);
}
}
return {
seed,
observe,
reset,
beginSeed,
endSeed,
/** Test/introspection helper; returns a copy, never the live set. */
notifiedKeys: () => [...notified],
statusOf: (runId) => lastStatus.get(runIdOf(runId)),
};
}
/** Trim/lowercase the server's status word; an absent value is "". */
function normalizeStatus(status) {
return String(status ?? "").trim().toLowerCase();
}
/** A positive run id as a number, or null for anything malformed. */
function runIdOf(value) {
const id = Number(value);
return Number.isFinite(id) && id > 0 ? id : null;
}
// ---------------------------------------------------------------------------
// Permission wording and persistence
// ---------------------------------------------------------------------------
/** Android's NOTIFICATION_RATIONALE, verbatim (RunAlerts.kt). */
export const NOTIFICATION_RATIONALE =
"Pipelines can notify you when a run is waiting for your decision or has failed. " +
"Without it, those runs still appear in the in-app Needs you surface.";
/** The explicit-gesture control's label; shown only when a request is possible. */
export const NOTIFICATION_REQUEST_LABEL = "Enable notifications";
export const NOTIFICATION_UNSUPPORTED =
"This browser does not support notifications. The in-app Needs you surface is the only channel.";
export const NOTIFICATION_INSECURE =
"Notifications need a secure context (https or localhost). This page is not secure, so the " +
"in-app Needs you surface is the only channel.";
export const NOTIFICATION_GRANTED =
"Notifications are on. Failed and waiting runs will raise a browser notification.";
export const NOTIFICATION_DENIED =
"Notifications are blocked for this site. Allow them in the browser's site settings to use them; " +
"until then the in-app Needs you surface is the only channel.";
export const NOTIFICATION_DEFAULT =
"Notifications are off. Enable them to be told when a run fails or needs your decision.";
export const NOTIFICATION_DEFAULT_ASKED =
"Notifications are still off. Your browser did not grant permission when asked; you can ask " +
"again, or the in-app Needs you surface remains the only channel.";
/**
* The total permission view for Settings. `supported` and `secureContext` are
* the browser's own facts; `permission` is the Notification API's own word
* (`default` | `granted` | `denied`, anything else treated as default).
*
* Only a supported, secure page whose permission is still `default` offers the
* request control. The request is always an explicit user gesture; nothing here
* asks on its own, and the `asked` flag only changes the honest wording.
*/
export function notificationPermissionState({
supported = true,
secureContext = true,
permission = "default",
asked = false,
} = {}) {
const state = !supported
? "unsupported"
: !secureContext
? "insecure"
: permission === "granted"
? "granted"
: permission === "denied"
? "denied"
: "default";
const canRequest = state === "default";
let body = NOTIFICATION_DEFAULT;
switch (state) {
case "unsupported":
body = NOTIFICATION_UNSUPPORTED;
break;
case "insecure":
body = NOTIFICATION_INSECURE;
break;
case "granted":
body = NOTIFICATION_GRANTED;
break;
case "denied":
body = NOTIFICATION_DENIED;
break;
default:
body = asked ? NOTIFICATION_DEFAULT_ASKED : NOTIFICATION_DEFAULT;
}
return {
state,
body,
canRequest,
actionLabel: canRequest ? NOTIFICATION_REQUEST_LABEL : null,
asked: Boolean(asked),
};
}
/**
* The browser facts the permission view needs. Pure enough to unit-test with a
* fake scope; the real page passes `globalThis`. An unrecognised permission
* value is read as `default` rather than guessed.
*/
export function notificationEnvironment(scope = globalThis) {
const ctor = scope?.Notification;
const supported = typeof ctor === "function";
const raw = supported ? ctor.permission : "default";
const permission = raw === "granted" || raw === "denied" ? raw : "default";
return { supported, secureContext: scope?.isSecureContext === true, permission };
}
/** The one localStorage key for this page's notification preference. */
export const NOTIFY_STORAGE_KEY = "pipelines.web.notify.v1";
/** Encode only the asked flag; no endpoint, credential or permission claim. */
export function encodeNotificationSettings(settings) {
return JSON.stringify({ asked: Boolean(settings?.asked) });
}
/**
* Decode the stored preference. Total: blank, unreadable JSON, a non-object, a
* non-boolean or a throwing getter all mean "never asked", so a malformed value
* can never throw into the page or claim the operator was asked.
*/
export function decodeNotificationSettings(stored) {
const text = stored == null ? "" : String(stored).trim();
if (text === "") return { asked: false };
let parsed;
try {
parsed = JSON.parse(text);
} catch {
return { asked: false };
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { asked: false };
return { asked: parsed.asked === true };
}
-503
View File
@@ -1,503 +0,0 @@
// Pure pipeline-list/detail logic for the web client. Deliberately DOM-free:
// every helper here is a plain function a `node --test` can exercise without a
// browser, exactly like `client.js`. The DOM wiring lives in `app.js`.
//
// The wording and behaviour mirror the Android app one-for-one — the same
// singular/plural spelling, the same status vocabulary, the same comparator
// tie-breaks and the same empty-state sentences — because the web client's goal
// is feature parity, not a re-invention:
// ui/Format.kt, ui/screens/ListSort.kt, ui/screens/ListFilter.kt,
// ui/screens/PipelineLastRun.kt, ui/screens/PipelineDetailScreen.kt,
// ui/components/RunStatus.kt.
// ---------------------------------------------------------------------------
// 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
* timestamp is handled the same way everywhere.
*/
export function parseInstant(text) {
if (typeof text !== "string" || text.trim() === "") return null;
const ms = Date.parse(text);
return Number.isNaN(ms) ? null : ms;
}
/**
* An RFC3339 timestamp as the app's one human, local rendering (`d MMM HH:mm`,
* e.g. `17 Oct 21:26`), or null when blank/unparseable so the caller omits the
* value rather than printing a blank. The day/month/hour/minute parts are
* assembled from `Intl.DateTimeFormat.formatToParts`, so no locale's list comma
* leaks into the string and the shape is the same everywhere. `timeZone` is
* accepted for deterministic tests; `locale` defaults to a fixed English so the
* month abbreviation matches the app's `d MMM` wording rather than drifting with
* the host locale.
*/
export function formatLocalTimestamp(instant, options = {}) {
const ms = parseInstant(instant);
if (ms === null) return null;
const { timeZone, locale = "en-GB" } = options;
const parts = new Intl.DateTimeFormat(locale, {
day: "numeric",
month: "short",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
...(timeZone ? { timeZone } : {}),
}).formatToParts(new Date(ms));
const get = (type) => parts.find((part) => part.type === type)?.value ?? "";
return `${get("day")} ${get("month")} ${get("hour")}:${get("minute")}`;
}
/**
* Human duration for a whole number of seconds: `45s`, `2m 5s`, `1h 2m`. The
* single duration rule every surface shares. A negative total renders as `0s`
* so a clamped value never prints a negative.
*/
export function formatDuration(totalSeconds) {
const seconds = Math.max(0, Math.trunc(totalSeconds));
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}
/**
* Non-negative whole seconds between two RFC3339 timestamps, or null when either
* is blank/unparseable or the end precedes the start.
*/
export function durationSeconds(start, end) {
const from = parseInstant(start);
const to = parseInstant(end);
if (from === null || to === null) return null;
const seconds = Math.floor((to - from) / 1000);
return seconds >= 0 ? seconds : null;
}
/**
* Non-negative whole seconds from a `start` timestamp to `nowMillis`, or null
* when `start` is blank/unparseable. Clamps a future/unparseable elapsed to 0 so
* a live timer never prints a negative.
*/
export function secondsSince(start, nowMillis) {
const from = parseInstant(start);
if (from === null) return null;
return Math.max(0, Math.floor((nowMillis - from) / 1000));
}
/**
* The time a run has taken so far: while it is still executing, its live elapsed
* from its start to `nowMs`; once finished, its stored total duration. Null when
* the needed timestamps are unusable, so the caller omits the value.
*/
export function runDurationText(run, nowMs) {
if (run && run.executing) {
const elapsed = secondsSince(run.created_at, nowMs);
return elapsed === null ? null : formatDuration(elapsed);
}
const total = durationSeconds(run?.created_at, run?.finished_at);
return total === null ? null : formatDuration(total);
}
/**
* A compact "how long ago" for a run's start: `just now` under a minute, then
* `Nm ago`/`Nh ago`/`Nd ago`. Null when the timestamp is blank/unparseable so
* the caller omits the fragment instead of printing a blank. A future start
* (clock skew) reads as `just now`, never a negative age.
*/
export function formatRanAgo(createdAt, nowMs) {
const start = parseInstant(createdAt);
if (start === null) return null;
const seconds = Math.max(0, Math.floor((nowMs - start) / 1000));
if (seconds < 60) return "just now";
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
/**
* A stage count in the app's one singular/plural spelling (`1 stage` /
* `n stages`), shared by the list and the detail so a single-stage pipeline
* never reads "1 stages".
*/
export function stageCountText(count) {
const n = Number(count) || 0;
return `${n} ${n === 1 ? "stage" : "stages"}`;
}
// ---------------------------------------------------------------------------
// Run states (ui/components/RunStatus.kt)
// ---------------------------------------------------------------------------
const RUN_STATE_ALIASES = {
running: "running",
queued: "queued",
waiting: "waiting",
active: "active",
succeeded: "succeeded",
success: "succeeded",
completed: "succeeded",
done: "succeeded",
failed: "failed",
error: "failed",
canceled: "canceled",
cancelled: "canceled",
interrupted: "interrupted",
blocked: "blocked",
skipped: "skipped",
};
/**
* Maps a server status or outcome word to the app's run-state word, accepting
* the server's own vocabulary only. A blank or unrecognised value falls back to
* `unknown` so a bad value never crashes the UI.
*/
export function runStateOf(status) {
const key = String(status ?? "").trim().toLowerCase();
return RUN_STATE_ALIASES[key] ?? "unknown";
}
// ---------------------------------------------------------------------------
// Last-run join and badge (ui/screens/PipelineLastRun.kt)
// ---------------------------------------------------------------------------
/** Shown for a pipeline that has recorded no run. */
export const NO_RUNS_RECORDED = "no runs recorded";
/**
* Timestamps decide recency; the higher run id breaks an exact tie (or a bad
* timestamp). The one recency rule, shared by the per-pipeline last-run join
* and the "most recent run" ordering.
*/
export function isMoreRecent(candidate, current) {
const a = parseInstant(candidate.created_at);
const b = parseInstant(current.created_at);
if (a !== null && b !== null && a !== b) return a > b;
return candidate.id > current.id;
}
/**
* Joins the whole run history onto pipelines by pipeline id: the most recent
* run per pipeline. The input order never matters — recency is decided from the
* timestamps, with the higher run id breaking an exact tie — so a pipeline with
* no runs is simply absent from the result (the caller renders
* [NO_RUNS_RECORDED] for it).
*/
export function latestRunByPipeline(runs) {
const latest = new Map();
for (const run of runs ?? []) {
const current = latest.get(run.pipeline_id);
if (current === undefined || isMoreRecent(run, current)) latest.set(run.pipeline_id, run);
}
return latest;
}
/** The display facts one pipeline row shows for `run`, anchored to `nowMs`. */
export function runBadge(run, nowMs) {
return {
runId: run.id,
state: runStateOf(run.status),
ranAgo: formatRanAgo(run.created_at, nowMs),
duration: runDurationText(run, nowMs),
};
}
/**
* The last-run secondary line, e.g. `2h ago · 1m 5s · run 42`. Missing
* fragments (an unparseable start, a run still executing) are omitted so no
* blank separator is ever printed; the run id is always present.
*/
export function runBadgeMetaLine(badge) {
const fragments = [badge.ranAgo, badge.duration, `run ${badge.runId}`];
return fragments.filter((fragment) => fragment != null && fragment !== "").join(" · ");
}
// ---------------------------------------------------------------------------
// Sorting (ui/screens/ListSort.kt)
// ---------------------------------------------------------------------------
/** The pipeline-list orderings offered by the sort control; Server order is the default. */
export const PIPELINE_SORTS = [
{ key: "server_order", label: "Server order" },
{ key: "name_asc", label: "Name A\u2013Z" },
{ key: "name_desc", label: "Name Z\u2013A" },
{ key: "recent_run", label: "Most recent run" },
{ key: "fewest_stages", label: "Fewest stages" },
{ key: "most_stages", label: "Most stages" },
];
/** Case-insensitive string comparison, matching String.CASE_INSENSITIVE_ORDER for ASCII. */
function compareInsensitive(a, b) {
const x = String(a ?? "").toUpperCase();
const y = String(b ?? "").toUpperCase();
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
/** Plain (case-sensitive) string comparison for the comparator's second key. */
function compareSensitive(a, b) {
const x = String(a ?? "");
const y = String(b ?? "");
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
/**
* The pure pipeline comparator for `sort`. Every case ends in an explicit
* tie-break (`id` is unique), so pipelines that compare equal on the primary
* key always order the same way rather than depending on the input order.
*
* `latestRuns` maps a pipeline id to that pipeline's most recent run (see
* [latestRunByPipeline]); only "Most recent run" uses it but it is passed in
* once so the fold is never repeated per comparison.
*/
export function pipelineComparator(sort, latestRuns = new Map()) {
const runFor = (pipeline) =>
latestRuns instanceof Map ? latestRuns.get(pipeline.id) : latestRuns[pipeline.id];
switch (sort) {
case "name_asc":
return (a, b) =>
compareInsensitive(a.name, b.name) ||
compareSensitive(a.name, b.name) ||
a.id - b.id;
case "name_desc":
return (a, b) =>
-compareInsensitive(a.name, b.name) ||
compareSensitive(a.name, b.name) ||
a.id - b.id;
case "recent_run":
return (a, b) => {
const ra = runFor(a);
const rb = runFor(b);
const noRunA = ra == null ? 1 : 0;
const noRunB = rb == null ? 1 : 0;
if (noRunA !== noRunB) return noRunA - noRunB;
const ta = ra ? parseInstant(ra.created_at) : null;
const tb = rb ? parseInstant(rb.created_at) : null;
const na = ta == null ? -Infinity : ta;
const nb = tb == null ? -Infinity : tb;
if (na !== nb) return na > nb ? -1 : 1;
const ia = ra ? ra.id : -Infinity;
const ib = rb ? rb.id : -Infinity;
if (ia !== ib) return ia > ib ? -1 : 1;
return a.id - b.id;
};
case "fewest_stages":
return (a, b) =>
(Number(a.stages) || 0) - (Number(b.stages) || 0) ||
compareInsensitive(a.name, b.name) ||
a.id - b.id;
case "most_stages":
return (a, b) =>
(Number(b.stages) || 0) - (Number(a.stages) || 0) ||
compareInsensitive(a.name, b.name) ||
a.id - b.id;
// Server order (and any unknown stored value): the identity comparator, so
// a stable sort preserves the server's own ordering exactly.
case "server_order":
default:
return () => 0;
}
}
/** Orders `pipelines` by `sort` without mutating the input, folding the run history once. */
export function sortPipelines(pipelines, sort, latestRuns = new Map()) {
return [...(pipelines ?? [])].sort(pipelineComparator(sort, latestRuns));
}
// ---------------------------------------------------------------------------
// Filtering (ui/screens/ListFilter.kt)
// ---------------------------------------------------------------------------
/**
* The statuses a filter can select: the server's own run vocabulary. The
* app-only `active` bucket, the stage-outcome words (`blocked`/`skipped`) and
* the `unknown` fallback are deliberately not offered, so a status filter
* always names a real run state.
*/
export const RUN_STATUS_FILTERS = [
"queued",
"running",
"waiting",
"succeeded",
"failed",
"canceled",
"interrupted",
];
/** The has/no-runs narrowing offered by the filter's Runs section. */
export const RUN_PRESENCES = [
{ key: "any", label: "Any" },
{ key: "has_runs", label: "Has runs" },
{ 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: "", scheduled: "any" };
/** Whether a run-history facet (presence or last-run status) is set. */
export function hasRunFacets(filters) {
return (filters?.presence ?? "any") !== "any" || (filters?.lastRunStatuses ?? []).length > 0;
}
/** True when the filters actually narrow anything. */
export function pipelineFiltersActive(filters) {
return hasRunFacets(filters) || String(filters?.name ?? "").trim() !== "" || ["scheduled", "unscheduled"].includes(filters?.scheduled);
}
/** The number of active facets, used for the control's badge. */
export function pipelineFilterCount(filters) {
return (
((filters?.presence ?? "any") !== "any" ? 1 : 0) +
((filters?.lastRunStatuses ?? []).length > 0 ? 1 : 0) +
(String(filters?.name ?? "").trim() !== "" ? 1 : 0) +
(["scheduled", "unscheduled"].includes(filters?.scheduled) ? 1 : 0)
);
}
/** True when `name` is blank, or when `pipelineName` contains it, ignoring case. */
export function pipelineMatchesName(name, pipelineName) {
const needle = String(name ?? "").trim();
return needle === "" || String(pipelineName ?? "").toLowerCase().includes(needle.toLowerCase());
}
/** True when `presence` is satisfied by whether the pipeline has a run. */
export function pipelineMatchesPresence(presence, hasRun) {
switch (presence) {
case "has_runs":
return hasRun;
case "no_runs":
return !hasRun;
case "any":
default:
return true;
}
}
/**
* True when `latestRun`'s status is in `statuses`; an empty set means "any
* status" and a pipeline with no run never matches a selected status, so the
* filter genuinely narrows.
*/
export function pipelineMatchesLastRunStatus(latestRun, statuses) {
const wanted = statuses ?? [];
if (wanted.length === 0) return true;
return latestRun != null && wanted.includes(runStateOf(latestRun.status));
}
/**
* Narrows `pipelines` by `filters`: the name narrowing and both run facets
* combined with AND. The name facet never depends on the run history, so it
* applies immediately; the run facets do, so while that history is still
* unknown (`runsKnown == false`) they are skipped rather than briefly hiding
* every pipeline.
*/
export function filterPipelines(pipelines, filters, latestRuns = new Map(), runsKnown = true) {
const all = pipelines ?? [];
if (!pipelineFiltersActive(filters)) return all;
const runFacets = hasRunFacets(filters);
const getRun = (pipeline) =>
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;
if (!pipelineMatchesLastRunStatus(latestRun, filters.lastRunStatuses)) return false;
}
return true;
});
}
/**
* The empty-state sentence for the pipeline list plus its optional reset action.
* Returns null when there is something to show. `Clear filters` is only offered
* when pipelines exist (nothing exists to reveal otherwise).
*/
export function pipelineListEmptyState(all, items, filters) {
if ((items ?? []).length > 0) return null;
const every = all ?? [];
if (every.length === 0) {
return { message: "No pipelines are defined on this server.", clearAction: null };
}
const name = String(filters?.name ?? "");
const message =
name.trim() !== "" && !hasRunFacets(filters) && !["scheduled", "unscheduled"].includes(filters?.scheduled)
? `No pipelines match "${name}".`
: "No pipelines match the current filters.";
return { message, clearAction: "Clear filters" };
}
// ---------------------------------------------------------------------------
// List row and detail text
// ---------------------------------------------------------------------------
/** The pipeline row's secondary line: `id {id} · v{version} · {N stages}`. */
export function pipelineSubtitle(pipeline) {
const stages = pipeline.stages ?? pipeline.graph?.stages?.length ?? 0;
return `id ${pipeline.id} · v${pipeline.version} · ${stageCountText(stages)}`;
}
/** The row's `updated …` line, or null when the timestamp is unparseable. */
export function pipelineUpdatedLine(pipeline) {
const formatted = formatLocalTimestamp(pipeline.updated_at);
return formatted ? `updated ${formatted}` : null;
}
/** The pipeline-detail tabs, Summary first (the version list lives inside it). */
export const PIPELINE_DETAIL_TABS = [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
{ key: "source", label: "Source" },
];
/**
* The Summary tab's key/value rows, in the app's order: Content hash
* (monospace), Latest version (`v{n}` or blank — never a dash), Version created,
* Pipeline created, Pipeline updated.
*/
export function summaryFields(detail) {
const latest = Number(detail?.latest_version) || 0;
return [
{ key: "Content hash", value: detail?.content_hash ?? "", monospace: true },
{ key: "Latest version", value: latest > 0 ? `v${latest}` : "" },
{ key: "Version created", value: formatLocalTimestamp(detail?.version_created_at) ?? "" },
{ key: "Pipeline created", value: formatLocalTimestamp(detail?.created_at) ?? "" },
{ key: "Pipeline updated", value: formatLocalTimestamp(detail?.updated_at) ?? "" },
];
}
/** One Version row: `v{n}` plus its stage count and (parseable) created time. */
export function versionRow(version) {
return {
versionLabel: `v${version?.version}`,
stagesText: stageCountText(version?.stages),
createdText: formatLocalTimestamp(version?.created_at),
};
}
/**
* The Graph tab's guidance note, adapted for a browser: mouse-wheel zoom and
* click replace the app's pinch and tap. The graph itself is the separate P6
* item.
*/
export const GRAPH_NOTE =
"Mouse wheel to zoom, drag to pan, click a stage for details. " +
"Edges are labelled with their outcome; error* is the implicit fallback.";
/** The guidance note string (a function so callers need no constant import). */
export function graphNote() {
return GRAPH_NOTE;
}
-176
View File
@@ -1,176 +0,0 @@
// Protocol command/type constants. Mirrors the subset of
// android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt and
// internal/protocol/*.go used by this spike, so renames cannot drift silently.
export const Protocol = Object.freeze({
PING: "ping",
PONG: "pong",
ERROR: "error",
LIST: "list_pipelines",
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",
VALIDATE: "validate",
VALIDATED: "validated",
// Publishing a new create-only draft from a source (internal/protocol/message.go
// Submit/Submitted; mirrors PipelinesRepository.createPipeline). The reply
// carries the new pipeline `detail`.
SUBMIT: "submit",
SUBMITTED: "submitted",
LIST_RUNS: "list_runs",
RUNS: "runs",
GET_RUN: "get_run",
REPAIR_SESSION_EXPORT: "repair_session_export",
RUN: "run",
// Live run state (internal/protocol/runevents.go, Message.kt; R10). `subscribe`
// scopes the watch to a workspace (the blank string means "any") and may carry
// explicit `run_ids`; `unsubscribe` drops the connection's watch; `run_event` is
// the server-pushed compact delta, which arrives without a matching request id
// and is therefore surfaced by client.js as a `frame` event. Both commands are
// send-only: the server may not ack `subscribe` and the Android client never
// awaits a reply.
SUBSCRIBE: "subscribe",
UNSUBSCRIBE: "unsubscribe",
RUN_EVENT: "run_event",
// Omni-search (internal/protocol/search.go): the command and its reply type.
// The per-kind payloads and the kind/limit vocabulary live in src/search.js.
SEARCH: "search",
SEARCH_RESULTS: "search_results",
// The run-level operator actions (R11–R14). Each replies with a `run` (or
// `run_started` for retry) envelope carrying the updated run detail; mirrors
// internal/protocol/runs.go and Message.kt.
RUN_PIPELINE: "run_pipeline",
CANCEL_RUN: "cancel_run",
RETRY_RUN: "retry_run",
DECIDE_RUN: "decide_run",
SET_RUN_TITLE: "set_run_title",
// Brokered OpenCode chat (C1/C3/C4), mirroring internal/protocol/chat.go and
// Message.kt. The session-scoped commands carry their body in `chat_query`;
// the list replies in `chat_sessions`, history in `chat_history` (an opaque
// `next_cursor` + `has_more`) and a close/reopen echoes the updated session in
// `chat_session` (with the `chat_close` outcome alongside).
CHAT_SESSIONS: "chat_sessions",
CHAT_MESSAGES: "chat_messages",
CHAT_CLOSE: "chat_close",
CHAT_REOPEN: "chat_reopen",
CHAT_STAR: "chat_star",
CHAT_RENAME: "chat_rename",
CHAT_BACKENDS: "chat_backends",
// Model selection for one chat. `chat_models` uses the usual `chat_query`
// session body and replies in `chat_models`; `chat_model` carries
// `{session_id,provider,model}` in `chat_model` and echoes it.
CHAT_MODELS: "chat_models",
CHAT_MODEL: "chat_model",
// The shared live stream (C5). `chat_subscribe` attaches this connection to one
// session's stream (body: the session id); the server then pushes `chat_event`
// frames without a matching request id, so every client watching a session sees
// the same turn. There is no `chat_unsubscribe` on the wire — the server
// detaches a subscription when the connection closes.
CHAT_SUBSCRIBE: "chat_subscribe",
CHAT_EVENT: "chat_event",
CHAT_ANSWER: "chat_answer",
// The composer's own commands (C8/C9). `chat_prompt` carries its body in
// `chat_prompt` (`{session_id,text,files?,operation_id}`) and its reply echoes
// `chat_queued` when the prompt waits behind an in-flight turn; `chat_interrupt`
// carries the same `chat_query` body as the other session-scoped commands; and
// `chat_create` carries `chat_create` and replies with `chat_session`.
CHAT_PROMPT: "chat_prompt",
CHAT_INTERRUPT: "chat_interrupt",
CHAT_CREATE: "chat_create",
// The create flow's directory choices (C2): `chat_directories` has no body and
// replies in the `chat_directories` field, home first then recent operator
// directories (internal/protocol/chat.go ChatDirectories).
CHAT_DIRECTORIES: "chat_directories",
// The approval card (C10): the server pushes `chat_permission` frames (one
// pending request, later re-pushed with the resolution) and the phone answers
// with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply).
CHAT_PERMISSION: "chat_permission",
CHAT_REPLY: "chat_reply",
// The background shells a chat session owns (C11). `chat_shells` lists the
// session's currently verified shells (body: `chat_query`); `chat_shell_output`
// reads a bounded, lazy output page from one of them (body:
// `chat_shell_output_query`). Mirrors internal/protocol/chat.go and Message.kt.
CHAT_SHELLS: "chat_shells",
CHAT_SHELL_OUTPUT: "chat_shell_output",
SUCCESS_END: "#success",
FAILURE_END: "#failure",
});
/**
* The envelope field names the chat commands read and write
* (internal/protocol/message.go). Kept beside the command constants so a rename
* in the Go envelope cannot drift silently.
*/
export const ChatKeys = Object.freeze({
SESSIONS: "chat_sessions",
SESSION: "chat_session",
QUERY: "chat_query",
HISTORY: "chat_history",
MESSAGES: "chat_messages",
CLOSE: "chat_close",
// `chat_subscribe` (the request body naming the session) and `chat_event` (the
// unsolicited pushed frame on the shared stream).
SUBSCRIBE: "chat_subscribe",
EVENT: "chat_event",
ANSWER: "chat_answer",
RENAME: "chat_rename",
BACKENDS: "chat_backends",
MODELS: "chat_models",
MODEL: "chat_model",
// The composer's payloads (C8/C9). `chat_interrupt` deliberately has no key of
// its own: its body is the same `chat_query` the other session-scoped commands
// carry (internal/protocol/chat.go ChatQuery, Chat.kt interruptRequest), so a
// separate field name here would put it on the wrong part of the envelope.
PROMPT: "chat_prompt",
CREATE: "chat_create",
// The `chat_directories` reply (C2), home first then recents; mirrors
// internal/protocol/message.go `ChatDirectories []string`.
DIRECTORIES: "chat_directories",
QUEUED: "chat_queued",
// C10: the pushed approval frame (`chat_permission`) and the answer body
// (`chat_reply`), both distinct Message fields in internal/protocol/message.go.
PERMISSION: "chat_permission",
REPLY: "chat_reply",
// The shell commands (C11, internal/protocol/message.go). `chat_shells` carries
// its body in `chat_query` (like the other session-scoped commands) and replies
// in `chat_shells`; `chat_shell_output` carries `chat_shell_output_query`
// ({session_id,shell_id,cursor,limit}) and replies in `chat_shell_output`.
SHELLS: "chat_shells",
SHELL_OUTPUT: "chat_shell_output",
SHELL_OUTPUT_QUERY: "chat_shell_output_query",
});
/**
* The integer wire protocol this page speaks. Mirrors `ProtocolVersion` in
* internal/protocol/identity.go and the value the Android client compares in
* `data/protocol/Message.kt` (the `protocol` field of the `pong` reply). It is
* compared as a number, never a string; a differing server value is surfaced as
* a warning rather than silently misread.
*/
export const PROTOCOL_VERSION = 1;
export function isTerminal(target) {
return target === Protocol.SUCCESS_END || target === Protocol.FAILURE_END;
}
/** Mirrors protocol.ResolveTarget: preserve the # shorthand as an explicit terminal. */
export function resolveTarget(outcome, target) {
if (target !== "#") return target;
return outcome === "error" ? Protocol.FAILURE_END : Protocol.SUCCESS_END;
}
-646
View File
@@ -1,646 +0,0 @@
// Typed access to the existing WebSocket protocol. Request builders and id
// matching live here so the app never constructs frames by hand or invents
// divergent field names. Mirrors android/.../data/PipelinesRepository.kt.
import { ChatKeys, Protocol } from "./protocol.js";
import { ProtocolError } from "./client.js";
import { DECISIONS } from "./chat.js";
/** The server default history page the app asks for (CHAT_HISTORY_LIMIT, 200). */
export const CHAT_HISTORY_LIMIT = 200;
/**
* The label this browser client records with a permission answer, so every other
* watching client can see which device resolved the request (the Android analogue
* is the device name). It is always sent; the server records it with the outcome.
*/
export const WEB_CHAT_CLIENT = "Web";
/**
* The largest shell-output page the server accepts (ChatShellOutputLimit,
* 64 KiB). The browser always reads from the page's start and never sends more
* than this, so a background task's output can never grow unbounded on the
* client.
*/
export const SHELL_OUTPUT_LIMIT = 64 << 10;
export class PipelinesRepository {
#client;
constructor(client) {
this.#client = client;
}
get connectionState() {
return this.#client.state;
}
connect(validated) {
this.#client.connect(validated);
}
disconnect() {
this.#client.disconnect();
}
ping() {
return this.#client.call({ type: Protocol.PING });
}
async listPipelines() {
return (await this.#client.call({ type: Protocol.LIST })).pipelines ?? [];
}
async getPipeline(id, version) {
const response = await this.#client.call({
type: Protocol.GET_PIPELINE,
pipeline_id: id,
version,
});
if (!response.detail) {
throw new ProtocolError("The server returned no pipeline detail.");
}
return response.detail;
}
async listTemplates() {
return (await this.#client.call({ type: Protocol.LIST_TEMPLATES })).templates ?? [];
}
async validate(source) {
const response = await this.#client.call({ type: Protocol.VALIDATE, source });
// A server error envelope already rejects inside client.call, so a reply
// here is `validated`; a missing graph is still an unusable definition.
if (!response.graph) {
throw new ProtocolError("The server returned no graph.");
}
return response.graph;
}
/**
* Creates a new pipeline from a definition `source` (the `submit` command),
* create-only, mirroring `PipelinesRepository.createPipeline`: the name must
* not already exist, so this can only ever add a draft and never overwrite a
* retained pipeline. A blank name is refused before anything is sent, exactly
* like the Android client; the sent name is trimmed. No run is started.
*/
async submit(name, source) {
if (!String(name ?? "").trim()) {
throw new ProtocolError("Enter a pipeline name.");
}
const response = await this.#client.call({
type: Protocol.SUBMIT,
name: String(name).trim(),
source,
create_only: true,
});
if (!response.detail) {
throw new ProtocolError("The server returned no pipeline detail.");
}
return response.detail;
}
async listRuns() {
const response = await this.#client.call({ type: Protocol.LIST_RUNS });
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,
run_id: id,
});
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
/** Export the exact recorded visit again; never invokes its model or tools. */
async repairSessionExport(id, sequence) {
if (!Number.isSafeInteger(id) || id<1 || !Number.isSafeInteger(sequence) || sequence<1) throw new ProtocolError("An exact run and visit are required.");
const response=await this.#client.call({type:Protocol.REPAIR_SESSION_EXPORT,run_id:id,export_sequence:sequence});
if (!response.run_detail) throw new ProtocolError("The server returned no run detail.");
return response.run_detail;
}
/**
* Asks the server to push this connection the live run state it displays
* (R10, also the source of L5's notifications). Send-only, mirroring
* `PipelinesRepository.subscribeRuns`: it returns the generated frame id and
* never waits for a reply, because the server may not acknowledge a
* `subscribe`. The body is exactly `{type:'subscribe', workspace}`; `run_ids`
* rides only when ids are given, so a blank workspace with no ids asks for the
* server-wide "any workspace" scope — the same `runIds.ifEmpty { null }` shape
* the Android client sends. The pushed state arrives as unsolicited
* `run_event` frames (client.js surfaces them as `frame` events).
*/
subscribeRuns(workspace = "", runIds = []) {
const request = { type: Protocol.SUBSCRIBE, workspace: String(workspace ?? "") };
if (Array.isArray(runIds) && runIds.length > 0) request.run_ids = runIds;
return this.#client.sendOnly(request);
}
/**
* Drops this connection's run-event watch (R10). Send-only like `subscribe`:
* the server may ack it, but nothing is awaited. It stops the pushes; a later
* `subscribe` re-reads the current state.
*/
unsubscribeRuns() {
return this.#client.sendOnly({ type: Protocol.UNSUBSCRIBE });
}
/**
* Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from
* internal/protocol/search.go: `kind` is the empty string for every kind, and
* `limit` is fixed at `0` so the server applies its own default cap
* (`SearchDefaultLimit`, 50) and never the client's — `SearchMaxLimit` (200) is
* therefore never approached, let alone exceeded.
*
* Returns `reply.search_results`, the ranked `SearchResponse`, or **null** when
* an older server answered without that payload (its default `pong`), which the
* caller reports as "this server does not support search" rather than dropping.
* An explicit server error is already surfaced by `client.call` as a
* `ProtocolError` carrying the server's own text.
*/
async search(query, kind = "") {
const response = await this.#client.call({
type: Protocol.SEARCH,
search: { query, kind, limit: 0 },
});
return response.search_results ?? null;
}
/**
* Answers a run's waiting human stage with the chosen `option` and optional
* `feedback` (mirrors PipelinesRepository.decideRun). The stage is sent only
* when non-blank and the feedback is trimmed, exactly like the Android client;
* a refused decision rejects with the server's own reason (a ProtocolError).
*/
async decideRun(id, { stage, option, feedback } = {}) {
const request = { type: Protocol.DECIDE_RUN, run_id: id, option };
if (stage != null && String(stage).trim() !== "") request.stage = stage;
const trimmedFeedback = String(feedback ?? "").trim();
if (trimmedFeedback !== "") request.feedback = trimmedFeedback;
const response = await this.#client.call(request);
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
/** Cancels a run; mirrors PipelinesRepository.cancelRun (exactly run_id). */
/**
* Starts a fresh run of one pipeline version. `notifyMode` is auto, on or off;
* auto omits the field so the pipeline definition applies.
*/
async runPipeline({ pipelineId, version, prompt, workspace, notifyMode = "auto", title = "", outputFormat = "", requestKey = newChatOperationId() } = {}) {
const request = {
type: Protocol.RUN_PIPELINE,
pipeline_id: Number(pipelineId),
version: Number(version),
request_key: requestKey,
workspace: String(workspace ?? "").trim(),
input: { prompt: String(prompt ?? "") },
};
if (String(title ?? "").trim() !== "") request.title = String(title).trim();
if (outputFormat) request.output_format = outputFormat;
const mode = String(notifyMode ?? "auto").trim().toLowerCase();
if (mode === "on" || mode === "off") request.notify_mode = mode;
const response = await this.#client.call(request);
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
/** Read-only admission reconciliation after a lost launch response. */
async runByRequestKey(requestKey) {
if (!String(requestKey ?? "").trim()) throw new ProtocolError("A launch request key is required.");
const response = await this.#client.call({ type: Protocol.GET_RUN, request_key: requestKey });
return response.run_detail ?? null;
}
async cancelRun(id) {
const response = await this.#client.call({ type: Protocol.CANCEL_RUN, run_id: id });
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
/**
* Retries a terminal failed run. `request_key` is always sent (the retry is
* its own idempotent run); `retry_mode` is sent only for an explicit
* `restart`, so the server's default (resume) applies exactly as the Android
* client's mode-less call.
*/
async retryRun(id, { mode = null, requestKey } = {}) {
const request = {
type: Protocol.RETRY_RUN,
run_id: id,
request_key: requestKey ?? "",
};
if (mode === "restart") request.retry_mode = "restart";
const response = await this.#client.call(request);
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
/** Renames a run's stored title; mirrors the set_run_title wire command. */
async setRunTitle(id, title) {
const response = await this.#client.call({
type: Protocol.SET_RUN_TITLE,
run_id: id,
title,
});
if (!response.run_detail) {
throw new ProtocolError("The server returned no run detail.");
}
return response.run_detail;
}
// ---- Brokered OpenCode chat (C1/C3/C4) -----------------------------------
// The browser never speaks OpenCode directly and never holds its credentials;
// it talks only to the Pipelines server. Mirrors PipelinesRepository.chat*.
/**
* Lists the sessions this server owns. The server already returns operator
* sessions only, so the app never filters the list by ownership.
*/
async chatSessions() {
return (await this.#client.call({ type: Protocol.CHAT_SESSIONS }))[ChatKeys.SESSIONS] ?? [];
}
/** The installed chat harnesses a new session can use. */
async chatBackends() {
return (await this.#client.call({ type: Protocol.CHAT_BACKENDS }))[ChatKeys.BACKENDS] ?? ["opencode"];
}
/** The models the session's harness offers for switching. */
async chatModels(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const response = await this.#client.call({
type: Protocol.CHAT_MODELS,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return response[ChatKeys.MODELS] ?? [];
}
/** Switch one session's model for subsequent turns. */
async switchChatModel(sessionId, provider, model) {
const session = String(sessionId ?? "").trim();
const providerId = String(provider ?? "").trim();
const modelId = String(model ?? "").trim();
if (session === "") throw new ProtocolError("Select a chat session first.");
if (providerId === "" || modelId === "") throw new ProtocolError("Choose a model first.");
const response = await this.#client.call({
type: Protocol.CHAT_MODEL,
[ChatKeys.MODEL]: { session_id: session, provider: providerId, model: modelId },
});
return response[ChatKeys.MODEL] ?? { session_id: session, provider: providerId, model: modelId };
}
/**
* Loads a bounded chronological history page. `cursor` is the opaque
* continuation the server returned as `next_cursor`; it is passed back
* verbatim and never interpreted. The reply is `chat_history`
* (`{messages,next_cursor,has_more}`); an older server that only knows
* `chat_messages` exposes no continuation, so the page is that list with
* `hasMore:false` and an empty cursor — exactly like
* PipelinesRepository.chatMessages.
*/
async chatHistory(sessionId, { limit = CHAT_HISTORY_LIMIT, cursor = "" } = {}) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const response = await this.#client.call({
type: Protocol.CHAT_MESSAGES,
[ChatKeys.QUERY]: { session_id: sessionId, limit, cursor },
});
const page = response[ChatKeys.HISTORY];
if (page) {
return {
messages: page.messages ?? [],
nextCursor: page.next_cursor ?? "",
hasMore: Boolean(page.has_more),
};
}
return { messages: response[ChatKeys.MESSAGES] ?? [], nextCursor: "", hasMore: false };
}
/**
* Attaches this connection to one session's shared live stream (C5). The body
* is exactly `{type:'chat_subscribe', chat_subscribe:{session_id}}` — the
* `chat_subscribe` field, not `chat_query` (internal/protocol/message.go); the
* server replies with an id-matched echo once the subscription is attached and
* then pushes `chat_event` frames without an id, which `client.js` surfaces as a
* `frame` event. Any number of clients may watch one session; the session is
* never read-only. There is no `chat_unsubscribe`: the server drops a
* subscription when the connection closes.
*/
async subscribeChat(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
return this.#client.call({
type: Protocol.CHAT_SUBSCRIBE,
[ChatKeys.SUBSCRIBE]: { session_id: sessionId },
});
}
/**
* Lists the currently verified shells this operator chat session owns (C11),
* so the conversation can show a background-tasks bar while one is running.
* The body is the session-scoped `chat_query` (like chat_messages); the reply
* is `chat_shells`, and an older server that returns none answers with an empty
* list. A blank session id is refused here, exactly like
* PipelinesRepository.chatShells.
*/
async chatShells(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const response = await this.#client.call({
type: Protocol.CHAT_SHELLS,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return response[ChatKeys.SHELLS] ?? [];
}
/**
* Reads one bounded output page from a verified shell (C11), mirroring
* PipelinesRepository.chatShellOutput. The body is exactly
* `chat_shell_output_query` — {session_id, shell_id, cursor, limit}, **not** the
* `chat_query` the other session commands use — with the cursor always sent so
* a refresh rereads from the page's start rather than appending. A blank
* session/shell, an out-of-bounds cursor/limit or a reply with no page is
* refused with the same reason the Android client uses.
*/
async chatShellOutput(sessionId, shellId, { cursor = 0, limit = SHELL_OUTPUT_LIMIT } = {}) {
if (!String(sessionId ?? "").trim() || !String(shellId ?? "").trim()) {
throw new ProtocolError("Select a shell first.");
}
if (!(cursor >= 0) || !(limit > 0) || limit > SHELL_OUTPUT_LIMIT) {
throw new ProtocolError("Shell output bounds are invalid.");
}
const response = await this.#client.call({
type: Protocol.CHAT_SHELL_OUTPUT,
[ChatKeys.SHELL_OUTPUT_QUERY]: {
session_id: sessionId,
shell_id: shellId,
cursor,
limit,
},
});
const page = response[ChatKeys.SHELL_OUTPUT];
if (!page) {
throw new ProtocolError("The server returned no shell output page.");
}
return page;
}
/**
* Finishes a session and records it closed on the server (nothing is
* deleted). The reply echoes the updated session (`chat_session`) and the
* close outcome (`chat_close`: the id, the close time and whether an
* in-flight turn was interrupted).
*/
async closeChat(sessionId) {
const response = await this.#client.call({
type: Protocol.CHAT_CLOSE,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null };
}
/**
* Records the shared star on the server (chat_star), so every browser and
* device lists the same Starred group. Returns the updated session row.
*/
async starChat(sessionId, starred) {
const response = await this.#client.call({
type: Protocol.CHAT_STAR,
[ChatKeys.QUERY]: { session_id: sessionId, starred: Boolean(starred) },
});
return response[ChatKeys.SESSION] ?? null;
}
/**
* Answers one OpenCode form (the question tool's form). Answers is keyed by
* the form field key; the server forwards it to the paused tool call and the
* resolved form arrives on the normal chat_event stream.
*/
async answerChatForm(sessionId, formId, answers, action = "") {
return this.#client.call({
type: Protocol.CHAT_ANSWER,
[ChatKeys.ANSWER]: { session_id: sessionId, form_id: formId, answers, ...(action ? {action} : {}) },
});
}
/**
* Records the shared chat title on the server (chat_rename), so every browser
* and device lists the same name. Returns the updated session row.
*/
async renameChat(sessionId, title) {
const response = await this.#client.call({
type: Protocol.CHAT_RENAME,
[ChatKeys.RENAME]: { session_id: sessionId, title: String(title ?? "").trim() },
});
return response[ChatKeys.SESSION] ?? null;
}
/** Clears the closed state again, so a finished chat can be resumed. */
async reopenChat(sessionId) {
const response = await this.#client.call({
type: Protocol.CHAT_REOPEN,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null };
}
// ---- The composer's own commands (C8/C9) ---------------------------------
// Mirrors PipelinesRepository.chatPrompt / chatInterrupt / chatCreate.
/**
* Sends one prompt with its attached file references (mirrors
* `PipelinesRepository.chatPrompt`): a blank session or blank text is refused
* here rather than sent, the text is trimmed, and `files` is **omitted** when
* empty (the shape a text-only prompt has always sent — the Android
* `ChatPromptRequest.Files` is `omitempty` too). `operation_id` is the durable
* idempotency key for this send. Returns true when the server queued the
* prompt behind an in-flight turn (`chat_queued` on the reply), which is the
* one signal the composer's queued notice is derived from.
*
* Browser attachments travel in `attachments` as {name,mime,data} with data
* encoded as standard base64. The server writes them to private temporary
* files and hands those file:// references to OpenCode; `files` remains the
* legacy reference-only field for older clients.
*/
async chatPrompt(sessionId, text, files = [], operationId = newChatOperationId(), attachments = []) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const trimmed = String(text ?? "").trim();
if (trimmed === "") {
throw new ProtocolError("Enter a message before sending.");
}
const body = {
session_id: sessionId,
text: trimmed,
operation_id: operationId,
native_message_id: nativeChatMessageId(operationId),
};
if (files.length > 0) body.files = files;
if (attachments.length > 0) body.attachments = attachments;
const response = await this.#client.call({ type: Protocol.CHAT_PROMPT, [ChatKeys.PROMPT]: body });
return Boolean(response[ChatKeys.QUEUED]);
}
/**
* Aborts the in-flight turn for a session (mirrors
* `PipelinesRepository.chatInterrupt`). The body is the session-scoped
* `chat_query`, exactly like the other session commands.
*/
async chatInterrupt(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
await this.#client.call({
type: Protocol.CHAT_INTERRUPT,
[ChatKeys.QUERY]: { session_id: sessionId },
});
}
/**
* Lists the directories a new chat can live in (C2), mirroring
* `PipelinesRepository.chatDirectories`: a bare `{type:'chat_directories'}` with
* no body, replying in `chat_directories` (home first, then recent operator
* directories). An older server that returns no field answers with an empty
* list; the view still offers home so the picker is never empty.
*/
async chatDirectories() {
const response = await this.#client.call({ type: Protocol.CHAT_DIRECTORIES });
return response[ChatKeys.DIRECTORIES] ?? [];
}
/**
* Creates one session in an explicit directory (mirrors
* `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is
* never created in whatever directory the server happens to be running in. The
* reply's `chat_session` is returned, or a `ProtocolError` when the server did
* not return one.
*
* `ephemeral` creates a verification chat: the server makes and bootstraps the
* session but records no operator-registry row, so the chat never appears in
* `chat_sessions` for the operator. Automated checks that drive this real page
* set it, so a run can never leave a stray "New chat" in the operator's list.
*/
async chatCreate(title, directory, operationId = newChatOperationId(), { backend = "opencode", ephemeral = false, instructions = "" } = {}) {
const response = await this.#client.call({
type: Protocol.CHAT_CREATE,
[ChatKeys.CREATE]: {
title,
directory,
operation_id: operationId,
...(backend && backend !== "opencode" ? { backend } : {}),
...(ephemeral ? { ephemeral: true } : {}),
...(String(instructions ?? "").trim() !== "" ? { instructions: String(instructions).trim() } : {}),
},
});
const session = response[ChatKeys.SESSION];
if (!session) {
throw new ProtocolError("The server did not return the new chat session.");
}
return session;
}
/**
* Answers one pending permission request (C10). Sends exactly
* `{type:'chat_reply', chat_reply:{session_id,request_id,decision,client}}` —
* `message` rides only when non-blank (mirrors ChatReplyRequest's omitempty).
* A blank session/request/decision, or a decision outside `once`/`always`/
* `reject`, is refused here before anything is sent, so an unaccepted decision
* can never reach the server. The server pushes the shared resolution back to
* every watching client once the first answer is recorded.
*/
async chatReply(sessionId, requestId, decision, { message = "", client = WEB_CHAT_CLIENT } = {}) {
const session = String(sessionId ?? "").trim();
const request = String(requestId ?? "").trim();
const chosen = String(decision ?? "").trim();
if (session === "") throw new ProtocolError("Select a chat session first.");
if (request === "") {
throw new ProtocolError("This approval request is no longer available.");
}
if (!DECISIONS.includes(chosen)) {
throw new ProtocolError("Choose once, always or reject.");
}
const body = {
session_id: session,
request_id: request,
decision: chosen,
client: String(client ?? "").trim() || WEB_CHAT_CLIENT,
};
const trimmed = String(message ?? "").trim();
if (trimmed !== "") body.message = trimmed;
await this.#client.call({ type: Protocol.CHAT_REPLY, [ChatKeys.REPLY]: body });
}
}
/**
* A durable operation id for one chat request intent, retaining the shape of the
* Android `newRequestKey`/`newChatCreateOperationId` (a client-prefixed opaque
* key). One create/send keeps its id across a retry so the server can dedupe it.
*/
export function newChatOperationId() {
const random = Math.random().toString(36).slice(2, 10);
return `web-chat-${Date.now().toString(36)}-${random}`;
}
/**
* The OpenCode message identity carried with a prompt, mirroring the Android
* `nativeMessageId`: the operation id's alphanumerics, prefixed `msg_` and capped
* at 120 characters. OpenCode persists it in history, so the live user echo and
* an authoritative history page can be reconciled; a blank operation id yields an
* empty id (the server then supplies its own).
*/
export function nativeChatMessageId(operationId) {
const compact = String(operationId ?? "")
.replace(/[^A-Za-z0-9]/g, "")
.slice(0, 120);
return compact === "" ? "" : `msg_${compact}`;
}
-295
View File
@@ -1,295 +0,0 @@
// The page's URL route model (L6). Pure and DOM-free: the parser is total (a
// malformed or unknown location resolves to the default Pipelines list), and the
// serialiser is its inverse for every route the page can produce.
//
// The Android app's `pipelines://run/<id>` deep link becomes a real page route,
// and every destination the app has becomes a URL:
//
// /pipelines Pipelines list
// /pipelines/:id pipeline detail, latest version
// /pipelines/:id/:version pipeline detail at a version (0 = latest)
// /pipelines/:id[/:version]/stage/:key the definition pane's stage
// /runs Runs list
// /runs/:id run detail (optional ?action=decide)
// /runs/:id/stage/:key[?visit=N] one visit's stage pane
// /chat Chat list
// /chat/:id one chat session
// /templates template gallery
// /templates/:key template detail
// /settings Settings
// /settings/templates[/:key] aliases for the two template routes
//
// Where a section sits inside a detail (Summary/Graph/Source, run tabs) is
// in-place state, not a route: only the two stage panes are deep-linkable. Search
// is query state owned by the search panel and is never part of a route; unknown
// query parameters are ignored. `/templates` and `/templates/:key` are the
// canonical forms the serialiser emits; the `/settings/...` aliases still parse
// and round-trip to the same route.
/** The destination an unknown or malformed location opens. */
export const DEFAULT_ROUTE = Object.freeze({ kind: "pipelines" });
const ID_PATTERN = /^[0-9]+$/;
/** Decode one path segment, or null when the percent escapes are malformed. */
function decodeSegment(segment) {
try {
return decodeURIComponent(segment);
} catch {
return null;
}
}
/** A positive safe integer id, or null. Mirrors runLinkFromDeepLink's id > 0. */
function parseId(value) {
if (!ID_PATTERN.test(value)) return null;
const id = Number(value);
return Number.isSafeInteger(id) && id > 0 ? id : null;
}
/** A non-negative safe integer (a pipeline version; 0 means latest), or null. */
/** A chat session id segment: nonempty, bounded, URL-safe. */
function parseChatId(value) {
const id = String(value ?? "");
return id !== "" && id.length <= 200 && /^[A-Za-z0-9_-]+$/.test(id) ? id : null;
}
function parseVersion(value) {
if (!ID_PATTERN.test(value)) return null;
const version = Number(value);
return Number.isSafeInteger(version) ? version : null;
}
/** The `action` query value verbatim, or null; only `decide` has an effect. */
function parseAction(params) {
if (!params) return null;
const action = params.get("action");
return action != null && action !== "" ? action : null;
}
/**
* The zero-based visit index from `?visit=`, or null. A negative, non-integer or
* absent value drops the query while keeping the stage route, exactly as the
* Android extra is optional.
*/
function parseVisit(params) {
if (!params) return null;
const raw = params.get("visit");
if (raw == null || raw === "") return null;
return parseVersion(raw);
}
function parseParams(search) {
if (!search) return null;
const text = String(search).replace(/^\?/, "");
if (!text) return null;
try {
return new URLSearchParams(text);
} catch {
return null;
}
}
/**
* Parse a location-style pathname (and optional search) into a route. Total:
* anything unrecognised — an unknown path, a malformed percent escape, a zero or
* negative run id, a non-numeric version — returns DEFAULT_ROUTE and never
* throws. Unknown query parameters are ignored; `visit` is dropped when invalid.
*/
export function parseRoute(pathname, search = "") {
let raw = pathname == null ? "" : String(pathname);
let query = search == null ? "" : String(search);
// A full URL is accepted too (the smoke and a pasted link use one); its own
// path and query stand in for the arguments.
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
try {
const url = new URL(raw);
if (!query) query = url.search;
raw = url.pathname;
} catch {
return DEFAULT_ROUTE;
}
}
const hash = raw.indexOf("#");
if (hash !== -1) raw = raw.slice(0, hash);
const mark = raw.indexOf("?");
if (mark !== -1) {
if (!query) query = raw.slice(mark);
raw = raw.slice(0, mark);
}
if (!query && typeof search === "string") query = search;
// Normalise trailing slashes: `/runs/` is `/runs`.
const trimmed = raw.replace(/\/+$/, "");
const segments = trimmed.split("/").filter((segment, index) => index > 0 || segment !== "");
if (trimmed === "" || trimmed === "/") return { ...DEFAULT_ROUTE };
const decoded = [];
for (const segment of segments) {
const value = decodeSegment(segment);
if (value == null || value === "") return { ...DEFAULT_ROUTE };
decoded.push(value);
}
const params = parseParams(query);
const [head, second, third, fourth, fifth, ...rest] = decoded;
if (rest.length) return { ...DEFAULT_ROUTE };
if (head === "pipelines" && second == null) return { kind: "pipelines" };
if (head === "runs" && second == null) {
const pipelineId = parseId(params?.get("pipeline") ?? "");
return pipelineId == null ? { kind: "runs" } : { kind: "runs", pipelineId };
}
if (head === "chat") {
if (second == null) return { kind: "chat" };
if (third == null) {
const id = parseChatId(second);
return id == null ? { ...DEFAULT_ROUTE } : { kind: "chatSession", id };
}
return { ...DEFAULT_ROUTE };
}
if (head === "settings" && second == null) return { kind: "settings" };
if (head === "templates") {
if (second == null) return { kind: "templates" };
if (third == null) return { kind: "template", key: second };
return { ...DEFAULT_ROUTE };
}
if (head === "settings" && second === "templates") {
if (third == null) return { kind: "templates" };
if (fourth == null) return { kind: "template", key: third };
return { ...DEFAULT_ROUTE };
}
if (head === "pipelines") {
const id = parseId(second);
if (id == null) return { ...DEFAULT_ROUTE };
if (third == null) return { kind: "pipeline", id, version: 0 };
if (third === "stage" && fourth != null && fifth == null) {
return { kind: "pipelineStage", id, version: 0, stageKey: fourth };
}
const version = parseVersion(third);
if (version == null) return { ...DEFAULT_ROUTE };
if (fourth == null) return { kind: "pipeline", id, version };
if (fourth === "stage" && fifth != null) {
return { kind: "pipelineStage", id, version, stageKey: fifth };
}
return { ...DEFAULT_ROUTE };
}
if (head === "runs") {
const id = parseId(second);
if (id == null) return { ...DEFAULT_ROUTE };
if (third == null) {
const action = parseAction(params);
return action == null ? { kind: "run", id } : { kind: "run", id, action };
}
if (third === "stage" && fourth != null && fifth == null) {
const visit = parseVisit(params);
return visit == null
? { kind: "runStage", id, stageKey: fourth }
: { kind: "runStage", id, stageKey: fourth, visit };
}
return { ...DEFAULT_ROUTE };
}
return { ...DEFAULT_ROUTE };
}
function encode(value) {
return encodeURIComponent(String(value));
}
/**
* An id the parser will accept back (a positive safe integer), or null. A
* numeric string is accepted like the parser's own digit-only form.
*/
function serialId(value) {
if (typeof value === "number") {
return Number.isSafeInteger(value) && value > 0 ? value : null;
}
if (typeof value === "string" && ID_PATTERN.test(value)) {
const id = Number(value);
return Number.isSafeInteger(id) && id > 0 ? id : null;
}
return null;
}
/**
* A version the parser will accept back (a non-negative safe integer), or null
* when the value cannot describe one; the caller then emits the latest form so
* the URL still parses to a canonical route.
*/
function serialVersion(value) {
if (value == null) return 0;
if (typeof value === "number") {
return Number.isSafeInteger(value) && value >= 0 ? value : null;
}
if (typeof value === "string" && ID_PATTERN.test(value)) {
const version = Number(value);
return Number.isSafeInteger(version) ? version : null;
}
return null;
}
/**
* Serialise a route to a path + query. Total: an unrecognised object serialises
* to the default Pipelines route rather than throwing. Version 0/absent is
* omitted (it means latest), an absent visit is omitted, and `action` is emitted
* only when present.
*/
export function serializeRoute(route) {
const r = route ?? DEFAULT_ROUTE;
switch (r.kind) {
case "pipelines":
return "/pipelines";
case "runs":
return parseId(String(r.pipelineId ?? "")) == null ? "/runs" : `/runs?pipeline=${r.pipelineId}`;
case "chat":
return "/chat";
case "chatSession": {
const id = parseChatId(r.id);
return id == null ? "/chat" : `/chat/${encode(id)}`;
}
case "settings":
return "/settings";
case "templates":
return "/templates";
case "template":
return typeof r.key === "string" && r.key ? `/templates/${encode(r.key)}` : "/templates";
case "pipeline": {
const id = serialId(r.id);
if (id == null) return "/pipelines";
const version = serialVersion(r.version) ?? 0;
return version > 0 ? `/pipelines/${id}/${version}` : `/pipelines/${id}`;
}
case "pipelineStage": {
const id = serialId(r.id);
if (id == null || typeof r.stageKey !== "string" || !r.stageKey) return "/pipelines";
const version = serialVersion(r.version) ?? 0;
const base = version > 0 ? `/pipelines/${id}/${version}` : `/pipelines/${id}`;
return `${base}/stage/${encode(r.stageKey)}`;
}
case "run": {
const id = serialId(r.id);
if (id == null) return "/runs";
const base = `/runs/${id}`;
return r.action ? `${base}?${new URLSearchParams({ action: r.action }).toString()}` : base;
}
case "runStage": {
const id = serialId(r.id);
if (id == null || typeof r.stageKey !== "string" || !r.stageKey) return "/runs";
const base = `/runs/${id}/stage/${encode(r.stageKey)}`;
// A valid visit is a non-negative integer; anything else is omitted.
const visit = Number.isSafeInteger(r.visit) && r.visit >= 0 ? r.visit : null;
return visit == null ? base : `${base}?visit=${visit}`;
}
default:
return "/pipelines";
}
}
/** Two routes are the same when their canonical serialisations agree. */
export function sameRoute(a, b) {
return serializeRoute(a) === serializeRoute(b);
}
-904
View File
@@ -1,904 +0,0 @@
// Pure, DOM-free logic for the run-detail tabs and the stage pane, ported from
// the Android client so the browser says and shows exactly the same things:
// ui/screens/RunDetailScreen.kt the tab set (RUN_DETAIL_TABS)
// ui/screens/RunSummaryTab.kt the summary rows and identity line
// ui/screens/RunFieldSectionsTab.kt input/output field sections
// ui/screens/Timeline.kt runTimeline, timelineDescription, hasArtifacts
// ui/graph/StageDetailPane.kt runStepFields, headline/evidence split,
// stageSectionSpecs, stageDefinitionFields,
// controlVisitLabel, clampVisitIndex
// ui/graph/StageVerdict.kt verdictReasonSegments, referencedVerdictArtifacts
// ui/Format.kt displayText/displayMap, fileChangeLine,
// notificationLine, fileChangesSummary
// data/protocol/GraphSemantics.kt nodeLabel, outcome ordering, edge labels
// ui/graph/GraphPalette.kt the curated graph-only outcome palette
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// wording, ordering, counting and formatting can be unit-tested without a
// browser. The tab/pane wiring lives in app.js. Every server-provided string is
// only ever compared or rendered, never parsed as markup; the caller sets it
// with textContent.
import {
runIdentity,
visitCount,
formatDuration,
durationSeconds,
secondsSince,
formatLocalTimestamp,
runStateOf,
} from "./runs.js";
import { presentedArtifacts, sessionExportArtifact, stageArtifacts, visitArtifacts, displayVisit } from "./artifacts.js";
import { changeStat, parseUnifiedPatch, runChanges, runChangesHeader } from "./changes.js";
import { effectiveStageType } from "./templates.js";
// ---------------------------------------------------------------------------
// Tabs
// ---------------------------------------------------------------------------
/**
* The run-detail tabs, Summary first so it is the default selection. The Graph
* tab sits between Summary and Input (R5) and mounts the shared workflow graph
* in run mode. The timeline keeps Android's stable key `steps` with the visible
* title `Timeline`.
*/
export const RUN_DETAIL_TABS = [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
{ key: "input", label: "Input" },
{ key: "output", label: "Output" },
{ key: "steps", label: "Timeline" },
];
/**
* The tabs the browser renders. Input and Output are run Summary sections now
* (alongside Artifacts and Files changed), not separate tabs; the stable keys
* `input`/`output` remain in RUN_DETAIL_TABS for Android parity and old routes.
*/
export const RENDERED_RUN_TABS = [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
{ key: "steps", label: "Timeline" },
];
// The empty-state sentences, exactly as the app spells them.
export const EMPTY_INPUT_MESSAGE = "No input recorded.";
export const EMPTY_OUTPUT_MESSAGE = "No output recorded.";
export const EMPTY_TIMELINE_MESSAGE = "No visits recorded.";
export const NO_STAGE_DETAILS_MESSAGE = "No details recorded for this node.";
/** The original run prompt, without display formatting or a fallback source. */
export function originalRunPrompt(run) {
return typeof run?.input?.prompt === "string" ? run.input.prompt : undefined;
}
/** The stage-pane section titles (Android StageDetailPane constants). */
export const STAGE_ARTIFACTS_TITLE = "Artifacts";
export const STAGE_SESSION_TITLE = "Session";
export const STAGE_EVIDENCE_TITLE = "This run";
export const STAGE_DEFINITION_TITLE = "Stage definition";
// ---------------------------------------------------------------------------
// Field display (ui/Format.kt displayText / displayMap)
// ---------------------------------------------------------------------------
/**
* Compact rendering of an arbitrary JSON value for read-only display: a
* primitive verbatim, an array `, `-joined, an object `k=v` `, `-joined.
* Mirrors Format.kt JsonElement.displayText (a JSON null reads `null`).
*/
export function displayText(value) {
if (Array.isArray(value)) return value.map((item) => displayText(item)).join(", ");
if (value !== null && typeof value === "object") {
return Object.entries(value)
.map(([key, item]) => `${key}=${displayText(item)}`)
.join(", ");
}
if (value === undefined) return "null";
return String(value);
}
/**
* A field map rendered one `key: value` line per entry, in insertion order.
* Mirrors Format.kt Map<String, JsonElement>?.displayMap (a null/empty map is
* the empty string).
*/
export function displayMap(map) {
if (!map) return "";
return Object.entries(map)
.map(([key, value]) => `${key}: ${displayText(value)}`)
.join("\n");
}
/**
* The input/output tab's sections, one per map entry in insertion order: the
* entry's own key as the title (falling back to the section prefix so it is
* never empty) and the value's display text. Mirrors
* RunFieldSectionsTab.fieldSectionTitle + displayText.
*/
export function fieldSections(map, keyPrefix) {
if (!map) return [];
return Object.entries(map).map(([key, value]) => ({
key,
title: fieldSectionTitle(key, keyPrefix),
value: displayText(value),
}));
}
/** A field section's title: the field's own name, else the section prefix. */
export function fieldSectionTitle(key, keyPrefix) {
const text = String(key ?? "");
return text.trim() === "" ? keyPrefix : text;
}
// ---------------------------------------------------------------------------
// Run summary (ui/screens/RunSummaryTab.kt)
// ---------------------------------------------------------------------------
/**
* The summary rows in Android order: Pipeline `id {id} · v{version}`, Stage, the
* resource-wait line only when `resource_wait` is set, Workspace, Content hash
* (monospace), Started, Finished, the live-aware Duration, `Retry of run {n}`
* when set, and the Diagnostic block. Blank values are omitted so no empty row
* is ever drawn. Each entry is tagged with a `kind` so the renderer can style
* and (for `duration`) live-update it.
*/
export function summaryRows(run, nowMillis, options = {}) {
if (!run) return [];
const rows = [];
const kv = (key, value, monospace = false) => {
const text = String(value ?? "");
if (text.trim() === "") return;
rows.push({ kind: "kv", key, value: text, monospace });
};
if (Number(run.pipeline_id) > 0) {
rows.push({
kind: "pipeline",
key: "Pipeline",
value: `id ${run.pipeline_id} · v${run.version ?? 0}`,
pipelineId: Number(run.pipeline_id),
pipelineName: String(run.name ?? ""),
version: Number(run.version) || 0,
});
} else {
kv("Pipeline", `id ${run.pipeline_id ?? 0} · v${run.version ?? 0}`);
}
kv("Stage", run.current_stage);
const wait = resourceWaitLine(run);
if (wait) rows.push({ kind: "wait", value: wait });
kv("Workspace", run.workspace);
kv("Content hash", run.content_hash, true);
kv("Started", formatLocalTimestamp(run.created_at, options));
kv("Finished", formatLocalTimestamp(run.finished_at, options));
const duration = runDurationText(run, nowMillis);
if (duration != null) rows.push({ kind: "duration", key: "Duration", value: duration });
if (Number(run.retry_of) > 0) kv("Retry of", `run ${run.retry_of}`);
if (String(run.diagnostic ?? "").trim() !== "") {
rows.push({ kind: "block", key: "Diagnostic", value: String(run.diagnostic) });
}
return rows;
}
/**
* The resource-wait line, `Waiting for resource {name}`, only when the run is
* waiting on a resource. Mirrors RunSummaryTab's `run.resourceWait?.let { ... }`
* and ResourceWait.statusLabel.
*/
export function resourceWaitLine(run) {
if (!run || run.resource_wait == null) return "";
return `Waiting for resource ${String(run.resource_wait.resource ?? "")}`;
}
/**
* The run's identity line: `run {id} · {recorded visits} · {completed visits}`,
* the same recorded/completed vocabulary the runs list and the server use.
* Mirrors RunSummaryTab's buildString.
*/
export function runIdentityLine(run) {
if (!run) return "";
const recorded = visitCount((run.steps ?? []).length, "recorded");
const completed = visitCount(Number(run.completed_steps) || 0, "completed");
return `run ${run.id} · ${recorded} · ${completed}`;
}
/**
* The run's primary label (stored title, else the pipeline name), from the one
* runIdentity helper the runs list also uses so the two never disagree.
*/
export function runLabelFor(run) {
return runIdentity(run?.title, run?.name).label;
}
/**
* The summary's Duration value: live elapsed while executing, else the stored
* total. Mirrors Format.kt runDurationText (null when unavailable, so the caller
* omits the row).
*/
export function runDurationText(run, nowMillis) {
if (!run) return null;
if (run.executing) {
const elapsed = secondsSince(run.created_at, nowMillis);
return elapsed == null ? null : formatDuration(elapsed);
}
const total = durationSeconds(run.created_at, run.finished_at);
return total == null ? null : formatDuration(total);
}
// ---------------------------------------------------------------------------
// Timeline (ui/screens/Timeline.kt)
// ---------------------------------------------------------------------------
/**
* The run's timeline plus each stage's ordered visits, derived in one pass.
* Stages keep first-appearance order; a stage's visits are ordered by sequence.
* One entry per recorded visit, in step order, with the display visit number,
* the outcome chip label (`outcome` else `status`), whether the visit recorded
* artifacts, its duration and its one-line description. Pure and total over an
* empty list and blank control/outcome fields. Mirrors `runTimeline`.
*/
export function runTimeline(steps) {
const list = steps ?? [];
if (list.length === 0) return { entries: [], visitsByStage: new Map() };
const visitsByStage = new Map();
for (const step of list) {
const stage = step?.stage ?? "";
if (!visitsByStage.has(stage)) visitsByStage.set(stage, []);
visitsByStage.get(stage).push(step);
}
const indexByStageSequence = new Map();
for (const [stage, visits] of visitsByStage) {
[...visits]
.sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0))
.forEach((visit, index) => indexByStageSequence.set(`${stage}\u0000${visit?.sequence ?? 0}`, index));
}
const entries = list.map((step) => {
const index = indexByStageSequence.get(`${step?.stage ?? ""}\u0000${step?.sequence ?? 0}`) ?? 0;
return {
step,
stageKey: step?.stage ?? "",
visit: displayVisit(step, index),
visitIndex: index,
outcomeLabel: String(step?.outcome ?? "").trim() !== "" ? String(step.outcome) : String(step?.status ?? ""),
hasArtifacts: hasArtifacts(step),
duration: stepDuration(step),
description: timelineDescription(step),
};
});
const orderedVisits = new Map();
for (const [stage, visits] of visitsByStage) {
orderedVisits.set(
stage,
[...visits].sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0)),
);
}
return { entries, visitsByStage: orderedVisits };
}
/**
* The brief one-line description after a visit's name: the first non-blank
* diagnostic line, else the resolved target, else nothing (never fabricated).
*/
export function timelineDescription(step) {
const diagnostic = String(step?.diagnostic ?? "");
const line = diagnostic.split(/\r?\n/).find((candidate) => candidate.trim() !== "");
if (line != null) return line.trim();
const target = String(step?.target ?? "");
if (target.trim() !== "") return `→ ${nodeLabel(target)}`;
return "";
}
/**
* Whether a visit recorded any presented artifact. The retired session markdown
* is not presented, so it never counts. Composes the one presentedArtifacts
* filter so the timeline and the pane never disagree.
*/
export function hasArtifacts(step) {
return presentedArtifacts(step).length > 0;
}
/** Human duration between a step's timestamps, or null when unavailable. */
export function stepDuration(step) {
const seconds = durationSeconds(step?.started_at, step?.finished_at);
return seconds == null ? null : formatDuration(seconds);
}
// ---------------------------------------------------------------------------
// Graph semantics (data/protocol/GraphSemantics.kt, Message.kt)
// ---------------------------------------------------------------------------
export const SUCCESS_END = "#success";
export const FAILURE_END = "#failure";
/** A node label: the success/failure terminal shorthand, else the key itself. */
export function nodeLabel(key) {
if (key === SUCCESS_END) return "SUCCESS";
if (key === FAILURE_END) return "FAILURE";
return String(key ?? "");
}
/** Whether a resolved target is an explicit terminal. */
export function isTerminal(target) {
return target === SUCCESS_END || target === FAILURE_END;
}
/** Mirrors Protocol.resolveTarget: preserve `#` as the outcome's terminal. */
export function resolveTarget(outcome, target) {
if (target !== "#") return target;
return outcome === "error" ? FAILURE_END : SUCCESS_END;
}
/** A stage's outcomes (edge keys) in the app's order: success, others, error. */
export function stageOutcomes(stage) {
return Object.keys(stage?.edges ?? {}).sort((a, b) => {
const pa = a === "success" ? 0 : a === "error" ? 2 : 1;
const pb = b === "success" ? 0 : b === "error" ? 2 : 1;
return pa - pb || (a < b ? -1 : a > b ? 1 : 0);
});
}
/** Every definition edge in stable order. Mirrors Graph.edges(). */
export function graphEdges(graph) {
const result = [];
for (const stage of graph?.stages ?? []) {
for (const outcome of stageOutcomes(stage)) {
const target = resolveTarget(outcome, stage.edges[outcome]);
result.push({
source: stage.key,
outcome,
target,
label: outcome === "error" && stage.fallback_error ? "error*" : outcome,
});
}
}
return result;
}
/**
* Which stages and routes a run actually recorded, for the graph's execution
* highlighting. Mirrors Android `RunGraphState.from` (GraphSemantics.kt:91-116):
* every step's stage key is a visited stage (insertion order), a step with a
* non-blank outcome and target contributes a taken route
* `{source, outcome, resolvedTarget}` (recorded as a `source\0outcome\0target`
* key the graph matches) and, when that resolved target is a terminal, marks the
* terminal visited too. `currentStage` is the run's own stage, else the last
* visit's stage, else null; `executing` mirrors the run; `currentStageStartedAt`
* is the running visit's start for the active stage, only while executing. Pure
* and DOM-free so the renderer and the tests share one definition.
*/
export function runGraphState(run) {
const visitedStages = [];
const seenStages = new Set();
const takenRoutes = [];
const seenRoutes = new Set();
const steps = run?.steps ?? [];
const visit = (key) => {
if (key == null || seenStages.has(key)) return;
seenStages.add(key);
visitedStages.push(key);
};
for (const step of steps) {
visit(step?.stage);
const outcome = String(step?.outcome ?? "");
const target = String(step?.target ?? "");
if (target.trim() !== "" && outcome.trim() !== "") {
const resolved = resolveTarget(outcome, target);
const route = `${step?.stage}\u0000${outcome}\u0000${resolved}`;
if (!seenRoutes.has(route)) {
seenRoutes.add(route);
takenRoutes.push(route);
}
if (isTerminal(resolved)) visit(resolved);
}
}
const lastStage = steps.length > 0 ? steps[steps.length - 1]?.stage : "";
const rawCurrent = String(run?.current_stage ?? "").trim() !== "" ? run.current_stage : lastStage;
const currentStage = String(rawCurrent ?? "").trim() !== "" ? String(rawCurrent) : null;
const executing = Boolean(run?.executing);
let currentStageStartedAt = null;
if (executing && currentStage != null) {
for (let index = steps.length - 1; index >= 0; index -= 1) {
const step = steps[index];
if (step?.stage === currentStage && step?.status === "running") {
const started = String(step?.started_at ?? "");
if (started.trim() !== "") currentStageStartedAt = started;
break;
}
}
}
return { visitedStages, takenRoutes, currentStage, executing, currentStageStartedAt };
}
// ---------------------------------------------------------------------------
// Stage pane (ui/graph/StageDetailPane.kt)
// ---------------------------------------------------------------------------
/** One labelled row/block of stage detail, rendered by the pane. */
function field(label, value, mono = false, block = false) {
return { label, value, mono, block };
}
/**
* The always-visible run-side identity/result labels of a step. The item's
* headline list adds `Session` beside the app's six, so a visit that recorded a
* session id shows it up top with the rest of its result facts.
*/
export const STAGE_HEADLINE_LABELS = new Set([
"Status",
"Outcome",
"Target",
"Duration",
"Visit",
"Model target",
"Session",
]);
/** The always-visible run-side identity/result fields of a step's evidence. */
export function headlineFields(fields) {
return (fields ?? []).filter((entry) => STAGE_HEADLINE_LABELS.has(entry.label));
}
/**
* The remaining run evidence (diagnostic, transcript, agent, file changes,
* notifications) that belongs in the collapsible "This run" section: the
* headline facts and the input/output result blocks are surfaced elsewhere.
*/
export function evidenceFields(fields) {
return (fields ?? []).filter(
(entry) =>
!STAGE_HEADLINE_LABELS.has(entry.label) && entry.label !== "Input" && entry.label !== "Output",
);
}
/**
* The pure run view of one step: status, outcome, duration, visit against the
* control's max visits, target, session id, agent flag, diagnostic, transcript,
* the step's input/output, a file-change summary, changed files and notification
* receipts. Blank fields are skipped, so no empty row is ever emitted. Mirrors
* `runStepFields`.
*/
/** What an empty turn body reads as, matching input.md's own marker. */
const NO_TURN_OUTPUT = "_(no output)_";
/**
* A turn's value map carries the whole markdown body under the single key
* `markdown`. Returns that body so the pane can render it as the document it is;
* null means an ordinary map that still needs its keys shown.
*/
function turnBody(map) {
if (!map || typeof map !== "object") return null;
const keys = Object.keys(map);
if (keys.length !== 1 || keys[0] !== "markdown" || typeof map.markdown !== "string") return null;
return map.markdown;
}
export function runStepFields(step) {
const fields = [];
if (step == null) return fields;
if (str(step.status).trim() !== "") fields.push(field("Status", str(step.status)));
if (str(step.outcome).trim() !== "") fields.push(field("Outcome", str(step.outcome)));
const duration = stepDuration(step);
if (duration != null) fields.push(field("Duration", duration));
const control = step.control;
if (control) {
if (Number(control.max_visits) > 0 || Number(control.visit) > 0) {
fields.push(field("Visit", controlVisitLabel(control)));
}
const modelTarget = str(control.model_target);
if (modelTarget.trim() !== "") fields.push(field("Model target", modelTarget));
}
if (str(step.target).trim() !== "") fields.push(field("Target", str(step.target)));
if (str(step.session_id).trim() !== "") fields.push(field("Session", str(step.session_id), true));
if (step.agent_active) fields.push(field("Agent", "active"));
if (str(step.diagnostic).trim() !== "") fields.push(field("Diagnostic", str(step.diagnostic), false, true));
if (str(step.transcript).trim() !== "") fields.push(field("Transcript", str(step.transcript), false, true));
if (step.input && Object.keys(step.input).length > 0) {
const body = turnBody(step.input);
fields.push(
body == null
? field("Input", displayMap(step.input), false, true)
: field("Input", body.trim() === "" ? NO_TURN_OUTPUT : body, false, true),
);
}
if (step.output && Object.keys(step.output).length > 0) {
const body = turnBody(step.output);
fields.push(
body == null
? field("Output", displayMap(step.output), false, true)
: field("Output", body.trim() === "" ? NO_TURN_OUTPUT : body, false, true),
);
}
const changes = step.file_changes;
if (changes) {
const summary = fileChangesSummary(changes);
if (summary.trim() !== "") fields.push(field("File changes", summary));
const files = changes.files ?? [];
if (files.length > 0) {
fields.push(field("Changed files", files.map((file) => fileChangeLine(file)).join("\n"), false, true));
}
}
for (const receipt of step.notifications ?? []) {
if (str(receipt?.status).trim() !== "" || str(receipt?.destination).trim() !== "") {
fields.push(field("Notification", notificationLine(receipt)));
}
}
return fields;
}
/**
* The stage definition view: key + type title, prompt, output, edges with their
* outcomes and resolved terminals, configs, tools, limits and memory sources.
* Only non-blank fields are emitted. Mirrors `stageDefinitionFields`.
*/
export function stageDefinitionFields(stage) {
const fields = [];
if (stage == null) return fields;
fields.push(field("Type", effectiveStageType(stage.type)));
if (str(stage.prompt).trim() !== "") fields.push(field("Prompt", str(stage.prompt), false, true));
if (str(stage.output).trim() !== "") fields.push(field("Output", str(stage.output), false, true));
const outcomes = stageOutcomes(stage).map((outcome) => {
const target = resolveTarget(outcome, String(stage.edges?.[outcome] ?? ""));
const suffix = isTerminal(target) ? " (terminal)" : "";
return `${outcome} → ${nodeLabel(target)}${suffix}`;
});
if (outcomes.length > 0) fields.push(field("Outcomes", outcomes.join("\n"), false, true));
const configs = stage.configs ?? {};
for (const key of Object.keys(configs).sort()) {
const value = str(configs[key]);
if (value.trim() !== "") fields.push(field(configLabel(key), value));
}
const tools = stage.blocks?.tools;
if (str(tools).trim() !== "") fields.push(field("Tools", str(tools), false, true));
const limits = stage.limits;
if (limits) {
if (Number(limits.max_visits) > 0) fields.push(field("Max visits", String(limits.max_visits)));
const on = limits.on ?? [];
if (on.length > 0) fields.push(field("Limit on", on.join(", ")));
}
const memory = stage.memory;
if (memory && Object.keys(memory).length > 0) {
const value = Object.entries(memory)
.map(([key, source]) => `${key}: ${source}`)
.join("\n");
fields.push(field("Memory", value, false, true));
}
const notify = stage.notify;
if (notify) {
const on = notify.on ?? [];
if (on.length > 0) fields.push(field("Notify on", on.join(", ")));
if (str(notify.destination).trim() !== "") fields.push(field("Notify destination", str(notify.destination)));
const artifacts = notify.artifacts ?? [];
if (artifacts.length > 0) fields.push(field("Notify artifacts", artifacts.join(", ")));
}
return fields;
}
/** The config key's display label (mirrors StageDetailPane.configLabel). */
export function configLabel(key) {
switch (key) {
case "provider":
return "Provider";
case "model":
return "Model";
case "retries":
return "Retries";
case "timeout":
return "Timeout";
case "budget_usd":
return "Budget (USD)";
case "budget_tokens":
return "Budget (tokens)";
case "harness":
return "Harness";
default:
return key;
}
}
/** Incoming routes into a terminal node, for a pane opened on a terminal. */
export function terminalFields(graph, key) {
const lines = graphEdges(graph)
.filter((edge) => edge.target === key)
.map((edge) => `${edge.source} · ${edge.label} → ${nodeLabel(key)}`);
return lines.length === 0 ? [] : [field("Incoming routes", lines.join("\n"), false, true)];
}
/**
* The shared visit label for a step's control evidence, e.g.
* `3 / 5 (limit reached)` (or just `3` when no max is recorded). Mirrors
* `controlVisitLabel`.
*/
export function controlVisitLabel(control) {
const visit = Number(control?.visit) || 0;
const max = Number(control?.max_visits) || 0;
const base = max > 0 ? `${visit} / ${max}` : String(visit);
return base + (control?.limit_reached ? " (limit reached)" : "");
}
/** Clamps a visit index into `[0, count)`; an empty list yields 0. */
export function clampVisitIndex(index, count) {
if (count <= 0) return 0;
return Math.min(Math.max(Number(index) || 0, 0), count - 1);
}
/**
* The ordered sections of the stage pane for one stage and visit: a run pane
* leads with the visit's Artifacts gallery, then its exported Session when it
* has one, then Output, Input and the remaining evidence (`This run`); the
* stage's own definition is last. Blank field sections are skipped; the
* artifacts section always shows for a reached visit. Mirrors
* `stageSectionSpecs`.
*/
/**
* Whether a recorded field value is markdown rather than plain text: a heading, a
* fenced block, a bullet/ordered list or a table. The new stage turns write
* markdown bodies (`# outcome` …), while historical steps store plain maps; this
* keeps the old ones rendering as code.
*/
export function looksLikeMarkdown(value) {
const text = typeof value === "string" ? value : "";
if (!text) return false;
return /^#{1,6}\s/m.test(text) || /```/.test(text) || /^\s*(?:[-*]|\d+\.)\s+/m.test(text) || /^\|.+\|/m.test(text);
}
/**
* The stage pane's body sections for one visit: what the stage produced (its
* non-system artifacts) and what it changed. The turn files, session export and
* stage definition live behind Audit & debug, so the pane stays about the work.
*/
export function stageSectionSpecs(stageKey, graph, runSteps, visitIndex, runContext, allSteps = null) {
const specs = [];
const steps = runSteps ?? [];
const selectedStep = steps[clampVisitIndex(visitIndex, steps.length)];
if (runContext && selectedStep != null) {
const used = visitArtifacts(selectedStep, allSteps ?? steps).length;
specs.push({ key: "artifacts", title: `${STAGE_ARTIFACTS_TITLE} · ${used} recorded`, artifacts: true });
if (selectedStep.file_changes != null) {
specs.push({ key: "changes", title: runChangesHeader(runChanges([selectedStep])), changes: true });
}
}
return specs;
}
// ---------------------------------------------------------------------------
// Verdict (ui/graph/StageVerdict.kt)
// ---------------------------------------------------------------------------
/**
* The recorded artifacts a verdict refers to: its referenced names resolved to
* the visit's recorded artifacts, in recorded order and deduplicated by name. A
* name the server never recorded is dropped. Mirrors
* `referencedVerdictArtifacts`.
*/
export function referencedVerdictArtifacts(verdict, artifacts) {
const names = verdict?.artifacts ?? [];
if (names.length === 0) return [];
const wanted = new Set(names);
const seen = new Set();
const referenced = [];
for (const artifact of artifacts ?? []) {
const name = str(artifact?.name);
if (name === "" || seen.has(name)) continue;
seen.add(name);
if (wanted.has(name)) referenced.push(artifact);
}
return referenced;
}
/**
* Splits a reason into literal runs and references to the recorded artifacts it
* names (by full name or basename). At the same index a longer token wins. With
* nothing to reference the whole reason is one literal segment; an empty reason
* yields no segments. Mirrors `verdictReasonSegments`.
*/
export function verdictReasonSegments(reason, references) {
const text = String(reason ?? "");
if (text === "") return [];
const list = references ?? [];
if (list.length === 0) return [{ text }];
const tokens = [];
for (const artifact of list) {
const name = str(artifact?.name);
tokens.push([name, artifact]);
const base = artifactBaseName(name);
if (base !== "" && base !== name) tokens.push([base, artifact]);
}
tokens.sort((a, b) => b[0].length - a[0].length);
const segments = [];
let literal = "";
let index = 0;
while (index < text.length) {
const match = tokens.find(([token]) => text.startsWith(token, index));
if (!match) {
literal += text[index];
index++;
} else {
if (literal !== "") {
segments.push({ text: literal });
literal = "";
}
segments.push({ text: match[0], artifact: match[1] });
index += match[0].length;
}
}
if (literal !== "") segments.push({ text: literal });
return segments;
}
/** The last path segment of a recorded artifact name (`shots/x.png` → `x.png`). */
export function artifactBaseName(name) {
const text = str(name);
const slash = Math.max(text.lastIndexOf("/"), text.lastIndexOf("\\"));
return slash === -1 ? text : text.slice(slash + 1);
}
// ---------------------------------------------------------------------------
// Formatting (ui/Format.kt)
// ---------------------------------------------------------------------------
/**
* One changed-file line, e.g. `modified src/a.kt +3 -2 (truncated)`. The kind,
* path and binary/truncated markers are Format.kt's exact spelling; the `+N -M`
* stat is added when the recorded patch is readable (not binary) and parses to
* at least one hunk, so a line never claims a line count it could not read. A
* binary file keeps its marker and never gets a text stat.
*/
export function fileChangeLine(file) {
const base = `${str(file?.kind)} ${str(file?.path)}`;
const binary = file?.binary ? " (binary)" : "";
const truncated = file?.truncated ? " (truncated)" : "";
let stat = "";
if (!file?.binary) {
const patch = str(file?.patch);
if (patch.trim() !== "") {
const parsed = parseUnifiedPatch(patch);
if (parsed.hunks.length > 0) stat = changeStat(parsed.added, parsed.removed);
}
}
return base + (stat !== "" ? ` ${stat}` : "") + binary + truncated;
}
/** One notification receipt, e.g. `delivered → ntfy · ok`, skipping a blank diagnostic. */
export function notificationLine(receipt) {
const diagnostic = str(receipt?.diagnostic);
const suffix = diagnostic.trim() !== "" ? ` · ${diagnostic}` : "";
return `${str(receipt?.status)} → ${str(receipt?.destination)}${suffix}`;
}
/**
* A compact file-change summary, e.g.
* `partial (2 files), 1 skipped, 3 omitted · Excluded protected files.`.
* The status word, file count, skipped and omitted counts are the capture's own
* honest facts; the trimmed diagnostic follows after ` · ` when present. Blank
* parts are omitted, and an entirely blank change set renders as "".
*/
export function fileChangesSummary(changes) {
let text = "";
const status = str(changes?.status).trim();
if (status !== "") text += status;
const files = changes?.files ?? [];
if (files.length > 0) {
if (text !== "") text += " ";
text += `(${files.length} files)`;
}
if (Number(changes?.skipped) > 0) {
if (text !== "") text += ", ";
text += `${changes.skipped} skipped`;
}
if (Number(changes?.omitted) > 0) {
if (text !== "") text += ", ";
text += `${changes.omitted} omitted`;
}
const diagnostic = str(changes?.diagnostic).trim();
if (diagnostic !== "") {
if (text !== "") text += " · ";
text += diagnostic;
}
return text;
}
// ---------------------------------------------------------------------------
// Outcome colours (ui/graph/GraphPalette.kt, WorkflowGraph.outcomeColor)
// ---------------------------------------------------------------------------
/**
* The fixed palette for the graph-only flow outcomes (rejected/exhausted/retry/
* approved/fast/missing) plus the reserved fallback slots. Mirrors
* GraphPalette.colors.
*/
export const FLOW_OUTCOME_COLORS = [
"#F5A3A3", // rejected
"#F5B37A", // exhausted
"#7FD4E8", // retry
"#C0A3F5", // approved
"#F0E07A", // fast
"#F5A3D0", // missing
"#D8C98A", // fallback
"#9FD8C0", // fallback
"#D8A8C0", // fallback
];
const KNOWN_FLOW_OUTCOMES = ["rejected", "exhausted", "retry", "approved", "fast", "missing"];
/**
* The stable palette index for an outcome with no run-state meaning: known flow
* outcomes get their curated slot, everything else a stable fallback slot.
* Mirrors GraphPalette.outcomeColorIndex.
*/
export function flowOutcomeIndex(outcome) {
const known = KNOWN_FLOW_OUTCOMES.indexOf(outcome);
if (known !== -1) return known;
const fallbackStart = KNOWN_FLOW_OUTCOMES.length;
const fallbackCount = FLOW_OUTCOME_COLORS.length - fallbackStart;
if (fallbackCount <= 0) return 0;
return fallbackStart + (Math.abs(hashString(outcome)) % fallbackCount);
}
/**
* The colour token for an outcome/stage status: a run-state word takes the
* shared status palette (`state {state}`), any other flow outcome its curated
* palette slot (`flow {index}`). The renderer maps the token onto a CSS class so
* the timeline and the verdict block agree. Mirrors WorkflowGraph.outcomeColor.
*/
export function outcomeColorToken(outcome, status) {
const state = runStateOf(String(outcome ?? "").trim() !== "" ? outcome : status);
if (state !== "unknown") return `state ${state}`;
return `flow ${flowOutcomeIndex(String(outcome ?? "").trim() !== "" ? outcome : status)}`;
}
/** A distinct glyph per run state, echoing the app's one-glyph-per-state set. */
export function stateGlyph(state) {
switch (state) {
case "running":
return "▶";
case "queued":
return "◷";
case "waiting":
return "✋";
case "succeeded":
return "✓";
case "failed":
return "✕";
case "canceled":
return "⊘";
case "interrupted":
return "❚❚";
case "blocked":
return "■";
case "skipped":
return "⏭";
case "active":
return "⚡";
default:
return "?";
}
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
function str(value) {
return value == null ? "" : String(value);
}
/** A small, stable 31-bit string hash (Kotlin String.hashCode analogue). */
function hashString(value) {
let hash = 0;
for (let i = 0; i < value.length; i++) {
hash = (hash * 31 + value.charCodeAt(i)) | 0;
}
return hash;
}
-435
View File
@@ -1,435 +0,0 @@
// The pure fold from a server-pushed `run_event` into the client's cached run
// state. The app never polls: every value on the runs list, the pipeline rows'
// last-run line and the run detail (status, timeline, stages, completed count)
// is advanced here from the pushes.
//
// This is a direct port of android/.../ui/RunEvents.kt so the browser says and
// shows exactly what the app does. It is deliberately DOM-free: every rule is
// unit-testable under `node --test` with no browser and no server, and app.js
// keeps the wiring.
//
// The fold is monotonic so an out-of-order or duplicated delta can never move a
// run or a step backwards. A delta that names a run the list does not hold is
// inserted as a new row from the frame's own identity (pipeline id, name, title,
// version), so a run started after the screen loaded appears without a fetch;
// only a frame with no such identity (an older server) reports `needsResync`, and
// the caller re-reads the server's current list once instead.
//
// Field names stay snake_case exactly as they are on the wire
// (internal/protocol/runevents.go RunEventFrame / RunStepDelta). Every
// server-provided string is only ever compared or rendered, never parsed as
// markup; the caller sets it with textContent.
/** Run statuses from which a run never transitions again. */
export const TERMINAL_RUN_STATUSES = Object.freeze([
"succeeded",
"failed",
"canceled",
"interrupted",
]);
/** The lifecycle rank at which a status is settled: a later status never rewrites it. */
const SETTLED_RANK = 2;
/**
* Whether `status` is the human-stage status a run (or its waiting step) parks
* on: it is not terminal and it is not executing, but it still needs the full
* detail (the compact delta carries no options/prompt), so a pending decision is
* surfaced live.
*/
export function isWaitingRunStatus(status) {
return String(status ?? "").trim().toLowerCase() === "waiting";
}
/** Whether `status` is a settled run status (no further transitions expected). */
export function isTerminalRunStatus(status) {
return TERMINAL_RUN_STATUSES.includes(String(status ?? "").trim().toLowerCase());
}
/**
* The run lifecycle as an ordinal so a delta can only advance it:
* queued (0) < running/waiting (1) < terminal (2). A blank or unknown word is -1.
*/
export function runLifecycleRank(status) {
switch (String(status ?? "").trim().toLowerCase()) {
case "queued":
return 0;
case "running":
case "waiting":
return 1;
case "succeeded":
case "failed":
case "canceled":
case "interrupted":
return 2;
default:
return -1;
}
}
/**
* The step lifecycle as an ordinal so a settled visit is never reopened:
* in-flight running/waiting (1) < finished completed/failed/canceled (2).
*/
export function stepLifecycleRank(status) {
switch (String(status ?? "").trim().toLowerCase()) {
case "running":
case "waiting":
return 1;
case "completed":
case "failed":
case "canceled":
case "interrupted":
return 2;
default:
return -1;
}
}
/**
* The one staleness rule, shared by the run and step ladders so they cannot
* drift: a status behind the current rank, or a different settled word after the
* state already settled, marks the whole delta stale.
*/
function isStaleTransition(current, incoming, rank) {
if (String(incoming ?? "").trim() === "") return false;
const cur = rank(current);
const inc = rank(incoming);
if (cur < 0 || inc < 0) return false;
return inc < cur || (cur >= SETTLED_RANK && inc >= SETTLED_RANK && incoming !== current);
}
/** Whether the run frame is a stale transition that must be dropped whole. */
export function isStaleRunFrame(current, incoming, resourceWaitSet = false) {
if (resourceWaitSet && incoming === "queued" && !isTerminalRunStatus(current)) return false;
return isStaleTransition(current, incoming, runLifecycleRank);
}
/** The step counterpart of `isStaleRunFrame`: a settled visit drops a stale delta whole. */
export function isStaleStepDelta(current, incoming) {
return isStaleTransition(current, incoming, stepLifecycleRank);
}
/**
* The one monotonic status rule, shared by the run and step ladders so they
* cannot drift: a blank or unknown word never wins, a higher rank always does,
* and once a settled rank is reached its word is kept forever.
*/
function advanceStatus(current, incoming, rank) {
if (String(incoming ?? "").trim() === "" || incoming === current) return current;
const cur = rank(current);
const inc = rank(incoming);
if (cur < 0) return incoming;
if (inc < 0) return current;
if (inc > cur) return incoming;
if (cur >= SETTLED_RANK) return current;
return incoming;
}
function advanceRunStatus(current, incoming) {
return advanceStatus(current, incoming, runLifecycleRank);
}
function advanceStepStatus(current, incoming) {
return advanceStatus(current, incoming, stepLifecycleRank);
}
/**
* The client's best knowledge of `executing`: queued/running only; unknown keeps
* `current`.
*/
export function executingFor(status, current) {
switch (String(status ?? "").trim().toLowerCase()) {
case "queued":
case "running":
return true;
case "waiting":
case "succeeded":
case "failed":
case "canceled":
case "interrupted":
return false;
default:
return Boolean(current);
}
}
function blank(value) {
return String(value ?? "").trim() === "";
}
function sameResourceWait(a, b) {
if (a === b) return true;
if (!a || !b) return false;
return (
a.resource === b.resource &&
a.stage === b.stage &&
a.sequence === b.sequence &&
a.queued_since === b.queued_since
);
}
// 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 {
notify_mode: current.notify_mode ?? "auto",
resource_wait: current.resource_wait ?? null,
status: current.status ?? "",
outcome: current.outcome ?? "",
current_stage: current.current_stage ?? "",
completed_steps: Number(current.completed_steps) || 0,
created_at: current.created_at ?? "",
finished_at: current.finished_at ?? "",
executing: Boolean(current.executing),
cancel_requested: Boolean(current.cancel_requested),
cleanup_unconfirmed: Boolean(current.cleanup_unconfirmed),
export_pending_sequence: Number(current.export_pending_sequence) || 0,
};
}
/**
* The single run-field merge: every value advances forward, so the row and the
* detail can never apply a frame differently. Returns the current object when
* nothing changed, so a no-op frame keeps the same reference.
*/
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
: frame.resource_wait_set === true
? (frame.resource_wait ?? null)
: before.resource_wait,
status,
...(before.export_pending_sequence || Number(frame.export_pending_sequence) > 0 || Object.hasOwn(current, "export_pending_sequence")
? { export_pending_sequence: blank(frame.status) ? before.export_pending_sequence : status === "waiting" ? Number(frame.export_pending_sequence) || 0 : 0 }
: {}),
outcome: blank(frame.outcome) ? before.outcome : frame.outcome,
current_stage: blank(frame.current_stage) ? before.current_stage : frame.current_stage,
completed_steps: Math.max(before.completed_steps, Number(frame.completed_steps) || 0),
created_at: blank(frame.created_at) ? before.created_at : frame.created_at,
finished_at: blank(frame.finished_at) ? before.finished_at : frame.finished_at,
executing: executingFor(status, before.executing),
cancel_requested: before.cancel_requested || frame.cancel_requested === true,
cleanup_unconfirmed: before.cleanup_unconfirmed || frame.cleanup_unconfirmed === true,
};
// 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) ||
merged.status !== before.status ||
merged.outcome !== before.outcome ||
merged.current_stage !== before.current_stage ||
merged.completed_steps !== before.completed_steps ||
merged.created_at !== before.created_at ||
merged.finished_at !== before.finished_at ||
merged.executing !== before.executing ||
merged.cancel_requested !== before.cancel_requested ||
merged.cleanup_unconfirmed !== before.cleanup_unconfirmed;
const exportWaitChanged = (Number(merged.export_pending_sequence) || 0) !== before.export_pending_sequence;
return changed || exportWaitChanged ? { ...current, ...merged, ...(graphEvidence ? { graph_evidence: graphEvidence } : {}) } : current;
}
// Reuse the detail's monotonic visit merge, then compact by last stage visit and
// distinct route. Keep completeness separate: a delta from an older server or
// a mid-run first frame cannot prove that earlier stages were never visited.
function mergeGraphEvidence(current, frame) {
if (!frame.graph_evidence && !frame.graph_visits?.length && !frame.step) return current;
let visits = current?.visits ?? [];
const incoming = [...(frame.graph_evidence?.visits ?? []), ...(frame.graph_visits ?? []),
...(frame.step ? [frame.step] : [])];
for (const step of incoming) {
const { sequence, stage, status, outcome, target } = step;
visits = upsertStep(visits, { sequence, stage, status, outcome, target });
}
const latest = new Map();
const routes = new Map();
for (const visit of visits) {
latest.set(visit.stage, visit.sequence);
if (visit.outcome && visit.target) routes.set(JSON.stringify([visit.stage, visit.outcome, visit.target]), visit.sequence);
}
visits = visits.filter((visit) => latest.get(visit.stage) === visit.sequence ||
(visit.outcome && visit.target && routes.get(JSON.stringify([visit.stage, visit.outcome, visit.target])) === visit.sequence));
// Explicit allowlist: graph evidence never copies diagnostic/private fields.
visits = visits.map(({ sequence, stage, status, outcome, target }) => ({ sequence, stage, status, outcome, target }));
const result = { complete: Boolean(current?.complete || frame.graph_evidence?.complete), visits };
return JSON.stringify(result) === JSON.stringify(current) ? current : result;
}
/**
* The row a frame for a run the list has never held describes, or null when the
* frame lacks the pipeline identity a row needs (an older server), in which case
* the caller resyncs instead of inventing an incomplete row. The frame already
* carries everything the row shows, so no field is guessed from cached state.
*/
export function newRunSummaryFromFrame(frame) {
const pipelineId = Number(frame?.pipeline_id);
const name = String(frame?.name ?? "");
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),
pipeline_id: pipelineId,
name,
notify_mode: frame.notify_mode ?? "auto",
title: blank(frame.title) ? null : frame.title,
version: Number(frame.version) || 0,
status: frame.status ?? "",
...(Number(frame.export_pending_sequence) > 0 ? { export_pending_sequence: Number(frame.export_pending_sequence) } : {}),
executing: executingFor(frame.status, true),
cancel_requested: frame.cancel_requested === true,
cleanup_unconfirmed: frame.cleanup_unconfirmed === true,
outcome: frame.outcome ?? "",
current_stage: frame.current_stage ?? "",
created_at: frame.created_at ?? "",
finished_at: frame.finished_at ?? "",
completed_steps: Number(frame.completed_steps) || 0,
};
}
/**
* Folds one pushed frame into the runs list, in place and without reordering. A
* run the list has never held is inserted as a new row at the head (newest
* first, matching the server's own order) when the frame carries its pipeline
* identity, so a run started after the screen loaded appears while the operator
* watches without a fetch; a frame with no identity (an older server) still
* reports `needsResync` so the caller re-reads once instead.
*
* Returns `{ runs, needsResync }`; `runs` is the same array reference when
* nothing changed.
*/
export function foldRunEvent(runs, frame) {
const list = Array.isArray(runs) ? runs : [];
const runId = Number(frame?.run_id);
if (!(runId > 0)) return { runs: list, needsResync: false };
const index = list.findIndex((run) => Number(run?.id) === runId);
if (index < 0) {
const added = newRunSummaryFromFrame(frame);
if (!added) return { runs: list, needsResync: true };
return { runs: [added, ...list], needsResync: false };
}
const current = list[index];
const updated = applyRunStateFields(current, frame);
if (updated === current) return { runs: list, needsResync: false };
const next = list.slice();
next[index] = updated;
return { runs: next, needsResync: false };
}
/**
* Upserts one step delta, matched by sequence: an existing visit has only its
* non-blank fields advanced, and a new visit is inserted in sequence order so a
* late delta for an earlier step cannot reorder the timeline.
*/
function upsertStep(steps, delta) {
const list = Array.isArray(steps) ? steps : [];
const sequence = Number(delta?.sequence) || 0;
const index = list.findIndex((step) => Number(step?.sequence) === sequence);
if (index >= 0) {
const current = list[index];
const updated = applyStepDelta(current, delta);
if (updated === current) return list;
const next = list.slice();
next[index] = updated;
return next;
}
const added = {
sequence,
stage: delta.stage ?? "",
status: advanceStepStatus("", delta.status),
outcome: delta.outcome ?? "",
target: delta.target ?? "",
diagnostic: delta.diagnostic ?? "",
};
const next = list.slice();
const at = next.findIndex((step) => Number(step?.sequence) > sequence);
if (at < 0) next.push(added);
else next.splice(at, 0, added);
return next;
}
function applyStepDelta(current, delta) {
if (isStaleStepDelta(current.status, delta.status)) return current;
const merged = {
stage: blank(delta.stage) ? current.stage : delta.stage,
status: advanceStepStatus(current.status, delta.status),
outcome: blank(delta.outcome) ? current.outcome : delta.outcome,
target: blank(delta.target) ? current.target : delta.target,
diagnostic: blank(delta.diagnostic) ? current.diagnostic : delta.diagnostic,
};
const changed =
merged.stage !== current.stage ||
merged.status !== current.status ||
merged.outcome !== current.outcome ||
merged.target !== current.target ||
merged.diagnostic !== current.diagnostic;
return changed ? { ...current, ...merged } : current;
}
/**
* Folds one pushed frame into a cached run detail: the run's own status/outcome/
* stage/timestamps plus at most one step, matched by sequence so a duplicate or
* out-of-order step delta is idempotent and never adds a second visit. A frame
* for another run is ignored unchanged, as is a stale one (dropped whole).
*/
export function foldRunEventDetail(detail, frame) {
if (!detail || Number(detail.id) !== Number(frame?.run_id)) return detail;
if (isStaleRunFrame(detail.status, frame.status, frame.resource_wait_set === true)) return detail;
const merged = applyRunStateFields(detail, frame);
const steps = frame.step ? upsertStep(detail.steps ?? [], frame.step) : (detail.steps ?? []);
if (merged === detail && steps === (detail.steps ?? [])) return detail;
return { ...detail, ...runStateFields(merged), steps };
}
/**
* Whether a frame carries data the compact delta cannot express (recorded
* artifacts, output, a settled visit's diagnostic), so the caller fetches the
* full run once to fill those in rather than showing a stale gallery. A waiting
* run or step is included: its options and prompt live in the waiting step's
* `output`, which the compact delta deliberately omits, so the fetch is what
* surfaces a pending decision without a manual refresh.
*/
export function runDetailNeedsFullSync(frame) {
const step = frame?.step;
const stepSettled = step != null && stepLifecycleRank(step.status) >= SETTLED_RANK;
const stepWaiting = step != null && isWaitingRunStatus(step.status);
return (
stepSettled ||
stepWaiting ||
frame?.cancel_requested === true ||
frame?.cleanup_unconfirmed === true ||
isTerminalRunStatus(frame?.status) ||
isWaitingRunStatus(frame?.status)
);
}
-34
View File
@@ -1,34 +0,0 @@
// A launch intent survives a lost response and a page reload. It is never
// replayed automatically; the operator explicitly checks/retries the same key.
import { newChatOperationId } from "./repository.js";
function storageKey(endpoint, pipelineId, version) {
return `pipelines.web.pendingRun.v1:${endpoint}:${pipelineId}:${version}`;
}
export function pendingRun(storage, endpoint, pipelineId, version) {
try {
const item = JSON.parse(storage?.getItem(storageKey(endpoint, pipelineId, version)) ?? "null");
if (!item || typeof item.requestKey !== "string" || typeof item.prompt !== "string" || typeof item.workspace !== "string") return null;
if (item.pipelineId !== pipelineId || item.version !== version) return null;
return item;
} catch {
return null;
}
}
export function createRunIntent(payload) {
return { ...payload, requestKey: newChatOperationId() };
}
export function saveRunIntent(storage, endpoint, intent) {
try {
storage?.setItem(storageKey(endpoint, intent.pipelineId, intent.version), JSON.stringify(intent));
} catch { /* In-memory identity still protects retries when storage is unavailable. */ }
}
export function clearRunIntent(storage, endpoint, intent) {
try {
storage?.removeItem(storageKey(endpoint, intent.pipelineId, intent.version));
} catch { /* Storage failure must not turn a completed launch into another run. */ }
}
-531
View File
@@ -1,531 +0,0 @@
// Pure, DOM-free helpers for the runs history list: the status vocabulary, run
// identity, progress/meta wording, filtering, sorting and day grouping.
//
// This mirrors the Android app exactly — ui/screens/RunHistoryScreen.kt,
// screens/ListFilter.kt, screens/ListSort.kt, ui/RunIdentity.kt and ui/Format.kt
// — so the browser list reads the same words in the same order as the app. It is
// deliberately DOM-free: every rule here is unit-testable under `node --test`
// with no browser and no server. app.js keeps the wiring.
//
// 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
// ---------------------------------------------------------------------------
/**
* The server's own run vocabulary, in the filter's display order
* (internal/pipeline/runs.go: queued/running/waiting/succeeded/failed/canceled/
* interrupted). The app-only `active` usage bucket, the stage-outcome words
* (`blocked`/`skipped`) and the `unknown` fallback are deliberately not offered
* as run-status filters, mirroring RUN_STATUS_FILTERS.
*/
export const RUN_STATES = [
"queued",
"running",
"waiting",
"succeeded",
"failed",
"canceled",
"interrupted",
];
/**
* Maps a server status or outcome word to its canonical display state, accepting
* the server's vocabulary only (the steps/outcomes synonyms resolve onto the same
* states so one chip set renders list, detail and timeline). Mirrors
* runStateOf: blank or unrecognised input is the safe `unknown` fallback.
*/
export function runStatusLabel(run) {
if (["queued", "running", "waiting"].includes(run?.status)) {
if (run.cleanup_unconfirmed) return "Cleanup unconfirmed — workspace reserved";
if (run.cancel_requested) return "Stopping — waiting for execution to stop";
if (run.status === "waiting" && Number(run.export_pending_sequence) > 0) return "Waiting for session export";
}
return run?.status || "unknown";
}
export function runStateOf(status) {
switch (String(status ?? "").trim().toLowerCase()) {
case "running":
return "running";
case "queued":
return "queued";
case "waiting":
return "waiting";
case "active":
return "active";
case "succeeded":
case "success":
case "completed":
case "done":
return "succeeded";
case "failed":
case "error":
return "failed";
case "canceled":
case "cancelled":
return "canceled";
case "interrupted":
return "interrupted";
case "blocked":
return "blocked";
case "skipped":
return "skipped";
default:
return "unknown";
}
}
// ---------------------------------------------------------------------------
// Identity, wording and time formatting
// ---------------------------------------------------------------------------
/**
* The runs list's two identity lines: `label` is the run's primary line and
* `pipeline` is the pipeline the run belongs to, shown as a second line only
* when the label is a stored title. A run with no title falls back to the
* pipeline name as its only line — never a title followed by an empty one.
* Mirrors ui/RunIdentity.kt runIdentity.
*/
export function runIdentity(title, name) {
const stored = String(title ?? "").trim();
return stored
? { label: stored, pipeline: String(name ?? "") }
: { label: String(name ?? ""), pipeline: null };
}
/** The version chip label, e.g. `v5` (mirrors RunHistoryScreen.VersionChip). */
export function versionLabel(version) {
return `v${version}`;
}
/**
* A visit count in the app's one singular/plural spelling (`1 visit` /
* `n visits`), mirroring ui/Format.kt visitCount so the same run is never
* described inconsistently.
*/
export function visitCount(count, adjective) {
const n = Number(count) || 0;
return `${n} ${adjective} ${n === 1 ? "visit" : "visits"}`;
}
/** Parses an RFC3339 timestamp to epoch millis, or null when blank/unparseable. */
export function parseInstant(text) {
if (text == null) return null;
const value = String(text).trim();
if (!value) return null;
const ms = Date.parse(value);
return Number.isNaN(ms) ? null : ms;
}
/**
* Non-negative whole seconds between two RFC3339 timestamps, or null when either
* is blank/unparseable or the end precedes the start. Mirrors Format.durationSeconds
* (truncating toward zero), so a sort key and the printed duration never disagree.
*/
export function durationSeconds(start, end) {
const from = parseInstant(start);
const to = parseInstant(end);
if (from == null || to == null) return null;
const seconds = Math.trunc((to - from) / 1000);
return seconds >= 0 ? seconds : null;
}
/**
* Non-negative whole seconds from a [start] RFC3339 timestamp to [nowMillis], or
* null when [start] is blank/unparseable. A future start (clock skew) reads as 0,
* never a negative. Mirrors Format.secondsSince.
*/
export function secondsSince(start, nowMillis) {
const from = parseInstant(start);
if (from == null) return null;
return Math.max(0, Math.trunc((nowMillis - from) / 1000));
}
/**
* Human duration for a whole number of seconds: `Ns`, `Nm Ss`, `Hh Mm`. Mirrors
* Format.formatDuration (a negative total renders as `0s`).
*/
export function formatDuration(totalSeconds) {
const seconds = Math.max(0, Math.trunc(Number(totalSeconds) || 0));
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}
/**
* An RFC3339 timestamp as the app's one human, local rendering (`d MMM HH:mm`,
* e.g. `17 Oct 21:26`), or null when blank/unparseable so a caller omits the
* value rather than printing a blank. [options] may carry a `zone` (IANA name)
* and `locale` for deterministic tests; both default to the runtime's.
*/
export function formatLocalTimestamp(instant, options = {}) {
const ms = parseInstant(instant);
if (ms == null) return null;
return formatInZone(ms, options, (parts) => `${parts.day} ${parts.month} ${parts.hour}:${parts.minute}`);
}
/** The run's calendar day (`YYYY-MM-DD`) in [zone], or null when unparseable. */
export function localDayKey(value, zone) {
const ms = value instanceof Date ? value.getTime() : parseInstant(value);
if (ms == null || !Number.isFinite(ms)) return null;
try {
const fmt = new Intl.DateTimeFormat("en-CA", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone: zone,
});
return fmt.format(new Date(ms));
} catch {
return null;
}
}
/**
* The day header for a run: `Today`, `Yesterday`, `d MMM yyyy`, or `Unknown date`
* for a blank/unparseable timestamp. [today] may be a day-key string or a Date.
* Mirrors RunHistoryScreen.dayLabel.
*/
export function dayLabel(createdAt, today, zone) {
const key = localDayKey(createdAt, zone);
if (key == null) return "Unknown date";
const todayKey = typeof today === "string" ? today : localDayKey(today, zone);
if (todayKey == null) return "Unknown date";
if (key === todayKey) return "Today";
if (key === addDays(todayKey, -1)) return "Yesterday";
return formatDayKey(key);
}
/**
* The runs list's meta line: `run {id} · {local d MMM HH:mm} · {duration}` for a
* finished run, and `run {id} · {live elapsed}` for an executing one (elapsed
* computed from its server start timestamp against [nowMillis]). Mirrors
* RunHistoryScreen.metaText.
*/
export function metaText(run, nowMillis, options = {}) {
const parts = [`run ${run.id}`];
if (run.executing) {
const elapsed = secondsSince(run.created_at, nowMillis);
if (elapsed != null) parts.push(formatDuration(elapsed));
} else {
const stamp = formatLocalTimestamp(run.created_at, options);
if (stamp != null) parts.push(stamp);
const duration = durationSeconds(run.created_at, run.finished_at);
if (duration != null) parts.push(formatDuration(duration));
}
return parts.join(" · ");
}
/**
* Progress from the fields a summary actually has: an optional resource-wait
* line, completed visits, then the current stage. Mirrors
* RunHistoryScreen.progressText.
*/
export function progressText(run) {
const parts = [];
if (run.resource_wait != null) {
parts.push(`Waiting for resource ${String(run.resource_wait.resource ?? "")}`);
}
parts.push(visitCount(run.completed_steps, "completed"));
const stage = String(run.current_stage ?? "").trim();
if (stage) parts.push(`stage ${stage}`);
return parts.join(" · ");
}
// ---------------------------------------------------------------------------
// Filters
// ---------------------------------------------------------------------------
/** The run-list time windows offered by the filter control. */
export const RUN_TIME_RANGES = [
{ value: "any_time", label: "Any time" },
{ value: "today", label: "Today" },
{ value: "last_7_days", label: "Last 7 days" },
{ value: "last_30_days", label: "Last 30 days" },
];
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, scheduled: "any" };
}
/** The number of active facets (one per status/pipeline/time choice). */
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) +
(["scheduled", "unscheduled"].includes(filters.scheduled) ? 1 : 0)
);
}
/** True when [run] is in [statuses]; an empty set means "any status". */
export function runMatchesStatuses(run, statuses) {
if (!statuses || statuses.size === 0) return true;
return statuses.has(runStateOf(run.status));
}
/** True when [run] belongs to [pipelineId]; null means "any pipeline". */
export function runMatchesPipeline(run, pipelineId) {
return pipelineId == null || run.pipeline_id === pipelineId;
}
/**
* True when [run] falls inside [range] relative to [today]. A blank/unparseable
* timestamp and a future-dated run never match a finite window; `any_time`
* matches everything. The window is inclusive calendar days ending today.
*/
export function runMatchesTimeRange(run, range, today, zone) {
if (!range || range === DEFAULT_TIME_RANGE) return true;
const key = localDayKey(run.created_at, zone);
if (key == null) return false;
const todayKey = typeof today === "string" ? today : localDayKey(today, zone);
if (todayKey == null) return false;
if (key > todayKey) return false;
switch (range) {
case "today":
return key === todayKey;
case "last_7_days":
return key >= addDays(todayKey, -6);
case "last_30_days":
return key >= addDays(todayKey, -29);
default:
return true;
}
}
/** Every run facet combined with AND. */
export function runMatchesFilters(run, filters, today, zone) {
return (
runMatchesStatuses(run, filters.statuses) &&
runMatchesPipeline(run, filters.pipelineId) &&
runMatchesTimeRange(run, filters.timeRange, today, zone) &&
matchesScheduleState(runScheduleState(run), filters.scheduled)
);
}
/** Narrows [runs] by [filters]; the default filters change nothing. */
export function filterRuns(runs, filters, today, zone) {
if (runFiltersActiveCount(filters) === 0) return runs;
return (runs ?? []).filter((run) => runMatchesFilters(run, filters, today, zone));
}
/** One selectable pipeline in the run filter, named from its runs. */
export function pipelineFilterOptions(runs) {
const names = new Map();
for (const run of runs ?? []) {
const current = names.get(run.pipeline_id);
if (current == null || current.trim() === "") names.set(run.pipeline_id, run.name ?? "");
}
return [...names.entries()]
.map(([id, name]) => ({ id, name: name.trim() === "" ? `Pipeline ${id}` : name }))
.sort((a, b) => caseInsensitiveCompare(a.name, b.name) || a.id - b.id);
}
// ---------------------------------------------------------------------------
// Sort
// ---------------------------------------------------------------------------
/** The run-list orderings offered by the sort control. */
export const RUN_SORTS = [
{ value: "newest_first", label: "Newest first" },
{ value: "oldest_first", label: "Oldest first" },
{ value: "longest_duration", label: "Longest duration" },
{ value: "shortest_duration", label: "Shortest duration" },
{ value: "pipeline_name", label: "Pipeline name" },
{ value: "status", label: "Status" },
];
export const DEFAULT_RUN_SORT = "newest_first";
/**
* The pure comparator for [sort]. Every case ends in an explicit id tie-break
* (`id` is unique) so runs that compare equal on the primary key always order
* the same way. A blank/unparseable timestamp and a run with no recorded
* duration (still executing) sort last regardless of direction and never crash.
* Mirrors ListSort.runComparator.
*/
export function runComparator(sort) {
switch (sort) {
case "oldest_first":
return (a, b) =>
ascending(instantOr(a.created_at, Infinity), instantOr(b.created_at, Infinity)) ||
ascending(a.id, b.id);
case "longest_duration":
return (a, b) => {
const da = durationSeconds(a.created_at, a.finished_at);
const db = durationSeconds(b.created_at, b.finished_at);
return (
ascending(da == null ? 1 : 0, db == null ? 1 : 0) ||
descending(da ?? -Infinity, db ?? -Infinity) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id)
);
};
case "shortest_duration":
return (a, b) => {
const da = durationSeconds(a.created_at, a.finished_at);
const db = durationSeconds(b.created_at, b.finished_at);
return (
ascending(da == null ? 1 : 0, db == null ? 1 : 0) ||
ascending(da ?? Infinity, db ?? Infinity) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id)
);
};
case "pipeline_name":
return (a, b) =>
caseInsensitiveCompare(a.name, b.name) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id);
case "status":
return (a, b) =>
caseInsensitiveCompare(a.status, b.status) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id);
case "newest_first":
default:
return (a, b) =>
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id);
}
}
/** Orders [runs] by [sort], returning a new array. */
export function sortRuns(runs, sort) {
return [...(runs ?? [])].sort(runComparator(sort));
}
// ---------------------------------------------------------------------------
// Day grouping and the list's slots
// ---------------------------------------------------------------------------
/**
* Groups runs by calendar day in [zone], preserving the order [order] puts them
* in and the order within a day. A blank/unparseable timestamp gets a safe
* "Unknown date" group. Mirrors RunHistoryScreen.groupRunsByDay.
*/
export function groupRunsByDay(runs, today, zone, order = runComparator(DEFAULT_RUN_SORT)) {
const groups = new Map();
for (const run of [...(runs ?? [])].sort(order)) {
const label = dayLabel(run.created_at, today, zone);
if (!groups.has(label)) groups.set(label, []);
groups.get(label).push(run);
}
return [...groups.entries()].map(([label, list]) => ({ label, runs: list }));
}
export const NO_RUNS_MESSAGE = "No runs have been recorded yet.";
export const NO_MATCH_MESSAGE = "No runs match the current filters.";
export const CLEAR_FILTERS_LABEL = "Clear filters";
/**
* The runs list's slots in layout order: the usage block when there is one, then
* either the single empty line (nothing recorded, or nothing matching the
* filters) or the day groups, then the inline error row. Pure and single-sourced
* with the renderer, so its size is exactly the list's entry count. Mirrors
* RunHistoryScreen.runListEntries.
*/
export function runListEntries(usage, nothingRecorded, nothingMatched, groups, error) {
const entries = [];
if (usage != null) entries.push({ kind: "usage", key: "usage", usage });
if (nothingRecorded) {
entries.push({ kind: "empty", key: "runs-empty", message: NO_RUNS_MESSAGE, actionLabel: null });
} else if (nothingMatched) {
entries.push({
kind: "empty",
key: "runs-filtered-empty",
message: NO_MATCH_MESSAGE,
actionLabel: CLEAR_FILTERS_LABEL,
});
} else {
for (const group of groups ?? []) {
entries.push({ kind: "day", key: `day-${group.label}`, label: group.label });
for (const run of group.runs) entries.push({ kind: "run", key: `run-${run.id}`, run });
}
}
if (error) entries.push({ kind: "error", key: "runs-error", message: error });
return entries;
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** Ascending compare of two numbers/strings, safe on the -Infinity sentinels. */
function ascending(x, y) {
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
/** Descending compare: the larger value sorts first. */
function descending(x, y) {
return ascending(y, x);
}
function instantOr(iso, fallback) {
const ms = parseInstant(iso);
return ms == null ? fallback : ms;
}
function caseInsensitiveCompare(a, b) {
const left = String(a ?? "").toLowerCase();
const right = String(b ?? "").toLowerCase();
if (left < right) return -1;
if (left > right) return 1;
return 0;
}
/** `dayKey` shifted by [days] calendar days (keys are `YYYY-MM-DD`). */
function addDays(dayKey, days) {
const [year, month, day] = dayKey.split("-").map(Number);
const shifted = new Date(Date.UTC(year, month - 1, day) + days * 86400000);
return `${shifted.getUTCFullYear()}-${pad2(shifted.getUTCMonth() + 1)}-${pad2(shifted.getUTCDate())}`;
}
function pad2(value) {
return String(value).padStart(2, "0");
}
function formatDayKey(dayKey) {
const [year, month, day] = dayKey.split("-").map(Number);
const parts = zoneParts(Date.UTC(year, month - 1, day), "UTC", "en-GB");
return `${parts.day} ${parts.month} ${parts.year}`;
}
function formatInZone(ms, options, assemble) {
const parts = zoneParts(ms, options.zone, options.locale);
return parts ? assemble(parts) : null;
}
/** The named parts of `ms` in [zone], or null when the zone is unusable. */
function zoneParts(ms, zone, locale) {
try {
const fmt = new Intl.DateTimeFormat(locale ?? "en-GB", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
timeZone: zone,
});
return Object.fromEntries(fmt.formatToParts(new Date(ms)).map((part) => [part.type, part.value]));
} catch {
return null;
}
}
-32
View File
@@ -1,32 +0,0 @@
// 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";
}
-106
View File
@@ -1,106 +0,0 @@
// Saved schedules are independent RunInfo snapshots, never pipeline definitions.
export const SCHEDULE_DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const clone = (value) => JSON.parse(JSON.stringify(value));
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
export function scheduleDraft({ pipeline, schedule = null, run = null, workspace = '', timezone } = {}) {
const source = schedule ?? run ?? {};
const input = clone(source.input ?? {});
const { prompt = '', ...other } = input;
const rule = source.rule ?? {};
return {
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),
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 ?? '',
};
}
export function parseScheduleObject(text, label) {
let value;
try { value = JSON.parse(text); } catch { throw new Error(`${label} must be valid JSON.`); }
if (!object(value)) throw new Error(`${label} must be a JSON object (not an array or null).`);
return value;
}
export function validScheduleModel(value) {
return typeof value === 'string' && /^[^\s/]+\/[^\s]+$/.test(value);
}
export function serializeSchedule(draft, { pipelineId, schedule = null } = {}) {
if (!String(draft.name).trim()) throw new Error('Enter a schedule name.');
if (typeof draft.prompt !== 'string' || !draft.prompt.trim()) throw new Error('Enter a prompt.');
const version = Number(draft.version);
if (!/^\d+$/.test(String(draft.version)) || !Number.isSafeInteger(version) || version < 1) throw new Error('Choose a positive pinned version, not latest (0).');
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.');
}
if (!['auto', 'on', 'off'].includes(draft.notifyMode)) throw new Error('Choose a notification mode.');
if (!Array.isArray(draft.days) || draft.days.some(day => !SCHEDULE_DAYS.includes(day)) || new Set(draft.days).size !== draft.days.length) throw new Error('Choose valid, distinct weekdays.');
const rule = { ...(schedule?.rule ?? {}) };
delete rule.every; delete rule.times; delete rule.days; delete rule.timezone;
if (draft.mode === 'interval') {
const every = draft.every.trim();
// Accept Go-style compound durations and decimal components, without parseInt truncation.
const parts = [...every.matchAll(/((?:\d+(?:\.\d*)?|\.\d+))(ms|us|µs|ns|h|m|s)/g)];
const units = { h: 3600000, m: 60000, s: 1000, ms: 1, us: .001, 'µs': .001, ns: .000001 };
const duration = parts.reduce((sum, part) => sum + Number(part[1]) * units[part[2]], 0);
if (parts.map(part => part[0]).join('') !== every || !Number.isFinite(duration) || duration < 60000) throw new Error('Interval must be at least 1m (for example 24h or 1h30m).');
rule.every = every;
} else if (draft.mode === 'clock') {
const times = draft.times.split(',').map(time => time.trim());
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) {
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 { 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();
}
const record = { ...(schedule ? clone(schedule) : {}), id: schedule?.id ?? 0,
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];
}
return record;
}
export function scheduleRuleLabel(rule = {}) {
return [rule.every ? `Every ${rule.every}` : (rule.times ?? []).join(', '),
(rule.days ?? []).join(', '), rule.timezone && rule.timezone !== 'Local' ? rule.timezone : 'Server timezone'].filter(Boolean).join(' · ');
}
export function scheduleDueLabel(value, timeZone = '') {
if (!value) return 'Not scheduled';
const date = new Date(value);
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)`;
}
-522
View File
@@ -1,522 +0,0 @@
// Pure, DOM-free omni-search logic for the web client, ported from the Android
// client so the browser says and shows exactly the same things:
// ui/OmniSearchResults.kt searchRow, snippetSpans, SearchKindFilter,
// SearchSort, filterSearchResults,
// sortSearchResults, searchTarget,
// searchFieldSection, resolveRunTarget,
// SearchSequencer, SearchUiState,
// searchPanelEmptyMessage
// ui/SearchResultsPanel.kt the controls summary and the empty-state copy
// data/protocol/Message.kt the search kind vocabulary (Protocol.SEARCH_KIND_*)
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// per-kind row text, the in-hand filtering/ordering, the routing target and the
// debounce/stale-token sequencing can be unit-tested without a browser. The DOM
// wiring lives in app.js. Every server-provided string is only ever compared or
// rendered, never parsed as markup; the caller sets it with textContent.
import { stageCountText, parseInstant, formatLocalTimestamp } from "./pipelines.js";
import { artifactKind, artifactKindLabel, humanBytes } from "./artifacts.js";
import { runTimeline } from "./runDetail.js";
// ---------------------------------------------------------------------------
// Kind + sort vocabulary (ui/OmniSearchResults.kt SearchKindFilter/SearchSort)
// ---------------------------------------------------------------------------
/**
* The kind narrowing the search control offers, in the task's order. `value` is
* exactly the server's `SearchRequest.kind` vocabulary
* (internal/protocol/search.go); the empty string is every kind. There is
* deliberately no "prompts" entry: the server has no such kind, so a filter that
* could only ever match nothing is not offered.
*/
export const SEARCH_KINDS = [
{ value: "", label: "All kinds" },
{ value: "pipeline", label: "Pipelines" },
{ value: "run", label: "Runs" },
{ value: "step", label: "Steps" },
{ value: "field", label: "Fields" },
{ value: "artifact", label: "Artifacts" },
{ value: "version", label: "Versions" },
];
/** The default, no-narrowing kind. */
export const DEFAULT_SEARCH_KIND = "";
/** Unquoted, whitespace-delimited t:/type: tokens; last supported token wins.
* Unknown tokens and quoted text stay literal, including their whitespace.
* The selector is a fallback; explicitly changing it removes tokens in the view.
*/
export function parseSearchQuery(value, selectedKind = DEFAULT_SEARCH_KIND) {
const source = String(value ?? "");
let kind = selectedKind;
let hasType = false;
const query = source.replace(/(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+/g, (token) => {
const match = /^(?:t|type):([a-z]+)$/i.exec(token);
const candidate = match?.[1].toLowerCase();
if (!candidate || !SEARCH_KINDS.some((option) => option.value === candidate)) return token;
kind = candidate;
hasType = true;
return "";
});
return { query, kind, hasType };
}
/**
* The orders the search sort control offers. "Relevance" keeps the server's own
* ranking (score, then recency, then a stable kind/target tie-break); "Newest
* first" and "Name" cannot be asked of the server — its search command takes only
* a query, an optional kind and a limit — so they order the results already in
* hand. Every sort is stable: two results that tie keep the server's order.
*/
export const SEARCH_SORTS = [
{ value: "relevance", label: "Relevance" },
{ value: "newest", label: "Newest first" },
{ value: "name", label: "Name" },
];
/** The default, server-order sort. */
export const DEFAULT_SEARCH_SORT = "relevance";
/** The quiet period after the last keystroke before a query is sent. */
export const SEARCH_DEBOUNCE_MS = 250;
/**
* The report for a server that cannot answer `search`: an explicit rejection
* naming an unknown/unsupported command, or an older server's reply without the
* `search_results` payload. Wording is AppViewModel.kt verbatim.
*/
export const SEARCH_UNSUPPORTED =
"This server does not support search. Update the Pipelines server, then try again.";
/** The label for `kind` (`""` = All kinds), tolerating a stale/unknown value. */
export function searchKindLabel(kind) {
return (SEARCH_KINDS.find((option) => option.value === kind) ?? SEARCH_KINDS[0]).label;
}
/** The label for `sort`, tolerating a stale/unknown value. */
export function searchSortLabel(sort) {
return (SEARCH_SORTS.find((option) => option.value === sort) ?? SEARCH_SORTS[0]).label;
}
/**
* The one-line summary of the active filter and order the collapsed controls
* show. The item's browser wording is exactly `{Kind} · {Sort}` — deliberately
* without the Android panel's ` (in hand)` suffix, which is a note about which
* orders run locally rather than a report the browser needs.
*/
export function searchControlsSummary(kind, sort) {
return `${searchKindLabel(kind)} · ${searchSortLabel(sort)}`;
}
// ---------------------------------------------------------------------------
// Row model (ui/OmniSearchResults.kt searchRow / snippetSpans)
// ---------------------------------------------------------------------------
/** The non-blank text, else null — the Android `takeIf { it.isNotBlank() }`. */
function nonBlank(value) {
const text = String(value ?? "");
return text.trim() === "" ? null : text;
}
/** A finite number for a payload field, so a missing value never prints "undefined". */
function num(value) {
const number = Number(value);
return Number.isFinite(number) ? number : 0;
}
/** The non-null, non-empty fragments joined with ` · `; blanks are omitted. */
function joinNonBlank(parts) {
return (parts ?? []).filter((part) => part != null && String(part) !== "").join(" · ");
}
/** Case-insensitive string comparison, matching String.CASE_INSENSITIVE_ORDER for ASCII. */
function compareInsensitive(a, b) {
const x = String(a ?? "").toUpperCase();
const y = String(b ?? "").toUpperCase();
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
/**
* Splits `snippet` into runs so the first case-insensitive occurrence of `query`
* (trimmed) is a distinct, `matched` span. When the query is blank or does not
* appear — a bare status/date query, or a server-trimmed snippet — the whole
* snippet is returned unmatched, so the caller never drops text. An empty
* snippet yields no spans at all. Mirrors OmniSearchResults.snippetSpans.
*/
export function snippetSpans(snippet, query) {
const text = String(snippet ?? "");
if (text === "") return [];
const needle = String(query ?? "").trim();
if (needle === "") return [{ text, matched: false }];
const index = text.toLowerCase().indexOf(needle.toLowerCase());
if (index < 0) return [{ text, matched: false }];
const end = index + needle.length;
const spans = [];
if (index > 0) spans.push({ text: text.slice(0, index), matched: false });
spans.push({ text: text.slice(index, end), matched: true });
if (end < text.length) spans.push({ text: text.slice(end), matched: false });
return spans;
}
/**
* The one-line non-snippet secondary line of a step hit: its outcome, route and
* first non-blank diagnostic line, or `step {sequence}` when all are blank.
* Mirrors OmniSearchResults.stepSecondary.
*/
function stepSecondary(step) {
const diagnostic = String(step?.diagnostic ?? "");
const line = diagnostic.split(/\r?\n/).find((candidate) => candidate.trim() !== "");
const target = nonBlank(step?.target);
const joined = joinNonBlank([
nonBlank(step?.outcome),
target ? `→ ${target}` : null,
line == null ? null : line.trim(),
]);
return joined === "" ? `step ${num(step?.sequence)}` : joined;
}
/**
* One rendered search row: its `title`, its plain `secondary` line and, only for
* a text ("field") match, a `snippet` split into spans so the matched run is
* distinguishable without colour (the caller wraps a matched span in an emphasis
* element). An unknown/absent payload is never dropped: it renders its stable
* target (or a placeholder) and a `read-only` note. Every per-kind rule mirrors
* OmniSearchResults.searchRow, including the Android blank fallbacks.
*/
export function searchRow(hit, query, options = {}) {
const { timeZone } = options;
const pipeline = hit?.pipeline;
const version = hit?.version;
const run = hit?.run;
const step = hit?.step;
const field = hit?.field;
const artifact = hit?.artifact;
if (pipeline) {
return {
title: nonBlank(pipeline.name) ?? `pipeline ${num(pipeline.id)}`,
secondary: `pipeline ${num(pipeline.id)} · v${num(pipeline.version)} · ${stageCountText(pipeline.stages)}`,
snippet: null,
};
}
if (version) {
const hash = nonBlank(version.content_hash);
return {
title: `pipeline ${num(version.pipeline_id)} · v${num(version.version)}`,
secondary: joinNonBlank([
hash ? `content ${hash}` : null,
formatLocalTimestamp(version.created_at, { timeZone }),
]),
snippet: null,
};
}
if (run) {
const name = nonBlank(run.pipeline_name);
return {
title: `run #${num(run.id)}${name ? ` · ${name}` : ""}`,
secondary: joinNonBlank([
nonBlank(run.status),
nonBlank(run.workspace),
formatLocalTimestamp(run.created_at, { timeZone }),
]),
snippet: null,
};
}
if (step) {
return {
title: `run #${num(step.run_id)} · ${nonBlank(step.stage) ?? "step"} visit ${num(step.visit)}`,
secondary: stepSecondary(step),
snippet: null,
};
}
if (field) {
return {
title: `run #${num(field.run_id)} · step ${num(field.sequence)} · ${nonBlank(field.field) ?? "field"}`,
secondary: String(field.snippet ?? ""),
snippet: snippetSpans(field.snippet, query),
};
}
if (artifact) {
return {
title: nonBlank(artifact.name) ?? "artifact",
secondary: joinNonBlank([
`run #${num(artifact.run_id)}`,
`step ${num(artifact.sequence)}`,
nonBlank(artifact.content_type),
humanBytes(artifact.size_bytes),
]),
snippet: null,
};
}
const kind = nonBlank(hit?.kind);
return {
title: nonBlank(hit?.target) ?? "Unrecognised result",
secondary: kind ? `kind "${kind}" · read-only` : "read-only",
snippet: null,
};
}
/**
* The kind in words for a row's accessible description, so a screen reader hears
* what the row is. An artifact is named by its own content type ("Image
* artifact", "JSON artifact"), from the same gallery classification
* searchResultIcon uses. Mirrors OmniSearchResults.searchResultKindLabel.
*/
export function searchResultKindLabel(hit) {
if (hit?.pipeline) return "Pipeline";
if (hit?.version) return "Pipeline version";
if (hit?.run) return "Run";
if (hit?.step) return "Step";
if (hit?.field) return "Field";
if (hit?.artifact) {
return `${artifactKindLabel(artifactKind(hit.artifact.content_type, hit.artifact.name))} artifact`;
}
return "Unrecognised result";
}
// ---------------------------------------------------------------------------
// In-hand narrowing and ordering (SearchResultsPanel.kt SearchResultList)
// ---------------------------------------------------------------------------
/**
* Narrows `results` to `kind`'s kind (`""` = every kind). The kind is also sent
* to the server (`SearchRequest.kind`), so this only re-narrows the results
* already in hand, keeping the panel honest while a narrowed request loads.
*/
export function filterSearchResults(results, kind) {
const list = results ?? [];
if (kind === "" || kind == null) return list;
return list.filter((hit) => hit?.kind === kind);
}
/**
* Orders `results` by `sort`. "Relevance" (and any stale value) leaves the
* server's ranking untouched; "Newest first" orders by parsed recency
* descending, with an unparseable/missing recency last; "Name" orders by the
* displayed title, case-insensitively. Every sort is stable, so ties keep the
* server's order rather than swapping arbitrarily.
*/
export function sortSearchResults(results, sort) {
const list = results ?? [];
if (sort === "newest") {
return [...list].sort((a, b) => {
const ta = parseInstant(a?.recency);
const tb = parseInstant(b?.recency);
const na = ta == null ? -Infinity : ta;
const nb = tb == null ? -Infinity : tb;
if (na === nb) return 0;
return na > nb ? -1 : 1;
});
}
if (sort === "name") {
return [...list]
.map((hit) => ({ hit, title: searchRow(hit, "").title }))
.sort((a, b) => compareInsensitive(a.title, b.title))
.map((entry) => entry.hit);
}
return list;
}
/**
* The empty-state line the panel shows when it has no rows to render for the
* (non-blank) query under `kind`, or null when it is showing rows, progress, an
* error or nothing at all. `shown` is the filtered and sorted list actually
* displayed, so a filter that empties the list reports itself ("No runs match …")
* rather than the generic line. Mirrors searchPanelEmptyMessage.
*
* Android's own copy is the invariant `No {kind} match "{query}".` — the same
* sentence shape the pipeline list already carries in src/pipelines.js — and the
* browser keeps it verbatim.
*/
export function searchPanelEmptyMessage(state, shown, kind) {
if (state?.error) return null;
if ((shown ?? []).length > 0) return null;
if (state?.loading) return null;
const query = String(state?.query ?? "");
if (query.trim() === "") {
if (!state?.loaded || !kind) return null;
const label = searchKindLabel(kind).toLowerCase();
return state?.truncated ? `No ${label} found within the server's scan limit.` : `No ${label} yet.`;
}
if (kind === "" || kind == null) return `No matches for "${query}".`;
return `No ${searchKindLabel(kind).toLowerCase()} match "${query}".`;
}
/**
* Text searches and valid kind-only browsing are sendable. Empty text with no
* supported kind still clears locally, without an all-kind scan.
*/
export function searchQuerySendable(query, kind = "") {
return String(query ?? "").trim() !== "" || SEARCH_KINDS.some((option) => option.value !== "" && option.value === kind);
}
/**
* Whether the panel draws its thin refresh bar: a newer query is loading while
* results are still on screen, so progress is reported above them rather than
* blanking the list. Pure, so "retained results plus progress on a refresh" is
* testable without a browser.
*/
export function searchPanelProgress(state) {
return Boolean(state?.loading) && (state?.results ?? []).length > 0;
}
/**
* The body the panel renders, mirroring SearchResultsPanel's `when` in order: an
* error takes precedence over the results; the filtered/sorted rows when there
* are any; the first-load searching row while nothing has arrived; otherwise the
* empty-state line, or nothing at all (a blank query, or a filter that emptied a
* list while a refresh is in flight). Pure, so every state is unit-testable
* without a browser.
*/
export function searchPanelBody(state, shown, kind) {
if (state?.error) return { kind: "error", message: state.error };
if ((shown ?? []).length > 0) return { kind: "results", message: "" };
// The searching row is the first load only: once any result is retained, a
// refresh reports itself with the progress bar instead of replacing the list.
if (state?.loading && (state?.results ?? []).length === 0) return { kind: "searching", message: "" };
const message = searchPanelEmptyMessage(state, shown, kind);
return message == null ? { kind: "idle", message: "" } : { kind: "empty", message };
}
// ---------------------------------------------------------------------------
// Navigation (ui/OmniSearchResults.kt searchTarget / resolveRunTarget)
// ---------------------------------------------------------------------------
/**
* The navigation a selected search result asks for, or null for a kind with no
* known payload (an unknown match), which is shown read-only rather than dropped.
* A pipeline/version target names the pipeline detail (version 0 = latest); a
* run target names a run, and carries the recorded `sequence` (0 = the plain run
* detail) plus, for a text match, the `matchedField` naming the run-detail tab
* holding the match.
*/
export function searchTarget(hit) {
if (hit?.pipeline) {
return { kind: "pipeline", pipelineId: num(hit.pipeline.id), version: num(hit.pipeline.version) };
}
if (hit?.version) {
return {
kind: "pipeline",
pipelineId: num(hit.version.pipeline_id),
version: num(hit.version.version),
};
}
if (hit?.run) return { kind: "run", runId: num(hit.run.id), sequence: 0, matchedField: "" };
if (hit?.step) {
return { kind: "run", runId: num(hit.step.run_id), sequence: num(hit.step.sequence), matchedField: "" };
}
if (hit?.field) {
// The run-detail tab is chosen from the hit's `matched_field` (the browser
// item's deliberate rule), not from the recorded field name.
return {
kind: "run",
runId: num(hit.field.run_id),
sequence: num(hit.field.sequence),
matchedField: String(hit.matched_field ?? ""),
};
}
if (hit?.artifact) {
return {
kind: "run",
runId: num(hit.artifact.run_id),
sequence: num(hit.artifact.sequence),
matchedField: "",
};
}
return null;
}
/**
* The run-detail tab holding a matched step field's text: `input` -> Input,
* `output` -> Output, anything else (a retired evidence/transcript tab, or an
* unknown field) -> Summary, so no stale hit accidentally selects Timeline.
*/
export function searchFieldTab(matchedField) {
switch (String(matchedField ?? "")) {
case "input":
return "input";
case "output":
return "output";
default:
return "summary";
}
}
/**
* Resolves a run `target` against the loaded run's `steps` into the pane
* selection showing the requested tab or visit. A text match returns the tab
* holding it; a step/artifact target returns the zero-based visit index within
* its stage (the server's visit number need not equal the index); a visit that
* cannot be located — or a bare run target — returns an empty selection, so the
* plain run detail is shown and a hit is never dropped. `runId` is the run the
* target named (kept for parity with the Android signature).
*/
export function resolveRunTarget(target, runId, steps) {
if (!target) return {};
if (String(target.matchedField ?? "").trim() !== "") {
return { tab: searchFieldTab(target.matchedField) };
}
const sequence = num(target.sequence);
if (sequence <= 0) return {};
const list = steps ?? [];
const step = list.find((candidate) => num(candidate?.sequence) === sequence);
if (!step) return {};
const visits = runTimeline(list).visitsByStage.get(step.stage) ?? [];
const index = visits.findIndex((candidate) => num(candidate?.sequence) === sequence);
return { stageKey: step.stage, visitIndex: Math.max(index, 0) };
}
// ---------------------------------------------------------------------------
// Query sequencing: debounce + stale-reply gating
// ---------------------------------------------------------------------------
/**
* The pure ordering behind omni-search.
*
* `edit` records a keystroke and returns the pending edit to debounce; when the
* quiet period elapses the caller passes it to `begin`, which returns the query
* to send only if no newer keystroke arrived — so a burst of keystrokes collapses
* into one request for the last one. Every sent request carries a monotonically
* increasing token and `accepts` is true only for the newest recorded edit, so a
* reply for a superseded query can never overwrite a newer one. Recording an edit
* (a keystroke, or an empty edit when the panel closes) is enough to reject an
* already in-flight reply; no separate cancel is needed.
*/
export class SearchSequencer {
#newest = 0;
edit(query) {
return { token: ++this.#newest, query };
}
begin(edit) {
if (!edit || edit.token !== this.#newest) return null;
return { token: edit.token, query: edit.query };
}
accepts(token) {
return token === this.#newest;
}
}
// ---------------------------------------------------------------------------
// Failure copy (AppViewModel.runSearch)
// ---------------------------------------------------------------------------
/**
* The message for a failed search: the "server cannot search" sentence for a
* missing `search_results` payload (an older server's pong) or a rejection naming
* an unknown/unsupported command, otherwise the server's own text unchanged.
*/
export function searchFailureText(error) {
if (error == null) return SEARCH_UNSUPPORTED;
const message = (error instanceof Error ? error.message : String(error)).trim();
if (message === "") return SEARCH_UNSUPPORTED;
if (/\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b/i.test(message)) {
return SEARCH_UNSUPPORTED;
}
return message;
}
-107
View File
@@ -1,107 +0,0 @@
// Server-URL validation mirroring android/.../data/transport/ServerUrl.kt and
// internal/client/config.go: only ws/wss with a non-empty hostname and no
// userinfo/fragment. The endpoint path defaults to /connect, matching
// internal/server/websocket.go `GET /connect`.
export const ServerUrlKind = Object.freeze({
EMPTY: "EMPTY",
MALFORMED: "MALFORMED",
UNSUPPORTED_SCHEME: "UNSUPPORTED_SCHEME",
MISSING_HOST: "MISSING_HOST",
USER_INFO: "USER_INFO",
FRAGMENT: "FRAGMENT",
});
/**
* @returns {{valid:true, wsUrl:string, httpUrl:string, host:string, port:number, secure:boolean}
* |{valid:false, kind:string, message:string}}
*/
export function validateServerUrl(raw) {
const trimmed = (raw ?? "").trim();
if (!trimmed) {
return {
valid: false,
kind: ServerUrlKind.EMPTY,
message:
"Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect",
};
}
let url;
try {
url = new URL(trimmed);
} catch {
return {
valid: false,
kind: ServerUrlKind.MALFORMED,
message: "That is not a valid URL.",
};
}
const scheme = url.protocol.replace(/:$/, "").toLowerCase();
if (scheme !== "ws" && scheme !== "wss") {
return {
valid: false,
kind: ServerUrlKind.UNSUPPORTED_SCHEME,
message: `Unsupported scheme "${scheme}"; use ws:// (trusted LAN/VPN) or wss://`,
};
}
if (url.username || url.password) {
return {
valid: false,
kind: ServerUrlKind.USER_INFO,
message:
"Credentials are not supported; the server has no authentication. Remove userinfo from the URL",
};
}
if (url.hash) {
return {
valid: false,
kind: ServerUrlKind.FRAGMENT,
message: "Remove the # fragment; it is not part of the server endpoint",
};
}
if (!url.hostname) {
return {
valid: false,
kind: ServerUrlKind.MISSING_HOST,
message:
"The URL is missing a host, for example ws://192.168.1.20:8081/connect",
};
}
const secure = scheme === "wss";
const port = url.port ? Number(url.port) : secure ? 443 : 80;
let path = url.pathname || "";
if (!path || path === "/") path = "/connect";
const authority = url.host; // host + explicit port only when present
const search = url.search || "";
const wsUrl = `${scheme}://${authority}${path}${search}`;
const httpUrl = `${secure ? "https" : "http"}://${authority}${path}${search}`;
return { valid: true, wsUrl, httpUrl, host: url.hostname, port, secure };
}
/**
* Resolves a server-relative artifact url (for example "/artifacts/55/4/shot.png")
* against the configured server URL by mapping ws/wss to http/https and dropping
* the /connect path. Never hardcodes a host: a blank or invalid configuration, or
* a blank path, yields null so the UI can disable actions. An already-absolute
* http(s) url is returned unchanged. Mirrors ServerUrl.resolveArtifactUrl.
*/
export function resolveArtifactUrl(configured, artifactUrl) {
const relative = (artifactUrl ?? "").trim();
if (!relative) return null;
if (relative.startsWith("http://") || relative.startsWith("https://")) {
return relative;
}
const validated = validateServerUrl(configured);
if (!validated.valid) return null;
const { secure, host, port } = validated;
const defaultPort = secure ? 443 : 80;
const authority = port && port !== defaultPort ? `${host}:${port}` : host;
const origin = `${secure ? "https" : "http"}://${authority}`;
const path = relative.startsWith("/") ? relative : `/${relative}`;
return origin + path;
}
-215
View File
@@ -1,215 +0,0 @@
// The Settings destination's pure logic and copy (L1): the exact strings the
// Android SettingsScreen.kt shows, the workspace-path validation rules
// (AppViewModel.validateWorkspace), the connection status card's lines, and the
// two localStorage keys that stand in for SettingsRepository's preferences.
//
// Deliberately free of DOM, sockets and timers, so every branch is unit-testable
// in Node and renders identically in the page. Wording authority:
// ui/screens/SettingsScreen.kt — the fields, helper lines, warning, status card
// and the TrustWarning / Templates row
// ui/AppViewModel.kt — validateWorkspace / saveWorkspace
// data/SettingsRepository.kt — the two persisted preferences (server URL, workspace)
// ui/screens/SettingsScreen.kt — the ConnectionStatusCard's connected build line
//
// The Android store persists the server URL and the workspace under `server_url`
// and `workspace`; the browser's analogue is localStorage. Only these two keys
// are ever written — never a credential, because the server has no authentication.
import { connectingLabel, serverBuildLabel } from "./connection.js";
/**
* The persisted server-URL key. It is the browser analogue of
* SettingsRepository's `KEY_SERVER_URL` and the single source of truth the page
* already used (`app.js`); kept here so the module owns both settings keys.
*/
export const SERVER_URL_STORAGE_KEY = "pipelines.web.serverUrl.v2";
/** The persisted workspace key (SettingsRepository's `KEY_WORKSPACE` analogue). */
export const WORKSPACE_STORAGE_KEY = "pipelines.web.workspace.v1";
/** Server-URL field copy, verbatim from SettingsScreen.kt. */
export const SERVER_URL_PLACEHOLDER = "ws://192.168.1.20:8081/connect";
export const SERVER_URL_HELPER =
"ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. No authentication is used.";
/** Workspace field copy, verbatim from SettingsScreen.kt. */
export const WORKSPACE_PLACEHOLDER = "/Users/you/repos/pipelines";
export const WORKSPACE_HELPER =
"An absolute directory that already exists on the execution server. For Docker, " +
"mount the host directory at the same absolute path with its owner's UID/GID. " +
"This is not the phone's storage.";
/** The one workspace validation failure, verbatim from AppViewModel.validateWorkspace. */
export const WORKSPACE_ERROR =
"The workspace must be an absolute path that exists on the execution server.";
/** The trusted-network warning, verbatim from SettingsScreen.kt's TrustWarning. */
export const TRUST_TITLE = "Trusted LAN/VPN only";
export const TRUST_BODY =
"The Pipelines API has no authentication and is not internet-safe. Do not " +
"expose it to untrusted networks, and never enter provider credentials here \u2014 " +
"the app stores none.";
/** The templates entry, verbatim from SettingsScreen.kt. */
export const TEMPLATES_CARD_LABEL = "Browse templates";
export const TEMPLATES_CARD_SECONDARY = "Reusable pipeline definitions offered by the server.";
/**
* AppViewModel.validateWorkspace: a blank draft is not an error (the field is
* simply untouched), a non-absolute path names the failure, an absolute path is
* accepted. Returns the error string or null.
*/
export function validateWorkspacePath(value) {
const trimmed = String(value ?? "").trim();
if (trimmed === "") return null;
if (!trimmed.startsWith("/")) return WORKSPACE_ERROR;
return null;
}
/**
* The supporting text under the workspace field: the validation error when the
* draft is invalid, otherwise the helper line (Android's `workspaceError ?: helper`).
*/
export function workspaceErrorText(value) {
return validateWorkspacePath(value) ?? "";
}
/**
* Whether `Save workspace` is enabled. The page deliberately refuses a blank
* field (there is nothing to save) as well as a relative path, so the only
* enabled state is a trimmed absolute path. This is stricter than Android's
* `workspaceError == null` (which also enables Save on a blank field) and is
* recorded in web/PARITY.md.
*/
export function canSaveWorkspace(value) {
const trimmed = String(value ?? "").trim();
return trimmed !== "" && validateWorkspacePath(trimmed) === null;
}
/** The `Saved workspace:` line (Android's `configuredWorkspace.ifBlank { "(none)" }`). */
export function savedWorkspaceLine(value) {
const trimmed = String(value ?? "").trim();
return `Saved workspace: ${trimmed || "(none)"}`;
}
/**
* Read the persisted workspace. Tolerant and blank-on-unreadable: a missing
* storage, a throwing `getItem` or a non-string value all read as "".
*/
export function readWorkspace(storage) {
try {
const raw = storage?.getItem?.(WORKSPACE_STORAGE_KEY);
return typeof raw === "string" ? raw : "";
} catch {
return "";
}
}
/**
* Persist the workspace trimmed, exactly as SettingsRepository.setWorkspace
* does, and return the stored value so the caller can show the same line. Never
* throws: an unavailable/full storage leaves the in-memory value authoritative.
*/
export function writeWorkspace(storage, value) {
const trimmed = String(value ?? "").trim();
try {
storage?.setItem?.(WORKSPACE_STORAGE_KEY, trimmed);
} catch {
// A read-only or full localStorage must not break saving in memory.
}
return trimmed;
}
/**
* Read the persisted server URL. The same tolerant contract as `readWorkspace`:
* a missing storage, a throwing `getItem` or a non-string value all read as "".
* (The page treats "" as "use the default endpoint", exactly as before.)
*/
export function readServerUrl(storage) {
try {
const raw = storage?.getItem?.(SERVER_URL_STORAGE_KEY);
return typeof raw === "string" ? raw : "";
} catch {
return "";
}
}
/**
* Persist the server URL trimmed, mirroring SettingsRepository.setServerUrl.
* Never throws: an unavailable/full storage leaves the in-memory value
* authoritative. Returns the stored value.
*/
export function writeServerUrl(storage, value) {
const trimmed = String(value ?? "").trim();
try {
storage?.setItem?.(SERVER_URL_STORAGE_KEY, trimmed);
} catch {
// A read-only or full localStorage must not break connecting.
}
return trimmed;
}
/**
* The connection status card's lines, exactly per SettingsScreen.kt's
* ConnectionStatusCard:
* idle -> "Not connected"
* connecting -> "Connecting (attempt N)…"
* connected -> "Connected", the build line when present, "Server time t" when present
* disconnected -> "Disconnected", the message, "Retrying with backoff…" only while retrying
*
* The connecting and build lines reuse `connection.js`, so each sentence has one
* definition shared with the header banner.
*/
export function connectionCard(state, { version, commit, serverTime } = {}) {
const c = state ?? {};
switch (c.kind) {
case "connected": {
const lines = ["Connected"];
const build = serverBuildLabel({ version, commit });
if (build) lines.push(build);
const time = String(serverTime ?? "").trim();
if (time) lines.push(`Server time ${time}`);
return lines;
}
case "connecting":
return [connectingLabel(c.attempt)];
case "disconnected": {
const lines = ["Disconnected"];
const reason = String(c.reason ?? "").trim();
if (reason) lines.push(reason);
if (c.retrying) lines.push("Retrying with backoff\u2026");
return lines;
}
default:
return ["Not connected"];
}
}
/**
* The emphasised primary action and the de-emphasised secondary one, mirroring
* SettingsScreen.kt's `active` branch: while connected (or connecting) the
* meaningful action is Disconnect, otherwise Connect, with Reconnect offered
* while idle/disconnected. The labels are the app's own.
*/
export function connectionActions(state) {
const kind = (state ?? {}).kind;
const active = kind === "connected" || kind === "connecting";
return active
? { primary: "Disconnect", secondary: "Connect" }
: { primary: "Connect", secondary: "Reconnect" };
}
/**
* Which existing client operation an action label drives. The mapping is pure so
* the page cannot accidentally send `Connect` through the header's toggle (which
* disconnects while connected): Android's `AppViewModel.connect()` is
* connect-only, `reconnect()` re-opens the saved endpoint and `disconnect()` is
* the only thing that closes the socket. Returns one of
* `"disconnect" | "reconnect" | "connect"`; anything that is not a known
* disconnect/reconnect label is a connect.
*/
export function connectionActionKind(label) {
if (label === "Disconnect") return "disconnect";
if (label === "Reconnect") return "reconnect";
return "connect";
}
-107
View File
@@ -1,107 +0,0 @@
// The persistent app shell's pure model (L2/L3/L4): the four destinations, the
// roving-tabindex arithmetic shared by the destination and section tablists, the
// compact connection word shown in the rail/dock, and the view -> destination
// mapping. Deliberately DOM-free, so every branch is unit-testable in Node.
//
// The rail is the wide presentation; the bottom dock is the narrow one. Both
// render the same DESTINATIONS model (roles: tablist + tab, aria-current on the
// route as well as aria-selected). Templates stays a route but not a
// destination: it is reached from Settings, the card that owns its entry point.
/** The four destinations, in Android's destination-bar order. */
export const DESTINATIONS = Object.freeze([
Object.freeze({ key: "pipelines", label: "Pipelines", path: "/pipelines", icon: "pipelines" }),
Object.freeze({ key: "runs", label: "Runs", path: "/runs", icon: "runs" }),
Object.freeze({ key: "chat", label: "Chat", path: "/chat", icon: "chat" }),
Object.freeze({ key: "settings", label: "Settings", path: "/settings", icon: "settings" }),
]);
/** The destination key that owns a view. Templates is reached from Settings. */
export function destinationForView(view) {
switch (view) {
case "runs":
return "runs";
case "chat":
return "chat";
case "settings":
case "templates":
return "settings";
default:
return "pipelines";
}
}
/** The index of a destination key in DESTINATIONS (0 for an unknown key). */
export function destinationIndex(key) {
const index = DESTINATIONS.findIndex((item) => item.key === key);
return index < 0 ? 0 : index;
}
/** Roving tabindex: the selected tab is the only stop in its tablist. */
export function rovingTabindex(selectedIndex, index) {
return selectedIndex === index ? "0" : "-1";
}
/**
* The next index after one of the roving-tablist keys, or -1 when the key is not
* one this tablist handles. ArrowLeft/ArrowRight always move (both tablists use
* a horizontal axis in the narrow strip); ArrowUp/ArrowDown are also accepted
* because the wide rail is vertical. Home/End jump to the ends. Movement wraps,
* as WAI-ARIA's tabs pattern recommends.
*/
export function tabIndexForKey(key, index, count, { vertical = false } = {}) {
if (!Number.isInteger(index) || !Number.isInteger(count) || count <= 0 || index < 0 || index >= count) {
return -1;
}
const last = count - 1;
switch (key) {
case "ArrowRight":
return index >= last ? 0 : index + 1;
case "ArrowLeft":
return index <= 0 ? last : index - 1;
case "ArrowDown":
return vertical ? (index >= last ? 0 : index + 1) : -1;
case "ArrowUp":
return vertical ? (index <= 0 ? last : index - 1) : -1;
case "Home":
return 0;
case "End":
return last;
default:
return -1;
}
}
/**
* The compact connection word for the shell status control. It deliberately does
* not repeat the banner's full sentence: the dot's tone carries the state and
* the word always names it, so colour is never the only signal. With no endpoint
* configured, the shell says exactly that instead of asking for a URL (Settings
* is the only place that asks).
*/
export function shellStatus(connection, { hasEndpoint = false } = {}) {
const c = connection ?? {};
switch (c.kind) {
case "connected":
return { text: "Connected", tone: "ok", state: "connected" };
case "connecting":
return { text: "Connecting\u2026", tone: "warn", state: "connecting" };
case "disconnected":
return { text: "Disconnected", tone: "bad", state: "disconnected" };
default:
return hasEndpoint
? { text: "Not connected", tone: "idle", state: "idle" }
: { text: "Not configured", tone: "idle", state: "unconfigured" };
}
}
/**
* The section tabs for the current detail. `tabs` is the model's own
* `{key,label}` list, `active` the selected key. No detail means no tablist.
*/
export function sectionModel(model) {
const tabs = Array.isArray(model?.tabs) ? model.tabs : [];
if (!tabs.length) return { tabs: [], active: -1 };
const active = Math.max(0, tabs.findIndex((tab) => tab.key === model.active));
return { tabs, active };
}
-21
View File
@@ -1,21 +0,0 @@
// Exact source ranges, following internal/pipeline/definition.go's block rules.
// Never reserialize graph fields: defaults and authored spelling differ.
export function stageSource(source, key) {
if (typeof source !== "string") return null;
let active = false;
let start = null;
let offset = 0;
for (const line of source.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
const trim = line.trim();
if (active) {
if (trim === "```") active = false;
} else if (trim.startsWith("# stage ")) {
if (start !== null) return source.slice(start, offset);
if (trim.slice(8).trim() === key) start = offset;
} else if (trim.startsWith("```")) {
active = true;
}
offset += line.length;
}
return start === null ? null : source.slice(start);
}
-62
View File
@@ -1,62 +0,0 @@
// The one status glyph used in list rows: a single coloured icon whose tooltip
// and accessible name say the state. The pill text badge is deliberately gone.
import { h } from "./dom.js";
const NS = "http://www.w3.org/2000/svg";
function iconPath(state) {
switch (state) {
case "succeeded":
return "M5 12.5l4.5 4.5L19 7";
case "failed":
return "M6 6l12 12M18 6L6 18";
case "running":
return "M12 3a9 9 0 1 0 9 9";
case "canceled":
return "M12 3a9 9 0 1 0 0 18M7.5 7.5l9 9";
case "interrupted":
return "M9 6v12M15 6v12";
case "waiting":
case "queued":
return "M12 6v6l4 2";
default:
return "M12 8v8M8 12h8";
}
}
/** `state` is the run status token; `label` is the word a person reads. */
export function statusIcon(state, label = state) {
const tone = String(state ?? "").trim().toLowerCase() || "unknown";
const word = String(label ?? tone);
const span = h("span", {
class: `chip chip-${tone} status-icon status-${tone}`,
role: "img",
title: word,
"aria-label": word,
"data-status": tone,
});
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
if (tone === "waiting" || tone === "queued") {
const circle = document.createElementNS(NS, "circle");
circle.setAttribute("cx", "12");
circle.setAttribute("cy", "12");
circle.setAttribute("r", "9");
circle.setAttribute("fill", "none");
circle.setAttribute("stroke", "currentColor");
circle.setAttribute("stroke-width", "1.8");
svg.append(circle);
}
const path = document.createElementNS(NS, "path");
path.setAttribute("d", iconPath(tone));
path.setAttribute("fill", "none");
path.setAttribute("stroke", "currentColor");
path.setAttribute("stroke-width", "2");
path.setAttribute("stroke-linecap", "round");
path.setAttribute("stroke-linejoin", "round");
svg.append(path);
span.append(svg);
return span;
}
-158
View File
@@ -1,158 +0,0 @@
// Pure Templates derivations, mirroring the Android app's ui/Templates.kt,
// ui/Format.kt and ui/graph/StageDetailPane.kt. No DOM and no protocol here, so
// the gallery/detail wording and the stage-count mapping are unit-tested without
// a browser. Every value returned is plain text (or plain data); the caller sets
// it with textContent and never with innerHTML.
/** A gallery card's name: a blank name is the explicit unnamed-template placeholder. */
export function templateGalleryName(name) {
return (name ?? "").trim() ? name : "(unnamed template)";
}
/** A detail's heading: a blank name falls back to the template's key. */
export function templateDetailName(entry) {
const name = (entry?.name ?? "").trim();
return name ? entry.name : (entry?.key ?? "");
}
/** "1 stage" / "N stages", mirroring ui/Format.kt stageCountText. */
export function stageCountText(count) {
return `${count} ${count === 1 ? "stage" : "stages"}`;
}
/**
* The card's stage-count line: the count parsed from the source, or an explicit
* "unavailable" when the source could not be parsed (never "0 stages", which
* would claim a count the client does not have).
*/
export function templateStageCountLabel(stageCount) {
return stageCount == null ? "stage count unavailable" : stageCountText(stageCount);
}
/** The effective stage type, mirroring internal/stage.EffectiveType: blank is the model stage. */
export function effectiveStageType(type) {
return (type ?? "").trim() ? type : "model";
}
/**
* One gallery card's content: the template's name and description (from the
* catalogue) and its stage count (from the graph the server parsed out of the
* source; null when the source did not parse, so the card says so rather than
* claiming zero stages).
*/
export function templateCard(entry, graph = null) {
return {
key: entry?.key ?? "",
name: entry?.name ?? "",
description: entry?.description ?? "",
stageCount: graph?.stages?.length ?? null,
};
}
/** The unparsed-source note the Summary tab shows instead of a stage list. */
export const TEMPLATE_UNPARSED_SUMMARY_NOTE =
"This template's source could not be parsed, so its stages are not listed. See the Source tab for the raw definition.";
/** The note the Summary tab shows for a parsed template that declares no stages. */
export const TEMPLATE_NO_STAGES_NOTE = "This template has no stages.";
/** The Graph tab's note when the source did not parse. */
export const TEMPLATE_UNPARSED_GRAPH_NOTE =
"This template's source could not be parsed, so there is no graph. The Source tab shows the raw definition.";
/** The Graph tab's note when the source parsed; the graph is the parsed definition. */
export const TEMPLATE_GRAPH_NOTE =
"Pinch to zoom and drag to pan. The graph is the parsed definition; nothing runs.";
/** The Source tab's note when the source did not parse on the server. */
export const TEMPLATE_UNPARSED_SOURCE_NOTE =
"This source could not be parsed on the server; showing the raw definition.";
/**
* The Summary tab's stage section: an explicit [note] and no stages when the
* source did not parse or parsed to nothing, else the stage rows (key + effective
* type). One derivation, so the note and the list can never disagree.
*/
export function templateStageSummary(graph) {
if (graph == null) {
return { note: TEMPLATE_UNPARSED_SUMMARY_NOTE, stages: [] };
}
const stages = graph.stages ?? [];
if (!stages.length) {
return { note: TEMPLATE_NO_STAGES_NOTE, stages: [] };
}
return {
note: null,
stages: stages.map((stage) => ({ key: stage.key, type: effectiveStageType(stage.type) })),
};
}
/** The Graph tab's note: the unparsed note when there is no graph, else the parsed-definition note. */
export function templateGraphNote(graph) {
return graph == null ? TEMPLATE_UNPARSED_GRAPH_NOTE : TEMPLATE_GRAPH_NOTE;
}
// --- Create a pipeline from this template (P5) -----------------------------
// The wording, verbatim from android/.../TemplateDetailScreen.kt's
// CreateFromTemplateDialog. The dialog validates the template's source first,
// then submits it create-only; nothing runs and an existing name is never
// overwritten.
/** The template-detail action that opens the create dialog. */
export const CREATE_ACTION_LABEL = "Create pipeline from this template";
/** The dialog's single required field label. */
export const CREATE_NAME_LABEL = "New pipeline name (required)";
/** The dialog's explanatory note (verbatim; states that nothing runs). */
export const CREATE_NOTE =
"Creates a new draft pipeline on the server from this template's source; it is not run.";
/** The confirm button's idle label. */
export const CREATE_CONFIRM = "Create";
/** The confirm button's in-flight label. */
export const CREATE_SENDING = "Creating…";
/** The dismiss button's label before a success. */
export const CREATE_CANCEL = "Cancel";
/** The dismiss button's label after a success. */
export const CREATE_CLOSE = "Close";
/** The dialog's title: `Create from {name}`, a blank name falling back to the key. */
export function createFormTitle(entry) {
return `Create from ${templateDetailName(entry)}`;
}
/**
* Whether the dialog can submit: not while sending, not once a pipeline has
* been created, and never with a blank (or whitespace-only) name.
*/
export function createFormValid(name, { sending = false, created = null } = {}) {
return !sending && created == null && String(name ?? "").trim() !== "";
}
/** The confirm button's label: "Creating…" while in flight, else "Create". */
export function createConfirmLabel(sending) {
return sending ? CREATE_SENDING : CREATE_CONFIRM;
}
/** The dismiss button's label: "Close" once a pipeline was created, else "Cancel". */
export function createDismissLabel(created) {
return created != null ? CREATE_CLOSE : CREATE_CANCEL;
}
/** The dialog's success line: `Created "{name}". It is in the Pipelines list.` */
export function createSuccessMessage(created) {
return `Created "${created}". It is in the Pipelines list.`;
}
/**
* The name to report after a successful submit: the created pipeline's own name
* when the server returned one, else the name the operator submitted (trimmed),
* mirroring `created = it.name.ifBlank { name.trim() }`.
*/
export function createdPipelineName(detail, submittedName) {
return String(detail?.name ?? "").trim() || String(submittedName ?? "").trim();
}
-383
View File
@@ -1,383 +0,0 @@
// The header attention bell and the "Needs you" sheet, plus the notification
// ledger's frame observer. Pure ordering/labels live in attention.js; this module
// owns only the DOM and the page's dismissal state.
import { h } from "../dom.js";
import {
ATTENTION_STORAGE_KEY,
AttentionKind,
attentionBadgeLabel,
attentionDismiss,
attentionDismissAll,
attentionDismissalSnapshot,
attentionEntries,
attentionRowDescription,
startOfLocalDay,
decodeAttentionDismissals,
encodeAttentionDismissals,
} from "../attention.js";
import { NOTIFY_STORAGE_KEY, decodeNotificationSettings, encodeNotificationSettings } from "../notify.js";
import { stateGlyph } from "../runDetail.js";
/** The dismissed identities from storage at boot; anything unreadable is empty. */
export function loadAttentionDismissed() {
try {
return decodeAttentionDismissals(localStorage.getItem(ATTENTION_STORAGE_KEY));
} catch {
return new Set();
}
}
/** The asked flag from storage at boot; anything unreadable means never asked. */
export function loadNotifyAsked() {
try {
return decodeNotificationSettings(localStorage.getItem(NOTIFY_STORAGE_KEY)).asked;
} catch {
return false;
}
}
export function createAttentionView(rt) {
const { state, attentionLayer, runAlerts, modal } = rt;
const render = (...args) => rt.render(...args);
const selectRun = (...args) => rt.selectRun(...args);
/**
* The monochrome outlined bell for the Runs heading: an inline SVG stroked with
* `currentColor` so it follows the button's text colour instead of the colour
* emoji's fixed yellow. Decorative — the button's `aria-label` carries the name.
*/
function attentionBellIcon() {
const NS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("class", "attention-bell-icon");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
for (const d of ["M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9", "M10.3 21a1.94 1.94 0 0 0 3.4 0"]) {
const path = document.createElementNS(NS, "path");
path.setAttribute("d", d);
path.setAttribute("fill", "none");
path.setAttribute("stroke", "currentColor");
path.setAttribute("stroke-width", "1.7");
path.setAttribute("stroke-linecap", "round");
path.setAttribute("stroke-linejoin", "round");
svg.append(path);
}
return svg;
}
/**
* The attention bell action, shown in the Runs list heading (R15). Its
* accessible name comes from `attentionBadgeLabel`; the visible badge is drawn
* only when something genuinely needs the operator, and the count comes from the
* same pure model the sheet reads.
*/
function renderAttentionBell() {
const count = attentionCount();
const label = attentionBadgeLabel(count);
const button = h("button", {
id: "attentionBell",
class: "attention-bell",
type: "button",
"aria-label": label,
title: label,
onclick: openAttentionSheet,
});
button.append(attentionBellIcon());
if (count > 0) {
button.append(
h("span", {
class: "attention-badge",
"aria-hidden": "true",
"data-count": String(count),
text: String(count),
}),
);
}
return button;
}
/** The number of entries the attention surface currently holds. */
function attentionCount() {
return attentionEntries(state.runs, state.attentionDismissed, { since: startOfLocalDay() }).length;
}
/**
* Update the bell in place after the run list (which the surface derives from)
* loads, without rebuilding the header and disturbing the URL field.
*/
function refreshAttentionBell() {
const count = attentionCount();
const label = attentionBadgeLabel(count);
const button = document.querySelector("#attentionBell");
if (button) {
button.setAttribute("aria-label", label);
button.title = label;
let badge = button.querySelector(".attention-badge");
if (count > 0) {
if (!badge) {
badge = h("span", { class: "attention-badge", "aria-hidden": "true" });
button.append(badge);
}
badge.dataset.count = String(count);
badge.textContent = String(count);
} else if (badge) {
badge.remove();
}
}
// The Runs destination mirrors the same count, so an operator on any surface
// can see that something needs attention without first opening Runs.
for (const destinationBadge of document.querySelectorAll("[data-attention-badge]")) {
destinationBadge.hidden = count <= 0;
destinationBadge.textContent = count > 0 ? String(count) : "";
}
}
// --- Attention / "Needs you" surface (R15) ---------------------------------
/**
* The attention sheet: the ordered list from the pure `attentionEntries` model,
* opened from the bell in the Runs heading. It is a single managed dialog — Escape,
* a backdrop click and the Close button all close it — with the exact app
* wording: title `Needs you`, rows of status icon + the run label + the
* `{pipeline} · {detail}` line + a trailing `Dismiss`, and the empty state
* `Nothing needs you right now.` with no Clear all.
*
* `state.attentionSnapshot` is captured only when the sheet opens and kept until
* it closes, so Clear all acts on what the operator actually saw and an entry
* that arrives while it is open is shown but not cleared.
*/
function renderAttentionSheet() {
if (!state.attentionSheetOpen) {
attentionLayer.replaceChildren();
modal.close("attention-sheet");
return;
}
const entries = attentionEntries(state.runs, state.attentionDismissed, { since: startOfLocalDay() });
const overlay = h("div", {
class: "attention-sheet",
role: "dialog",
"aria-modal": "true",
"aria-label": "Needs you",
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeAttentionSheet();
});
const head = h(
"div",
{ class: "attention-sheet-head" },
h("h2", { class: "attention-sheet-title", text: "Needs you" }),
h("button", {
class: "attention-sheet-close",
type: "button",
text: "Close",
onclick: () => closeAttentionSheet(),
}),
);
const body = h("div", { class: "attention-sheet-body" });
// One count for the whole open sheet: only repeated labels need the run id
// appended, so dismissing stays unambiguous without noisy names elsewhere.
const labelCounts = new Map();
for (const entry of entries) {
labelCounts.set(entry.label, (labelCounts.get(entry.label) ?? 0) + 1);
}
if (entries.length === 0) {
body.append(h("p", { class: "attention-empty", text: "Nothing needs you right now." }));
} else {
body.append(
h("button", {
class: "attention-clear",
type: "button",
text: "Clear all",
onclick: clearAttentionSheet,
}),
);
for (const entry of entries) body.append(renderAttentionRow(entry, labelCounts));
}
const sheet = h("div", { class: "attention-sheet-panel", tabindex: "-1" }, head, body);
overlay.append(sheet);
attentionLayer.replaceChildren(overlay);
modal.open("attention-sheet", overlay, {
history: false,
// The sheet is rebuilt by renderAttentionSheet, not by renderContent's
// staged set, so it is managed imperatively rather than reconciled away.
renderManaged: false,
onClose: () => closeAttentionSheet(),
triggerSelector: "#attentionBell",
fallbackSelectors: ["#listTitle", "#pane-main"],
});
}
/** One attention row: status icon, the two text lines, and a trailing Dismiss. */
function renderAttentionRow(entry, labelCounts = null) {
const glyphState = entry.kind === AttentionKind.Decision ? "waiting" : "failed";
const repeated = (labelCounts?.get(entry.label) ?? 0) > 1;
const dismissLabel = repeated
? `Dismiss ${entry.label} (run ${entry.runId})`
: `Dismiss ${entry.label}`;
const open = h(
"button",
{
class: "attention-row-open",
type: "button",
"data-run-id": String(entry.runId),
"data-kind": entry.kind.name.toLowerCase(),
onclick: () => activateAttentionEntry(entry),
},
h("span", {
class: `attention-icon chip-${glyphState}`,
"aria-hidden": "true",
text: stateGlyph(glyphState),
}),
h(
"span",
{ class: "attention-text" },
h("span", { class: "attention-label", text: entry.label }),
h("span", { class: "attention-desc", text: attentionRowDescription(entry) }),
),
);
const dismiss = h("button", {
class: "attention-dismiss",
type: "button",
"aria-label": dismissLabel,
title: dismissLabel,
onclick: (event) => {
// The trailing control must never activate the row it sits in.
event.stopPropagation();
dismissAttentionEntries([entry]);
},
});
dismiss.append(h("span", { "aria-hidden": "true", text: "\u2715" }));
return h("div", { class: "attention-row", "data-key": entry.key }, open, dismiss);
}
/** Open the sheet, capturing the dismissal snapshot it will act on. */
function openAttentionSheet() {
state.attentionSheetOpen = true;
state.attentionSnapshot = attentionDismissalSnapshot(
attentionEntries(state.runs, state.attentionDismissed, { since: startOfLocalDay() }),
);
render();
}
/** Close the sheet, dropping the snapshot; the controller returns focus to the bell. */
function closeAttentionSheet({ restoreFocus = true } = {}) {
if (!state.attentionSheetOpen) return;
state.attentionSheetOpen = false;
state.attentionSnapshot = null;
// The sheet is managed imperatively (renderManaged: false), so the controller
// must be told it closed; otherwise it stays on the stack and the app root is
// left inert, which silently swallows every real click. Focus moves after the
// repaint, since the close re-renders the surface the trigger lives in.
modal.close("attention-sheet", { restoreFocus: false });
render();
if (restoreFocus) document.getElementById("attentionBell")?.focus();
}
/** Dismiss one or more entries for good, persisting the identity set. */
function dismissAttentionEntries(entries) {
if (!entries?.length) return;
let next = new Set(state.attentionDismissed);
for (const entry of entries) next = attentionDismiss(next, entry.key);
persistAttentionDismissed(next);
render();
}
/** Clear all applies only the identities captured when the sheet opened. */
function clearAttentionSheet() {
const snapshot = state.attentionSnapshot ?? [];
const next = attentionDismissAll(state.attentionDismissed, snapshot);
persistAttentionDismissed(next);
render();
}
/**
* Activating a row closes the sheet and opens the run. A Failed row is dismissed
* first (opening it is the operator dealing with it); a Decision row is not —
* only answering the decision clears it.
*/
function activateAttentionEntry(entry) {
if (entry.kind === AttentionKind.Failed) {
persistAttentionDismissed(attentionDismiss(state.attentionDismissed, entry.key));
}
state.attentionSheetOpen = false;
state.attentionSnapshot = null;
state.view = "runs";
render();
selectRun(entry.runId);
}
/** Store the dismissed identities as one JSON array under one localStorage key. */
function persistAttentionDismissed(next) {
state.attentionDismissed = next;
try {
localStorage.setItem(ATTENTION_STORAGE_KEY, encodeAttentionDismissals(next));
} catch {
// Storage disabled or full: the in-memory set still applies for this session.
}
}
/**
* Fold one pushed `run_event` frame into the notification ledger (L5). It does
* not touch the runs list (R10's fold is separate); it only decides whether this
* transition raises exactly one notification. A run already failed/waiting when
* seeded, a duplicate frame, a non-qualifying status and a key the operator
* dismissed all produce nothing.
*/
function onRunAlertFrame(frame) {
const alert = runAlerts.observe(frame, { dismissed: state.attentionDismissed });
if (!alert || !notificationsAllowed()) return;
try {
const notification = new Notification(alert.title, { body: alert.body, tag: alert.key });
notification.onclick = () => {
window.focus();
state.view = "runs";
render();
selectRun(alert.runId);
};
} catch {
// Some browsers can throw even with permission granted; the in-page Needs
// you surface remains the only honest channel and nothing is faked.
}
}
/** True only when a real browser notification can be constructed right now. */
function notificationsAllowed() {
return (
typeof globalThis.Notification === "function" &&
globalThis.isSecureContext === true &&
globalThis.Notification.permission === "granted"
);
}
/** Persist only the asked flag; never a permission claim, endpoint or credential. */
function persistNotifyAsked(asked) {
state.notifyAsked = Boolean(asked);
try {
localStorage.setItem(NOTIFY_STORAGE_KEY, encodeNotificationSettings({ asked }));
} catch {
// Storage disabled or full: the in-memory flag still applies for this session.
}
}
return {
renderAttentionBell,
attentionCount,
refreshAttentionBell,
renderAttentionSheet,
openAttentionSheet,
closeAttentionSheet,
dismissAttentionEntries,
clearAttentionSheet,
activateAttentionEntry,
persistAttentionDismissed,
persistNotifyAsked,
onRunAlertFrame,
notificationsAllowed,
};
}
File diff suppressed because it is too large Load Diff
-969
View File
@@ -1,969 +0,0 @@
// Full-screen and modal dialogs owned by the run detail and chat surfaces:
// the rendered/raw diff viewer, the artifact viewer, the human-decision sheet,
// the shared cancel/retry confirm and the shared Action-failed report.
import { backChevronIcon, h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact, artifactBrowserLinkProps } from "../dom.js";
import { changeKindTone, describeError } from "../format.js";
import { definitionDocument } from "./stageDefinition.js";
import {
BINARY_DIFF_MESSAGE,
NO_LINE_CHANGES_MESSAGE,
TRUNCATED_PATCH_NOTE,
changeKindTitle,
changePositionLabel,
changeStat,
diffLineClass,
diffLineSymbol,
entryHasPatch,
gutterText,
gutterWidth,
parseUnifiedPatch,
patchUnavailableReason,
} from "../changes.js";
import {
ArtifactKind,
artifactKind,
artifactViewerPositionLabel,
isMarkdownArtifact,
pagedIndex,
resolvedArtifactUrl,
} from "../artifacts.js";
import {
ACTION_FAILED_OK,
ACTION_FAILED_TITLE,
CANCEL_CONFIRM,
CANCEL_DIALOG_MESSAGE,
DECISION_CANCEL,
DECISION_CONFIRM,
DECISION_SENDING,
DISMISS_KEEP,
DecisionDraft,
FEEDBACK_LABEL,
RESTART_CONFIRM,
RESTART_DIALOG_MESSAGE,
RETRY_CONFIRM,
RETRY_DIALOG_MESSAGE,
cancelDialogTitle,
decisionSheetMeta,
decisionSheetTitle,
optionTargetText,
restartDialogTitle,
retryDialogTitle,
retryRequestKey,
} from "../actions.js";
export function createDialogsView(rt) {
const { state, repo, modal } = rt;
const renderContent = (...args) => rt.renderContent(...args);
const selectRun = (...args) => rt.selectRun(...args);
let changeViewerOverlay = null;
let changeViewerIndex = null;
let refreshAudit = null;
function refreshStageAudit() { refreshAudit?.(); }
/** Close the diff viewer; the controller returns focus to the viewed row. */
function closeChangeViewer() {
modal.close("change-viewer");
changeViewerIndex = null;
changeViewerOverlay = null;
}
/**
* The full-screen diff viewer for one changed file. It pages through the run's
* changed files exactly as the artifact viewer pages through a gallery's media
* (one shared index, previous/next affordances, Escape/the close button/backdrop
* dismissing), and shows both forms the brief requires, switchable from one
* control row: the **Rendered** reading (each hunk's `@@` header, the shared
* diff line language and the old/new gutter numbers) and the **Raw patch** (the
* server's unified patch verbatim in monospace). A file the server could not
* give a patch for (binary, truncated, or a capture that recorded none) shows the
* honest reason in place of a diff rather than a fabricated one.
*/
function openChangeViewer(files, startIndex, trigger = null) {
closeChangeViewer();
if (!files?.length) return;
let index = Math.min(Math.max(Number(startIndex) || 0, 0), files.length - 1);
let form = "rendered";
const overlay = h("div", {
class: "change-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": "Diff viewer",
});
const panel = h("div", { class: "change-viewer-panel" });
overlay.append(panel);
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeChangeViewer();
});
const renderViewer = () => {
const entry = files[index];
changeViewerIndex = index;
const stat = changeStat(entry.added, entry.removed);
const hasPatch = entryHasPatch(entry);
const titles = h("div", { class: "change-viewer-titles" });
const titleRow = h("div", { class: "change-viewer-title-row" });
titleRow.append(
h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindTitle(entry.kind) }),
);
if (stat !== "") titleRow.append(h("span", { class: "change-viewer-stat monospace", text: stat }));
titles.append(titleRow);
titles.append(h("div", { class: "change-viewer-path monospace", text: entry.path }));
titles.append(
h("div", {
class: "change-viewer-position muted",
text: `${changePositionLabel(index, files.length)} · changed by ${(entry.steps ?? []).join(" → ")}`,
}),
);
const head = h("div", { class: "change-viewer-head" }, titles);
const controls = h(
"div",
{ class: "change-viewer-controls" },
h("button", {
class: `change-form${form === "rendered" ? " active" : ""}`,
type: "button",
"data-form": "rendered",
text: "Rendered",
disabled: form === "rendered",
onclick: () => {
form = "rendered";
renderViewer();
},
}),
h("button", {
class: `change-form${form === "raw" ? " active" : ""}`,
type: "button",
"data-form": "raw",
text: "Raw patch",
disabled: !hasPatch,
onclick: () => {
form = "raw";
renderViewer();
},
}),
h("div", { class: "change-viewer-spacer" }),
h("button", {
class: "change-icon",
type: "button",
"data-action": "copy",
title: "Copy raw patch",
"aria-label": "Copy raw patch",
text: "\u29c9",
disabled: !hasPatch,
onclick: () => copyText(entry.patch ?? ""),
}),
h("button", {
class: "change-icon",
type: "button",
"data-page": "prev",
title: "Previous file",
"aria-label": "Previous file",
text: "\u2039",
disabled: index === 0,
onclick: () => {
index = Math.max(index - 1, 0);
form = "rendered";
renderViewer();
},
}),
h("button", {
class: "change-icon",
type: "button",
"data-page": "next",
title: "Next file",
"aria-label": "Next file",
text: "\u203a",
disabled: index === files.length - 1,
onclick: () => {
index = Math.min(index + 1, files.length - 1);
form = "rendered";
renderViewer();
},
}),
h("button", {
class: "change-icon",
type: "button",
"data-action": "close",
title: "Close diff",
"aria-label": "Close diff",
text: "\u00d7",
onclick: closeChangeViewer,
}),
);
const body = h("div", { class: "change-viewer-body" });
if (entry.binary || !hasPatch) {
body.append(
h("div", {
class: "change-honest muted",
text: entry.binary ? BINARY_DIFF_MESSAGE : patchUnavailableReason(entry),
}),
);
} else if (form === "raw") {
body.append(h("pre", { class: "change-raw monospace", text: entry.patch ?? "" }));
} else {
body.append(renderRenderedDiff(entry));
}
// The toolbar is the first row: paging/copy/close never move when the
// path or the diff length changes.
panel.replaceChildren(controls, head, body);
};
renderViewer();
changeViewerOverlay = overlay;
modal.open("change-viewer", overlay, {
onClose: () => closeChangeViewer(),
trigger,
restore: () =>
changeViewerIndex == null
? null
: document.querySelector(`.change-row[data-change-index="${changeViewerIndex}"]`),
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
}
/** The rendered reading: the stat line, an optional truncation note, each hunk. */
function renderRenderedDiff(entry) {
const wrap = h("div", { class: "change-diff" });
const parsed = parseUnifiedPatch(entry.patch);
const statLine = h("div", { class: "change-diff-stat" });
if (parsed.added > 0) statLine.append(h("span", { class: "stat-add", text: `+${parsed.added}` }));
if (parsed.removed > 0) statLine.append(h("span", { class: "stat-del", text: `-${parsed.removed}` }));
if (parsed.added === 0 && parsed.removed === 0) {
statLine.append(h("span", { class: "muted", text: NO_LINE_CHANGES_MESSAGE }));
}
wrap.append(statLine);
if (entry.truncated) wrap.append(h("div", { class: "change-diff-note muted", text: TRUNCATED_PATCH_NOTE }));
for (const hunk of parsed.hunks) wrap.append(renderHunk(hunk));
return wrap;
}
/**
* One `@@` hunk: its header on a raised surface, then its lines in a
* horizontally scrollable container, each with its old/new gutter numbers (blank
* on the absent side and on a `\ No newline` marker) and the shared
* `{symbol} {text}` coloured by kind.
*/
function renderHunk(hunk) {
const width = gutterWidth(hunk);
const wrap = h("div", { class: "change-hunk" });
wrap.append(h("div", { class: "change-hunk-head", text: hunk.header }));
const lines = h("div", { class: "change-hunk-lines" });
for (const line of hunk.lines) {
const gutter = line.noNewlineMarker
? " ".repeat(width * 2 + 1)
: `${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}`;
lines.append(
h(
"div",
{ class: "change-line" },
h("span", { class: "change-gutter", text: gutter }),
h("span", { class: `change-text ${diffLineClass(line.kind)}`, text: `${diffLineSymbol(line.kind)} ${line.text}` }),
),
);
}
wrap.append(lines);
return wrap;
}
function openDecisionSheet(decision) {
state.runDecision = decision;
state.decisionOpen = true;
state.decisionDraft = new DecisionDraft();
state.decisionError = "";
renderContent();
}
/** Dismiss the decision sheet (never while a decision is in flight). */
function closeDecisionSheet() {
if (state.decisionSending) return;
const wasOpen = state.decisionOpen;
state.decisionOpen = false;
state.runDecision = null;
state.decisionError = "";
state.decisionDraft = new DecisionDraft();
if (!wasOpen) return;
renderContent();
}
/**
* The decision sheet (R11): the waiting stage, the author's recorded
* instructions, one selectable row per option (with its resolved target when
* declared), the optional feedback field and the deliberate confirm. Selecting a
* row never sends; a refusal keeps the sheet open with the server's exact reason.
*/
function renderDecisionSheet(decision) {
const overlay = h("div", {
class: "decision-sheet",
role: "dialog",
"aria-modal": "true",
"aria-label": decisionSheetTitle(decision.stageKey),
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeDecisionSheet();
});
const sheet = h("div", { class: "decision-sheet-panel" });
sheet.append(h("h2", { class: "decision-sheet-title", text: decisionSheetTitle(decision.stageKey) }));
sheet.append(h("div", { class: "decision-sheet-meta muted", text: decisionSheetMeta(decision) }));
if (String(decision.instructions ?? "").trim() !== "") {
sheet.append(h("p", { class: "decision-instructions", text: decision.instructions }));
}
const options = h("div", { class: "decision-options", role: "radiogroup", "aria-label": "Options" });
for (const option of decision.options) {
const selected = state.decisionDraft.selected === option.key;
const row = h("button", {
class: `decision-option${selected ? " selected" : ""}`,
type: "button",
role: "radio",
"aria-checked": selected ? "true" : "false",
"data-option": option.key,
onclick: () => {
state.decisionDraft = state.decisionDraft.select(option.key);
renderContent();
},
});
row.append(h("span", { class: "decision-radio", "aria-hidden": "true" }));
const body = h("span", { class: "decision-option-body" });
body.append(h("span", { class: "decision-option-key", text: option.key }));
const target = optionTargetText(option.target);
if (target !== "") body.append(h("span", { class: "decision-option-target muted", text: target }));
row.append(body);
options.append(row);
}
sheet.append(options);
const field = h("label", { class: "decision-field" });
field.append(h("span", { class: "decision-field-label", text: FEEDBACK_LABEL }));
field.append(
h("input", {
class: "decision-feedback",
type: "text",
value: state.decisionDraft.feedback,
spellcheck: "false",
oninput: (event) => {
state.decisionDraft = state.decisionDraft.withFeedback(event.target.value);
},
}),
);
sheet.append(field);
if (state.decisionError) sheet.append(h("div", { class: "decision-error bad", text: state.decisionError }));
const actions = h("div", { class: "decision-sheet-actions" });
actions.append(
h("button", {
class: "ghost decision-cancel",
type: "button",
text: DECISION_CANCEL,
disabled: state.decisionSending,
onclick: closeDecisionSheet,
}),
);
actions.append(
h("button", {
class: "decision-confirm",
type: "button",
text: state.decisionSending ? DECISION_SENDING : DECISION_CONFIRM,
disabled: !state.decisionDraft.canSubmit || state.decisionSending,
onclick: () => confirmDecision(decision),
}),
);
sheet.append(actions);
overlay.append(sheet);
modal.stage("decision-sheet", overlay, {
onClose: () => closeDecisionSheet(),
triggerSelector: ".decision-card .decision-open",
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return overlay;
}
/** Send the chosen decision; on refusal show the server's reason and re-read. */
async function confirmDecision(decision) {
if (state.decisionSending || !state.decisionDraft.canSubmit) return;
const option = state.decisionDraft.selected;
state.decisionSending = true;
state.decisionError = "";
renderContent();
try {
await repo.decideRun(decision.runId, {
stage: decision.stageKey,
option,
feedback: state.decisionDraft.feedback,
});
state.decisionSending = false;
state.decisionOpen = false;
state.runDecision = null;
state.decisionDraft = new DecisionDraft();
await selectRun(decision.runId, { silent: true });
} catch (error) {
state.decisionSending = false;
state.decisionError = describeError(error);
await selectRun(decision.runId, { silent: true });
}
renderContent();
}
/** Open one of the shared confirm dialogs (cancel / retry / restart). */
function openConfirm(kind) {
state.confirmKind = kind;
renderContent();
}
function dismissConfirm() {
state.confirmKind = null;
renderContent();
}
/**
* The shared confirm dialog: the exact Android title/message for cancel and
* retry (with Keep as the dismiss), plus the browser-only "Restart from start"
* secondary confirm that plainly states the whole-pipeline replay. The dismiss
* button is "Keep".
*/
function renderConfirmDialog(d) {
const kind = state.confirmKind;
if (!kind) return null;
const runId = kind.runId ?? d.id;
let title;
let message;
let confirmLabel;
let secondary = null;
if (kind.kind === "cancel") {
title = cancelDialogTitle(runId);
message = CANCEL_DIALOG_MESSAGE;
confirmLabel = CANCEL_CONFIRM;
} else if (kind.kind === "retry") {
title = retryDialogTitle(runId);
message = RETRY_DIALOG_MESSAGE;
confirmLabel = RETRY_CONFIRM;
secondary = { label: RESTART_CONFIRM, next: { kind: "restart", runId } };
} else {
title = restartDialogTitle(runId);
message = RESTART_DIALOG_MESSAGE;
confirmLabel = RESTART_CONFIRM;
}
const overlay = h("div", {
class: `confirm-dialog confirm-${kind.kind}`,
role: "dialog",
"aria-modal": "true",
"aria-label": title,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) dismissConfirm();
});
const panel = h("div", { class: "confirm-panel" });
panel.append(h("h2", { class: "confirm-title", text: title }));
panel.append(h("p", { class: "confirm-message", text: message }));
const actions = h("div", { class: "confirm-actions" });
if (secondary) {
actions.append(
h("button", {
class: "ghost confirm-secondary",
type: "button",
text: secondary.label,
onclick: () => openConfirm(secondary.next),
}),
);
}
actions.append(
h("button", {
class: "ghost confirm-dismiss",
type: "button",
text: DISMISS_KEEP,
onclick: dismissConfirm,
}),
);
actions.append(
h("button", {
class: "confirm-accept",
type: "button",
text: confirmLabel,
onclick: () => acceptConfirm(kind),
}),
);
panel.append(actions);
overlay.append(panel);
modal.stage("confirm", overlay, {
onClose: () => dismissConfirm(),
triggerSelector:
kind.kind === "cancel" ? ".run-actions .cancel-run" : ".run-actions .retry-run",
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return overlay;
}
/**
* Run the confirmed action, then a silent get_run refresh — exactly as the
* Android client does. A server refusal is reported through the one shared
* Action-failed dialog.
*/
async function acceptConfirm(kind) {
const runId = kind.runId ?? state.runDetail?.id;
state.confirmKind = null;
renderContent();
try {
if (kind.kind === "cancel") {
await repo.cancelRun(runId);
} else {
const mode = kind.kind === "restart" ? "restart" : "resume";
await repo.retryRun(runId, { mode, requestKey: retryRequestKey(runId) });
}
} catch (error) {
state.actionError = describeError(error);
}
await selectRun(runId, { silent: true });
renderContent();
}
/** The one shared "Action failed" dialog (title, the server's message, OK). */
function renderActionFailedDialog() {
const overlay = h("div", {
class: "action-failed",
role: "dialog",
"aria-modal": "true",
"aria-label": ACTION_FAILED_TITLE,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) dismissActionError();
});
const panel = h("div", { class: "action-failed-panel" });
panel.append(h("h2", { class: "action-failed-title", text: ACTION_FAILED_TITLE }));
panel.append(h("p", { class: "action-failed-message", text: state.actionError }));
panel.append(
h("button", { class: "action-failed-ok", type: "button", text: ACTION_FAILED_OK, onclick: dismissActionError }),
);
overlay.append(panel);
modal.stage("action-error", overlay, {
onClose: () => dismissActionError(),
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
});
return overlay;
}
function dismissActionError() {
state.actionError = "";
renderContent();
}
let viewerOverlay = null;
let viewerSession = null;
/** Close the full-screen viewer; the controller returns focus to its trigger. */
function closeArtifactViewer() {
if (viewerSession) {
viewerSession.closed = true;
viewerSession.abort?.abort();
viewerSession = null;
}
modal.close("artifact-viewer");
viewerOverlay = null;
}
/**
* Open the full-screen viewer at `startIndex` into `viewable`, the same ordered
* list the grid drew (images, videos and markdown/text documents). Previous/Next
* are disabled at the ends; ArrowLeft/ArrowRight page the same list; Escape and a
* click on the dimmed backdrop close it, while clicks inside the panel never do.
* Nothing autoplays: a video shows a still poster placeholder instead.
*
* Markdown and text artifacts are fetched once per viewer session from the
* resolved artifact URL and rendered with the page's own markdown renderer,
* building DOM nodes (never innerHTML). A failed fetch or render keeps the
* viewer honest: it shows describeError's message, the resolved-external action
* and the normal Open/Copy/Share actions.
*/
function openArtifactViewer(viewable, startIndex, trigger = null) {
closeArtifactViewer();
if (!viewable?.length) return;
let index = pagedIndex(startIndex, 0, viewable.length);
const session = {
closed: false,
generation: 0,
abort: null,
cache: new Map(),
errors: new Map(),
};
const overlay = h("div", {
class: "artifact-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": "Artifact viewer",
});
const panel = h("div", { class: "viewer-panel", "data-viewer-focus": "panel", tabindex: "-1" });
overlay.append(panel);
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeArtifactViewer();
});
/** The focus key of the control inside the panel that currently owns focus. */
const focusedKey = () => {
const active = document.activeElement;
if (!panel.contains(active)) return null;
return active?.getAttribute?.("data-viewer-focus") ?? null;
};
/** Keep focus inside the viewer after the panel is rebuilt. */
const restoreFocus = (key) => {
if (!key) return;
const target =
key === "panel" ? panel : panel.querySelector(`[data-viewer-focus="${key}"]`);
if (target && !target.disabled) target.focus({ preventScroll: true });
else panel.focus({ preventScroll: true });
};
const step = (delta) => {
const next = pagedIndex(index, delta, viewable.length);
if (next === index) return;
index = next;
renderViewer({ restore: true });
};
overlay.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
step(-1);
} else if (event.key === "ArrowRight") {
event.preventDefault();
step(1);
}
});
const renderViewer = ({ restore = false } = {}) => {
const keepFocus = restore ? focusedKey() : null;
const generation = ++session.generation;
const artifact = viewable[index] ?? {};
const resolved = resolvedArtifactUrl(artifact, state.url);
const kind = artifactKind(artifact.content_type, artifact.name);
const markdown = isMarkdownArtifact(artifact.content_type, artifact.name);
const name = artifact.name || "(unnamed artifact)";
const board = h("div", { class: "viewer-board" });
if (kind === ArtifactKind.Image && resolved) {
board.append(h("img", { class: "viewer-image", src: resolved, alt: name }));
} else if (kind === ArtifactKind.Video) {
board.append(
h(
"div",
{ class: "viewer-placeholder" },
h("span", { class: "artifact-play", text: "▶" }),
h("span", { class: "viewer-placeholder-name", text: name }),
),
);
} else if (markdown) {
board.classList.add("viewer-board-document");
const renderMarkdown = rt.views?.chat?.renderMarkdown;
const showFailure = (message) => {
const error = h("div", { class: "viewer-error" });
error.append(h("div", { class: "viewer-error-message", text: message }));
if (resolved) {
error.append(
h("a", {
class: "viewer-external",
...artifactBrowserLinkProps(resolved),
text: `Open ${name} externally`,
}),
);
}
board.append(error);
};
const draw = (text) => {
try {
const article = h("div", { class: "viewer-markdown" });
article.append(renderMarkdown(text));
board.append(article);
return true;
} catch (error) {
showFailure(describeError(error));
return false;
}
};
if (!resolved) {
showFailure("Set the server URL in Settings to open this artifact.");
} else if (session.cache.has(resolved)) {
draw(session.cache.get(resolved));
} else if (session.errors.has(resolved)) {
showFailure(session.errors.get(resolved));
} else if (typeof renderMarkdown !== "function") {
showFailure("Markdown rendering is unavailable.");
} else {
board.append(h("div", { class: "viewer-loading muted", text: "Loading markdown…" }));
session.abort?.abort();
const controller = new AbortController();
session.abort = controller;
(async () => {
try {
const response = await fetch(resolved, { signal: controller.signal });
if (!response.ok) throw new Error(`The server answered ${response.status}.`);
const text = await response.text();
if (session.closed || generation !== session.generation) return;
session.cache.set(resolved, text);
renderViewer({ restore: true });
} catch (error) {
if (error?.name === "AbortError" || session.closed || generation !== session.generation) return;
session.errors.set(resolved, describeError(error));
renderViewer({ restore: true });
}
})();
}
} else {
board.append(
h(
"div",
{ class: "viewer-placeholder" },
h("span", { class: "artifact-play", text: "▶" }),
h("span", { class: "viewer-placeholder-name", text: name }),
),
);
}
const head = h(
"div",
{ class: "viewer-head" },
h("div", { class: "viewer-title", text: name }),
h("div", {
class: "viewer-position muted",
text: artifactViewerPositionLabel(index, viewable.length, artifact.content_type),
}),
);
const actions = h("div", { class: "viewer-actions" });
// Where this file came from: a run's evidence is only interpretable next to
// the run, so the viewer offers the trip back without closing on a guess.
const runId = Number(artifact.run_id ?? state.selectedRunId ?? 0);
if (Number.isFinite(runId) && runId > 0) {
actions.append(
h("button", {
class: "viewer-action",
type: "button",
"data-viewer-focus": "run",
text: `Open run ${runId}`,
onclick: () => {
closeArtifactViewer();
selectRun(runId);
},
}),
);
}
if (resolved) {
actions.append(
h("a", {
class: "viewer-action browser-button",
...artifactBrowserLinkProps(resolved),
"data-viewer-focus": "open",
text: "Open in browser",
}),
h("button", {
class: "viewer-action",
type: "button",
"data-viewer-focus": "copy",
text: "Copy link",
disabled: !canCopyLink(),
onclick: () => copyArtifactLink(resolved),
}),
h("button", {
class: "viewer-action",
type: "button",
"data-viewer-focus": "share",
text: "Share",
disabled: !canShare(),
title: canShare() ? "Share file" : "File sharing is not supported in this browser",
onclick: (event) => shareArtifact(resolved, artifact, event.currentTarget),
}),
);
}
actions.append(
h("button", {
class: "viewer-action viewer-close",
type: "button",
"data-viewer-focus": "close",
text: "Close viewer",
onclick: closeArtifactViewer,
}),
);
const nodes = [head, board];
if (viewable.length > 1) {
nodes.push(
h(
"div",
{ class: "viewer-nav" },
h("button", {
class: "viewer-page",
type: "button",
"data-viewer-focus": "prev",
text: "Previous artifact",
disabled: pagedIndex(index, -1, viewable.length) === index,
onclick: () => step(-1),
}),
h("button", {
class: "viewer-page",
type: "button",
"data-viewer-focus": "next",
text: "Next artifact",
disabled: pagedIndex(index, 1, viewable.length) === index,
onclick: () => step(1),
}),
),
);
}
nodes.push(actions);
panel.replaceChildren(...nodes);
if (restore) restoreFocus(keepFocus ?? "panel");
};
renderViewer();
viewerOverlay = overlay;
viewerSession = session;
modal.open("artifact-viewer", overlay, {
onClose: () => closeArtifactViewer(),
trigger,
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
}
/** Graph inspection reuses the audit viewer without touching pane/route state. */
function openStageDefinition(detail, stageKey, subtitle = "") {
openStageAudit({
title: `${stageKey} definition`,
subtitle,
tabs: [{ key: "definition", label: "Definition", body: () =>
definitionDocument(detail, stageKey, (text) => rt.views.chat.renderMarkdown(text)) }],
});
}
/**
* The Audit & debug dialog: a stage's turn-owned evidence behind vertical tabs
* (Input, Output, Memory, Session, Stage definition), the chosen section's body
* on the right. It is the only place the system files are shown, so the artifact
* surfaces stay focused on what the stage actually produced.
*/
function openStageAudit({ title = "Audit", subtitle = "", tabs = [], trigger = null, revision = null } = {}) {
const available = (tabs ?? []).filter((tab) => typeof tab?.body === "function");
if (!available.length) return;
const close = () => { refreshAudit = null; modal.close("stage-audit"); };
const overlay = h("div", {
class: "audit-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": title,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) close();
});
const closeButton = h("button", {
class: "audit-close",
type: "button",
text: "Close",
onclick: close,
});
const panel = h("div", { class: "audit-panel" });
panel.append(
h(
"div",
{ class: "audit-head" },
h("button", { class: "ghost back-button audit-back", type: "button", "aria-label": "Back to stage", title: "Back to stage", onclick: close }, backChevronIcon()),
h(
"div",
{ class: "audit-titles" },
h("h2", { class: "audit-title", text: title }),
subtitle ? h("p", { class: "audit-subtitle muted", text: subtitle }) : null,
),
closeButton,
),
);
const nav = h("nav", {
class: "audit-tabs",
role: "tablist",
"aria-orientation": window.matchMedia("(max-width: 599px)").matches ? "horizontal" : "vertical",
"aria-label": "Audit sections",
});
const body = h("div", {
class: "audit-body",
id: "auditBody",
role: "tabpanel",
tabindex: "0",
});
panel.append(h("div", { class: "audit-layout" }, nav, body));
overlay.append(panel);
let active = available[0].key;
let renderedRevision = null;
const renderBody = () => {
const current = available.find((tab) => tab.key === active) ?? available[0];
body.replaceChildren(current.body());
renderedRevision = typeof revision === "function" ? revision(active) : null;
};
const renderTabs = () => {
nav.replaceChildren(
...available.map((tab) => {
const selected = tab.key === active;
return h("button", {
class: `audit-tab${selected ? " active" : ""}`,
type: "button",
role: "tab",
"aria-selected": selected ? "true" : "false",
"aria-controls": "auditBody",
"data-audit-tab": tab.key,
tabindex: selected ? "0" : "-1",
text: tab.label,
onclick: () => {
active = tab.key;
renderTabs();
},
onkeydown: (event) => {
const index = available.findIndex((entry) => entry.key === tab.key);
let next = -1;
if (event.key === "ArrowDown" || event.key === "ArrowRight") next = (index + 1) % available.length;
else if (event.key === "ArrowUp" || event.key === "ArrowLeft") next = (index - 1 + available.length) % available.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = available.length - 1;
if (next < 0) return;
event.preventDefault();
active = available[next].key;
renderTabs();
nav.querySelector(`[data-audit-tab="${active}"]`)?.focus();
},
});
}),
);
renderBody();
};
renderTabs();
modal.open("stage-audit", overlay, {
onClose: () => close(),
trigger,
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
refreshAudit = () => {
if (!overlay.isConnected || typeof revision !== "function") return;
if (revision(active) !== renderedRevision) renderBody();
};
}
return {
refreshStageAudit,
openStageDefinition,
closeChangeViewer,
openChangeViewer,
openDecisionSheet,
closeDecisionSheet,
renderDecisionSheet,
confirmDecision,
openConfirm,
dismissConfirm,
renderConfirmDialog,
acceptConfirm,
renderActionFailedDialog,
dismissActionError,
closeArtifactViewer,
openArtifactViewer,
openStageAudit,
};
}
-716
View File
@@ -1,716 +0,0 @@
// 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,
};
}
File diff suppressed because it is too large Load Diff
-398
View File
@@ -1,398 +0,0 @@
// The Runs history view: day groups, usage metrics, rows and the filter/sort
// menus. The pure filtering, sorting and formatting live in runs.js; this module
// owns the DOM and the page's run-list state.
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,
runIdentity,
versionLabel,
progressText,
metaText,
formatDuration,
localDayKey,
filterRuns,
groupRunsByDay,
runComparator,
pipelineFilterOptions,
runListEntries,
runFiltersActiveCount,
DEFAULT_RUN_SORT,
defaultRunFilters,
} from "../runs.js";
export function createRunsView(rt) {
const { state } = rt;
const renderContent = (...args) => rt.renderContent(...args);
const selectRun = (...args) => rt.selectRun(...args);
const renderAttentionBell = () => rt.renderAttentionBell();
const miniGraphFor = createMiniGraphCache((id, version) => rt.repo.getPipeline(id, version), () => {
if (state.view === "runs") renderContent();
});
function renderRunList(now = Date.now()) {
const pane = h("div", { class: "list runs" });
pane.append(renderRunToolbar());
const applied = renderAppliedRunFilters();
if (applied) pane.append(applied);
const scroll = h("div", { class: "run-scroll list-scroll" });
if (state.loading && !state.runs.length) {
scroll.append(h("div", { class: "muted pad", text: "Loading…" }));
pane.append(scroll);
return pane;
}
const filters = state.runFilters;
const today = localDayKey(new Date());
const filtered = filterRuns(state.runs, filters, today);
const groups = groupRunsByDay(filtered, today, undefined, runComparator(state.runSort));
const entries = runListEntries(
state.usage,
state.runs.length === 0,
filtered.length === 0 && state.runs.length > 0,
groups,
"",
);
for (const entry of entries) {
switch (entry.kind) {
case "empty":
scroll.append(renderEmptyState(entry));
break;
case "day":
scroll.append(h("div", { class: "day-header", text: entry.label }));
break;
case "run":
scroll.append(renderRunRow(entry.run, now));
break;
case "error":
scroll.append(h("div", { class: "run-list-error", text: entry.message }));
break;
}
}
pane.append(scroll);
return pane;
}
function renderUsage(usage) {
const metrics = h("div", { class: "metrics" });
metrics.append(metric("Total", String(usage.total ?? 0), "total"));
if ((usage.average_seconds ?? 0) > 0) {
metrics.append(metric("Average", formatDuration(usage.average_seconds), "average"));
}
metrics.append(metric("Succeeded", String(usage.succeeded ?? 0), "succeeded"));
metrics.append(metric("Failed", String(usage.failed ?? 0), "failed"));
metrics.append(metric("Canceled", String(usage.canceled ?? 0), "canceled"));
metrics.append(metric("Interrupted", String(usage.interrupted ?? 0), "interrupted"));
metrics.append(metric("Active", String(usage.active ?? 0), "active"));
return metrics;
}
function metric(label, value, cls) {
return h(
"div",
{ class: `metric metric-${cls}` },
h("span", { class: "metric-value", text: value }),
h("span", { class: "metric-label", text: label }),
);
}
function renderEmptyState(entry) {
const wrap = h("div", { class: "empty-state" }, h("span", { text: entry.message }));
if (entry.actionLabel) {
wrap.append(h("button", { class: "ghost", text: entry.actionLabel, onclick: clearRunFilters }));
}
return wrap;
}
/**
* One run row, in the app's exact hierarchy: status chip (+ spinner while
* executing); primary line = stored title else pipeline name, carrying the
* version chip when there is no title; the pipeline name + version chip on a
* second line only when a title exists; the progress line; the meta line; and
* the diagnostic line, in the error colour only on a failure. Every
* server-provided string is set with textContent.
*/
function renderRunRow(run, now) {
const status = runStateOf(run.status);
const identity = runIdentity(run.title, run.name);
const row = h("button", {
class: `row run-row${state.selectedRunId === run.id ? " selected" : ""}`,
"data-run-id": String(run.id),
"data-animate-key": `run:${run.id}`,
onclick: () => selectRun(run.id),
});
const head = h("span", { class: "run-row-head" });
head.append(statusIcon(status, runStatusLabel(run)));
if (run.cancel_requested || run.cleanup_unconfirmed) {
head.append(h("span", { class: "muted", text: runStatusLabel(run) }));
}
if (run.executing) head.append(h("span", { class: "spinner", "aria-hidden": "true" }));
// The pipeline is the list's anchor: it names what ran, before the task title.
head.append(
h("span", { class: "run-row-pipeline-name", text: identity.pipeline ?? identity.label }),
);
head.append(versionChip(run.version));
row.append(head);
if (identity.pipeline != null) {
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", {
class: "run-row-meta",
"data-run-id": String(run.id),
text: metaText(run, now),
}),
);
if (String(run.diagnostic ?? "").trim()) {
row.append(
h("span", {
class: `run-row-diag${status === "failed" ? " error" : ""}`,
text: run.diagnostic,
}),
);
}
const evidence = state.runDetail?.id === run.id ? state.runDetail : run;
const graph = miniGraphFor(evidence, state.pipelines, state.url);
const mini = renderMiniGraph(graph, evidence);
if (mini) row.append(mini);
return row;
}
function versionChip(version) {
return h("span", { class: "version-chip", text: versionLabel(version) });
}
function renderRunToolbar() {
const activeCount = runFiltersActiveCount(state.runFilters);
const filterLabel = activeCount > 0 ? `Filter (${activeCount})` : "Filter";
const sortLabel = (RUN_SORTS.find((s) => s.value === state.runSort) ?? RUN_SORTS[0]).label;
const toolbar = h("div", { class: "run-toolbar" });
toolbar.append(
h(
"div",
{ class: "menu-anchor" },
h("button", {
id: "runFilterBtn",
class: `ghost filter-btn${activeCount > 0 ? " active" : ""}`,
title: activeCount > 0 ? `${activeCount} active filter${activeCount === 1 ? "" : "s"}` : "Filter runs",
text: filterLabel,
"data-active-count": String(activeCount),
onclick: () => toggleMenu("filter"),
}),
state.openMenu === "filter" ? renderFilterMenu() : null,
),
h(
"div",
{ class: "menu-anchor" },
h("button", {
id: "runSortBtn",
class: "ghost sort-btn",
title: "Sort runs",
text: `Sort: ${sortLabel}`,
onclick: () => toggleMenu("sort"),
}),
state.openMenu === "sort" ? renderSortMenu() : null,
),
h("span", { class: "spacer" }),
renderAttentionBell(),
);
return toolbar;
}
function renderAppliedRunFilters() {
if (runFiltersActiveCount(state.runFilters) === 0) return null;
const applied = h("div", { class: "run-applied-filters", "aria-label": "Applied run filters" });
const chip = (label, clear, className = "") => h("button", {
class: `run-filter-chip ${className}`,
type: "button",
"aria-label": `Clear filter: ${label}`,
title: `Clear filter: ${label}`,
onclick: clear,
}, h("span", { text: label }), h("span", { "aria-hidden": "true", text: "×" }));
const pipelineId = state.runFilters.pipelineId;
if (pipelineId != null) {
const name = state.pipelines.find((pipeline) => pipeline.id === pipelineId)?.name ??
state.runs.find((run) => run.pipeline_id === pipelineId)?.name ?? `Pipeline ${pipelineId}`;
applied.append(chip(name, () => setPipelineFilter(null), "pipeline-filter-chip"));
}
for (const status of state.runFilters.statuses) {
applied.append(chip(status, () => toggleStatusFilter(status)));
}
const range = RUN_TIME_RANGES.find((entry) => entry.value === state.runFilters.timeRange);
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;
}
/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */
function renderFilterMenu() {
const filters = state.runFilters;
const menu = h("div", { class: "menu filter-menu", id: "runFilterMenu" });
menu.append(h("div", { class: "menu-section", text: "Status" }));
for (const status of RUN_STATES) {
menu.append(
filterCheck(status, filters.statuses.has(status), () => toggleStatusFilter(status), {
"data-status": status,
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Pipeline" }));
menu.append(
filterCheck("Any pipeline", filters.pipelineId == null, () => setPipelineFilter(null), {
"data-pipeline": "any",
}),
);
for (const option of pipelineFilterOptions(state.runs)) {
menu.append(
filterCheck(option.name, filters.pipelineId === option.id, () => setPipelineFilter(option.id), {
"data-pipeline": String(option.id),
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Time range" }));
for (const range of RUN_TIME_RANGES) {
menu.append(
filterCheck(range.label, filters.timeRange === range.value, () => setTimeRangeFilter(range.value), {
"data-time": range.value,
}),
);
}
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",
{ class: "menu-actions" },
h("button", { class: "ghost", text: "Clear filters", onclick: clearRunFilters }),
h("button", { class: "ghost", text: "Done", onclick: closeMenu }),
),
);
return menu;
}
function filterCheck(label, checked, onclick, data = {}) {
return h(
"label",
{ class: "filter-check" },
h("input", {
type: "checkbox",
checked: checked ? "checked" : null,
onchange: onclick,
...data,
}),
h("span", { text: label }),
);
}
function renderSortMenu() {
const menu = h("div", { class: "menu sort-menu", id: "runSortMenu" });
for (const option of RUN_SORTS) {
menu.append(
h("button", {
class: `menu-item${state.runSort === option.value ? " selected" : ""}`,
text: option.label,
onclick: () => {
state.runSort = option.value;
closeMenu();
},
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(
h("button", {
class: "menu-item",
text: "Reset",
onclick: () => {
state.runSort = DEFAULT_RUN_SORT;
closeMenu();
},
}),
);
return menu;
}
function toggleStatusFilter(status) {
const next = new Set(state.runFilters.statuses);
if (next.has(status)) next.delete(status);
else next.add(status);
state.runFilters = { ...state.runFilters, statuses: next };
renderContent();
}
function setPipelineFilter(pipelineId) {
state.runFilters = { ...state.runFilters, pipelineId };
if (state.selectedRunId == null) rt.pushRoute(pipelineId == null ? { kind: "runs" } : { kind: "runs", pipelineId });
closeMenu();
}
function setTimeRangeFilter(timeRange) {
state.runFilters = { ...state.runFilters, timeRange };
closeMenu();
}
function setScheduleFilter(scheduled) {
state.runFilters = { ...state.runFilters, scheduled };
closeMenu();
}
function clearRunFilters() {
state.runFilters = defaultRunFilters();
if (state.selectedRunId == null) rt.pushRoute({ kind: "runs" });
closeMenu();
}
function toggleMenu(name) {
state.openMenu = state.openMenu === name ? null : name;
renderContent();
}
function closeMenu() {
state.openMenu = null;
renderContent();
}
return {
renderRunList,
renderRunToolbar,
renderRunRow,
renderUsage,
renderEmptyState,
toggleMenu,
closeMenu,
clearRunFilters,
};
}
-171
View File
@@ -1,171 +0,0 @@
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();
const pipelineId = pipeline => pipeline.Pipeline?.id ?? pipeline.id;
const message = error => {
const text = error?.message || String(error);
return /unknown (message|request|command)|unsupported.*schedule/i.test(text)
? `This server does not support saved schedules. Upgrade the server to use schedules. (${text})` : text;
};
const unsupported = () => new Error('This server does not support saved schedules. Upgrade the server to use schedules.');
const refresh = () => rt.renderContent();
function clearScheduleCache() { cache.clear(); }
function loadPipelineSchedules(id, { force = false } = {}) {
const prior = cache.get(id);
if (prior?.pending || (!force && prior)) return prior.pending ?? Promise.resolve(prior.items);
const entry = { items: prior?.items ?? [], loading: true, error: null };
cache.set(id, entry);
entry.pending = Promise.resolve().then(() => {
if (!rt.repo.listSchedules) throw unsupported();
return rt.repo.listSchedules(id);
}).then(items => {
if (!Array.isArray(items)) throw new Error('Server returned an invalid schedules response.');
entry.items = items;
return items;
}).catch(error => { entry.error = message(error); return null; }).finally(() => {
entry.loading = false; entry.pending = null;
if (cache.get(id) === entry) refresh();
});
return entry.pending;
}
async function changed(id) {
await loadPipelineSchedules(id, { force: true });
await rt.scheduleChanged?.(id);
refresh();
}
function button(text, onclick, props = {}) {
return h('button', { type: 'button', text, onclick, ...props });
}
function renderPipelineSchedules(pipeline) {
const id = pipelineId(pipeline);
if (!cache.has(id)) void loadPipelineSchedules(id);
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})` : ''}` }),
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,
button('Retry', () => { void loadPipelineSchedules(id, { force: true }); refresh(); })));
if (!entry.loading && !entry.error && !entry.items.length) section.append(h('p', { class: 'schedule-muted', text: 'No schedules yet. Add one for each topic or recurring task.' }));
for (const schedule of entry.items) {
const errorNode = h('p', { class: 'schedule-error', role: 'alert', hidden: true });
const card = h('article', { class: 'schedule-card', 'data-schedule-id': schedule.id },
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, 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 () => {
toggle.disabled = true;
try {
if (!rt.repo.saveSchedule) throw unsupported();
await rt.repo.saveSchedule({ ...schedule, enabled: !schedule.enabled });
await changed(id);
} catch (error) { errorNode.hidden = false; errorNode.textContent = message(error); }
finally { toggle.disabled = false; }
});
actions.append(edit, toggle, button('Delete', event => openDelete(schedule, event.currentTarget)));
card.append(actions); section.append(card);
}
return section;
}
function openDelete(schedule, trigger) {
let pending = false;
const close = () => { if (!pending) rt.modal.close('schedule-delete'); };
const errorNode = h('p', { class: 'schedule-error', role: 'alert' });
const confirm = button('Delete schedule', async () => {
if (pending) return;
pending = true; confirm.disabled = true;
try {
if (!rt.repo.deleteSchedule) throw unsupported();
await rt.repo.deleteSchedule(schedule.id, schedule.revision);
} catch (error) {
errorNode.textContent = message(error); pending = false; confirm.disabled = false; return;
}
// Keep mutation success separate from a subsequent list-refresh failure.
pending = false;
await changed(schedule.pipeline_id).catch(error => { errorNode.textContent = message(error); });
rt.modal.close('schedule-delete');
});
const panel = h('div', { class: 'schedule-overlay', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Delete schedule' },
h('div', { class: 'schedule-panel schedule-confirm' }, h('h2', { text: `Delete ${schedule.name}?` }),
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', '.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 = {};
const field = (key, label, { textarea = false, ...props } = {}) => {
const input = h(textarea ? 'textarea' : 'input', { class: 'schedule-input', name: key, type: textarea ? null : 'text', ...props });
input.value = draft[key]; fields[key] = input;
return h('label', { class: 'schedule-field' }, h('span', { text: label }), input);
};
const mode = h('select', { name: 'mode', 'aria-label': 'Timer mode' }, h('option', { value: 'interval', text: 'Interval' }), h('option', { value: 'clock', text: 'Clock times' }));
mode.value = draft.mode;
const interval = field('every', 'Interval (at least 1m)');
const clock = field('times', 'Clock times (24h, comma separated)');
const updateMode = () => { interval.hidden = mode.value !== 'interval'; clock.hidden = mode.value !== 'clock'; };
mode.addEventListener('change', updateMode); updateMode();
const days = h('fieldset', { class: 'schedule-days' }, h('legend', { text: 'Weekdays (none means every day)' }));
const dayInputs = SCHEDULE_DAYS.map(day => {
const input = h('input', { type: 'checkbox', value: day, checked: draft.days.includes(day) });
days.append(h('label', {}, input, day)); return input;
});
const enabled = h('input', { type: 'checkbox', name: 'enabled', checked: draft.enabled });
const notify = h('select', { name: 'notifyMode' }, ...['auto', 'on', 'off'].map(value => h('option', { value, text: value })));
notify.value = draft.notifyMode;
const errorNode = h('p', { class: 'schedule-error', role: 'alert', hidden: true });
const save = h('button', { type: 'submit', text: 'Save schedule' });
const form = h('form', { class: 'schedule-panel', novalidate: true },
h('h2', { text: schedule ? 'Edit schedule' : 'Add schedule' }),
h('p', { class: 'schedule-muted', text: 'Future runs only; does not publish or change the workflow. Saving does not start a run.' }),
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'),
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('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 => {
event.preventDefault(); if (pending) return;
errorNode.hidden = true;
let record;
try {
for (const [key, input] of Object.entries(fields)) draft[key] = input.value;
Object.assign(draft, { mode: mode.value, days: dayInputs.filter(input => input.checked).map(input => input.value), enabled: enabled.checked, notifyMode: notify.value });
record = serializeSchedule(draft, { pipelineId: pipelineId(pipeline), schedule });
if (!rt.repo.saveSchedule) throw unsupported();
} 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, { 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;
}
await changed(record.pipeline_id).catch(() => {});
pending = false; close();
});
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', '.schedule-run', '#detailTitle', '#pane-main'] });
return overlay;
}
return { renderPipelineSchedules, openScheduleEditor, loadPipelineSchedules, clearScheduleCache };
}
-677
View File
@@ -1,677 +0,0 @@
// Omni-search: the shell's Search control, kind/sort controls, rows and result
// routing. Debounce/staleness/ordering/empty-state decisions are pure in
// search.js; this module owns the DOM and the route hand-off.
import { h, openArtifactInBrowser } from "../dom.js";
import { describeError } from "../format.js";
import { resolveArtifactUrl } from "../serverUrl.js";
import { ArtifactKind, artifactKind } from "../artifacts.js";
import {
DEFAULT_SEARCH_KIND,
DEFAULT_SEARCH_SORT,
SEARCH_DEBOUNCE_MS,
SEARCH_KINDS,
SEARCH_SORTS,
parseSearchQuery,
SearchSequencer,
filterSearchResults,
resolveRunTarget,
searchControlsSummary,
searchFailureText,
searchPanelBody,
searchPanelProgress,
searchQuerySendable,
searchResultKindLabel,
searchRow,
searchTarget,
sortSearchResults,
} from "../search.js";
export function createSearchView(rt) {
const { state, repo, searchHost } = rt;
const parsedSearch = () => parseSearchQuery(state.searchQuery, state.searchKind);
let searchTimer = null;
let searchEdit = null;
// The last search is resumed on the next open (the field, kind, sort and the
// selected row). Persisted so it also survives a reload.
const SEARCH_STORAGE_KEY = "pipelines.web.search.v1";
function saveSearchState() {
try {
localStorage.setItem(
SEARCH_STORAGE_KEY,
JSON.stringify({
query: state.searchQuery,
kind: state.searchKind,
sort: state.searchSort,
activeIndex: state.searchActiveIndex,
}),
);
} catch {
// Storage may be unavailable; the in-memory state still resumes in this page.
}
}
function restoreSearchState() {
if (state.searchQuery !== "") return;
try {
const saved = JSON.parse(localStorage.getItem(SEARCH_STORAGE_KEY) || "null");
if (!saved || typeof saved.query !== "string") return;
state.searchQuery = saved.query;
if (SEARCH_KINDS.some((k) => k.value === saved.kind)) state.searchKind = saved.kind;
if (SEARCH_SORTS.some((k) => k.value === saved.sort)) state.searchSort = saved.sort;
state.searchActiveIndex = Number.isInteger(saved.activeIndex) ? Math.max(0, saved.activeIndex) : 0;
} catch {
// A corrupt value simply starts empty.
}
}
// Where focus goes when the panel closes: the rail or dock Search control that
// opened it, so Escape/Close never drops the operator on <body>.
let searchTriggerId = null;
const renderHeader = (...args) => rt.renderHeader(...args);
const renderContent = (...args) => rt.renderContent(...args);
const selectPipeline = (...args) => rt.selectPipeline(...args);
const selectRun = (...args) => rt.selectRun(...args);
const openStagePane = (...args) => rt.views.runDetail.openStagePane(...args);
// Omni-search (S1/S2)
// ---------------------------------------------------------------------------
/** Open the search field and ask for focus; the current view is left alone. */
function openSearch() {
if (state.searchOpen) return;
const trigger = document.activeElement;
searchTriggerId = trigger && trigger.id ? trigger.id : null;
restoreSearchState();
state.searchOpen = true;
state.searchError = "";
state.searchFocusPending = true;
renderHeader();
renderSearch();
// Resume: show previous results immediately, then refresh text or kind-only
// searches so the list is not stale.
if (searchQuerySendable(state.searchQuery, parsedSearch().kind)) {
state.searchLoading = true;
const sent = state.searchSequencer.begin(state.searchSequencer.edit(state.searchQuery));
if (sent) runSearch(sent);
refreshSearch();
}
}
/**
* Close and clear the search: the pending debounce is dropped, an in-flight reply
* is invalidated by recording a fresh edit, and the query, results, error and
* loading flag are reset. The view, the selection and the loaded data are
* deliberately untouched, so closing restores exactly the state that was on
* screen before the search opened.
*/
function closeSearch() {
cancelSearchDebounce();
saveSearchState();
// Recording an empty edit advances the sequencer, so a reply for a request
// still in flight can no longer be accepted.
state.searchSequencer.edit("");
state.searchOpen = false;
state.searchLoading = false;
state.searchFocusPending = false;
renderHeader();
renderSearch();
const trigger = searchTriggerId ? document.getElementById(searchTriggerId) : null;
searchTriggerId = null;
if (trigger && trigger.getClientRects().length > 0) trigger.focus();
}
/** Keep the keyboard-selected row visible in the results list. */
function scrollActiveSearchRow() {
document.querySelector("#searchResults .search-row.active")?.scrollIntoView({ block: "nearest" });
}
function cancelSearchDebounce() {
if (searchTimer) {
clearTimeout(searchTimer);
searchTimer = null;
}
searchEdit = null;
}
/**
* A keystroke. Blank text without a kind clears locally and sends nothing;
* kind-only searches browse recent items. Previous results stay visible while
* loading; sending is debounced `SEARCH_DEBOUNCE_MS` from the last keystroke.
* Recording the edit is itself enough to drop any older reply still in flight.
*/
function onSearchInput(value) {
state.searchQuery = value;
state.searchError = "";
cancelSearchDebounce();
if (!searchQuerySendable(value, parsedSearch().kind)) {
state.searchSequencer.edit("");
state.searchResults = [];
state.searchLoading = false;
state.searchLoaded = false;
refreshSearch();
return;
}
state.searchLoading = true;
searchEdit = state.searchSequencer.edit(value);
refreshSearch();
searchTimer = setTimeout(() => {
searchTimer = null;
const sent = state.searchSequencer.begin(searchEdit);
if (sent) runSearch(sent);
}, SEARCH_DEBOUNCE_MS);
}
/** Send the current query at once (Enter, or a kind change), skipping the debounce. */
function sendSearchNow() {
const query = state.searchQuery;
cancelSearchDebounce();
if (!searchQuerySendable(query, parsedSearch().kind)) {
state.searchSequencer.edit("");
state.searchResults = [];
state.searchLoading = false;
state.searchError = "";
state.searchLoaded = false;
refreshSearch();
return;
}
const sent = state.searchSequencer.begin(state.searchSequencer.edit(query));
if (sent) runSearch(sent);
}
/**
* A kind-filter change: the in-hand filter is re-applied immediately so the list
* always matches the control. Text or a valid kind sends a fresh server request;
* clearing both stays local. A sort change never sends a request.
*/
function setSearchKind(kind) {
state.searchQuery = parsedSearch().query;
const input = document.getElementById("searchInput");
if (input) input.value = state.searchQuery;
state.searchKind = kind;
sendSearchNow();
}
function setSearchSort(sort) {
state.searchSort = sort;
refreshSearch();
}
/**
* Run one query and apply the reply only if it is still the newest edit. A reply
* without a `search_results` payload (an older server's pong) or a rejection
* naming an unknown command reports the app's "cannot search" sentence; any other
* failure carries the server's own text. A stale reply is dropped entirely.
*/
async function runSearch(sent) {
const parsed = parseSearchQuery(sent.query, state.searchKind);
try {
const reply = await repo.search(parsed.query.trim() ? parsed.query : "", parsed.kind);
if (!state.searchSequencer.accepts(sent.token)) return;
if (reply == null) {
state.searchLoading = false;
state.searchLoaded = true;
state.searchError = searchFailureText(null);
refreshSearch();
return;
}
state.searchResults = Array.isArray(reply.results) ? reply.results : [];
state.searchTruncated = Boolean(reply.truncated);
state.searchActiveIndex = 0;
state.searchLoading = false;
state.searchError = "";
state.searchLoaded = true;
refreshSearch();
} catch (error) {
if (!state.searchSequencer.accepts(sent.token)) return;
state.searchLoading = false;
state.searchLoaded = true;
state.searchError = searchFailureText(error);
refreshSearch();
}
}
/**
* Re-render the search panel's controls and results in place. Only the results
* area, the summary and the select values are touched, so a keystroke never
* rebuilds (and so never blurs) the query field.
*/
function refreshSearch() {
const kindSelect = document.getElementById("searchKind");
if (kindSelect) kindSelect.value = parsedSearch().kind;
const sortSelect = document.getElementById("searchSort");
if (sortSelect) sortSelect.value = state.searchSort;
const summary = document.getElementById("searchSummary");
if (summary) summary.textContent = searchControlsSummary(parsedSearch().kind, state.searchSort);
const area = document.getElementById("searchResults");
if (area) fillSearchResults(area);
}
/**
* The full-width search panel: the controls row (kind select, sort select, the
* one-line summary and the Clear filter reset) and a bounded scrolling result
* area. Rendered only while the search is open; the panel is one flat list, with
* no per-kind grouping headers, matching the app.
*/
function renderSearch() {
if (!state.searchOpen) {
searchHost.replaceChildren();
return;
}
const kindSelect = h(
"select",
{
id: "searchKind",
class: "search-select",
"aria-label": "Filter results",
onchange: (event) => setSearchKind(event.target.value),
},
...SEARCH_KINDS.map((option) => h("option", { value: option.value, text: option.label })),
);
kindSelect.value = parsedSearch().kind;
const sortSelect = h(
"select",
{
id: "searchSort",
class: "search-select",
"aria-label": "Sort results in hand",
onchange: (event) => setSearchSort(event.target.value),
},
...SEARCH_SORTS.map((option) => h("option", { value: option.value, text: option.label })),
);
sortSelect.value = state.searchSort;
const fieldRow = h(
"div",
{ class: "search-field-row" },
h("input", {
id: "searchInput",
class: "search-input",
type: "text",
placeholder: "Search pipelines, runs and artifacts",
value: state.searchQuery,
spellcheck: "false",
autocomplete: "off",
"aria-label": "Search",
oninput: (event) => onSearchInput(event.target.value),
onkeydown: (event) => {
const shown = sortSearchResults(
filterSearchResults(state.searchResults, parsedSearch().kind),
state.searchSort,
);
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!shown.length) return;
const delta = event.key === "ArrowDown" ? 1 : -1;
state.searchActiveIndex = (state.searchActiveIndex + delta + shown.length) % shown.length;
refreshSearch();
scrollActiveSearchRow();
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (shown.length && !state.searchLoading && !state.searchError) {
routeSearchResult(shown[state.searchActiveIndex] ?? shown[0]);
} else sendSearchNow();
}
},
}),
h("button", {
id: "searchClose",
class: "ghost search-close",
type: "button",
text: "Close search",
onclick: () => closeSearch(),
}),
);
const controls = h(
"div",
{ class: "search-controls" },
h("label", { class: "search-field" }, h("span", { class: "search-field-label", text: "Kind" }), kindSelect),
h("label", { class: "search-field" }, h("span", { class: "search-field-label", text: "Sort" }), sortSelect),
h("span", {
id: "searchSummary",
class: "search-summary muted",
text: searchControlsSummary(parsedSearch().kind, state.searchSort),
}),
h("button", {
id: "searchClearFilter",
class: "ghost search-clear",
type: "button",
text: "Clear filter",
onclick: () => setSearchKind(DEFAULT_SEARCH_KIND),
}),
);
const area = h("div", { id: "searchResults", class: "search-results", "aria-live": "polite" });
fillSearchResults(area);
const panel = h(
"div",
{ id: "searchPanel", class: "search-panel", role: "dialog", "aria-modal": "true", "aria-label": "Search" },
h("div", { class: "search-modal", role: "search" }, fieldRow, controls,
h("p", { class: "muted", text: "Filter with t:pipeline or type:artifact (pipeline, run, step, field, artifact, version). Type alone lists recent items. Last type wins; choosing Kind replaces it. Quote tokens to search literally." }), area),
);
// A spotlight: clicking the dimmed backdrop closes it (the modal itself stops).
panel.addEventListener("click", (event) => {
if (event.target === panel) closeSearch();
});
panel.querySelector(".search-modal")?.addEventListener("click", (event) => event.stopPropagation());
searchHost.replaceChildren(panel);
if (state.searchFocusPending) {
document.getElementById("searchInput")?.focus();
state.searchFocusPending = false;
}
}
/**
* Fill the results area from the current state. A first load with nothing yet
* shows the spinner and `Searching…`; a refresh that retained results shows a thin
* progress bar above them; an error takes precedence over the results; otherwise
* the filtered and sorted rows, or the empty-state line.
*/
function fillSearchResults(area) {
const parsed = parsedSearch();
const shown = sortSearchResults(
filterSearchResults(state.searchResults, parsed.kind),
state.searchSort,
);
const nodes = [];
const panelState = {
query: parsed.query, loading: state.searchLoading, loaded: state.searchLoaded,
error: state.searchError, results: state.searchResults,
truncated: state.searchTruncated,
};
if (searchPanelProgress(panelState)) {
nodes.push(h("div", { class: "search-progress", role: "progressbar", "aria-label": "Searching" }));
}
const body = searchPanelBody(panelState, shown, parsed.kind);
if (body.kind === "error") {
nodes.push(h("div", { class: "search-error", text: body.message }));
} else if (body.kind === "results") {
state.searchActiveIndex = Math.min(Math.max(0, state.searchActiveIndex), shown.length - 1);
shown.forEach((hit, index) => {
const row = renderSearchResultRow(hit);
if (index === state.searchActiveIndex) {
row.classList.add("active");
row.setAttribute("aria-selected", "true");
}
nodes.push(row);
});
} else if (body.kind === "searching") {
nodes.push(
h(
"div",
{ class: "search-searching muted" },
h("span", { class: "spinner", "aria-hidden": "true" }),
h("span", { text: "Searching…" }),
),
);
} else if (body.kind === "empty") {
nodes.push(h("div", { class: "search-empty muted", text: body.message }));
}
if (body.kind === "results" && !state.searchLoading && parsed.kind && !parsed.query.trim()) {
nodes.push(h("div", {
class: "search-summary muted",
text: state.searchTruncated ? "Recent items · limited by the server's result or scan cap." : "Recent items",
}));
}
area.replaceChildren(...nodes);
}
/** The inline glyph for a non-artifact search result's kind. */
function searchKindGlyph(kind) {
const ns = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(ns, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const paths = {
pipeline: "M7 12h5V6h4M12 12v6h4",
version: "M12 3l9 5-9 5-9-5 9-5ZM3 12l9 5 9-5",
run: "M8 5l11 7-11 7V5Z",
step: "M5 12h10M13 8l4 4-4 4",
field: "M5 7h14M5 12h14M5 17h9",
unknown: "M12 8v8M8 12h8",
};
const path = document.createElementNS(ns, "path");
path.setAttribute("d", paths[kind] ?? paths.unknown);
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);
if (kind === "pipeline") {
for (const [cx, cy] of [[4, 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;
}
/** The fixed-size leading tile for a non-artifact result: a kind glyph only. */
function searchKindTile(hit) {
const label = searchResultKindLabel(hit);
const tile = h("span", {
class: "search-type search-type-kind",
title: label,
"aria-label": label,
});
tile.append(searchKindGlyph(String(hit?.kind ?? "unknown")));
return tile;
}
/** The short caption on a non-image artifact's type tile. */
function artifactTypeBadge(kind, artifact) {
const name = String(artifact?.name ?? "").toLowerCase();
const mime = String(artifact?.content_type ?? "").split(";")[0].trim().toLowerCase();
const ext = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : "";
if (kind === ArtifactKind.Document) {
if (mime === "text/markdown" || ext === "md" || ext === "markdown") return "MD";
if (mime === "text/plain" || ext === "txt") return "TXT";
return "DOC";
}
if (kind === ArtifactKind.Spreadsheet) {
if (ext === "csv") return "CSV";
if (ext === "tsv") return "TSV";
if (ext === "xlsx" || ext === "xls") return "XLSX";
return "SHEET";
}
if (kind === ArtifactKind.Code) return ext ? ext.toUpperCase().slice(0, 5) : "CODE";
switch (kind) {
case ArtifactKind.Image:
return "IMG";
case ArtifactKind.Video:
return "VID";
case ArtifactKind.Audio:
return "AUD";
case ArtifactKind.Pdf:
return "PDF";
case ArtifactKind.Json:
return "JSON";
case ArtifactKind.Archive:
return "ZIP";
case ArtifactKind.Spreadsheet:
return "SHEET";
case ArtifactKind.Log:
return "LOG";
case ArtifactKind.Code:
return "CODE";
case ArtifactKind.Document:
return "DOC";
default:
return "FILE";
}
}
/** Leave the search panel and open a run, for an artifact row's own action. */
async function openRunFromSearch(runId) {
closeSearch();
state.error = "";
state.view = "runs";
await selectRun(runId);
}
/**
* One result row: the artifact itself when it is an image (a thumbnail), a type
* tile otherwise, the title and — for a text match — the server snippet with the
* first case-insensitive query occurrence emphasised. A known payload is
* clickable and routes to its destination; an unknown/absent payload is rendered
* read-only and is never clickable. Every server string is set as text.
*/
function renderSearchResultRow(hit) {
const row = searchRow(hit, parsedSearch().query);
const target = searchTarget(hit);
const artifactHit = hit?.kind === "artifact" && hit.artifact ? hit.artifact : null;
const element = h("div", {
class: `search-row${target ? " clickable" : " readonly"} search-row-with-icon${artifactHit ? " search-row-artifact" : ""}`,
"data-kind": String(hit?.kind ?? ""),
});
if (target) {
const route = () => routeSearchResult(hit);
element.setAttribute("role", "button");
element.setAttribute("tabindex", "0");
if (target.kind === "pipeline") {
element.setAttribute("data-target", `pipeline:${target.pipelineId}:v${target.version}`);
} else if (target.matchedField) {
element.setAttribute("data-target", `run:${target.runId}:${target.sequence}:${target.matchedField}`);
} else {
element.setAttribute("data-target", `run:${target.runId}${target.sequence ? `:${target.sequence}` : ""}`);
}
element.addEventListener("click", route);
element.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
route();
}
});
}
if (artifactHit) {
const kind = artifactKind(artifactHit.content_type, artifactHit.name);
const resolved = artifactHit.url ? resolveArtifactUrl(state.url, artifactHit.url) : "";
if (kind === ArtifactKind.Image && resolved) {
const thumb = h("img", {
class: "search-thumb",
src: resolved,
alt: "",
loading: "lazy",
"aria-hidden": "true",
});
element.append(thumb);
element.setAttribute("aria-label", `Image artifact ${searchRow(hit, state.searchQuery).title}`);
} else {
element.append(
h("span", {
class: "search-type",
text: artifactTypeBadge(kind, artifactHit),
title: searchResultKindLabel(hit),
"aria-label": searchResultKindLabel(hit),
}),
);
}
} else {
// Every row leads with the same fixed-size tile; kinds are symbols, never
// words like "PIPELINE" that make one row look different from another.
element.append(searchKindTile(hit));
}
const main = h("div", { class: "search-row-main" });
main.append(h("div", { class: "search-row-title", text: row.title }));
if (row.snippet != null) {
const line = h("div", { class: "search-row-snippet muted" });
for (const span of row.snippet) {
if (span.matched) {
line.append(h("strong", { class: "search-match" }, h("u", {}, span.text)));
} else {
line.append(document.createTextNode(span.text));
}
}
main.append(line);
} else if (row.secondary) {
main.append(h("div", { class: "search-row-secondary muted", text: row.secondary }));
}
if (artifactHit && Number(artifactHit.run_id) > 0) {
const runButton = h("button", {
class: "search-open-run",
type: "button",
text: `Open run #${Number(artifactHit.run_id)}`,
});
// A row action must not also trigger the row's own artifact navigation.
runButton.addEventListener("click", (event) => {
event.stopPropagation();
openRunFromSearch(Number(artifactHit.run_id));
});
runButton.addEventListener("keydown", (event) => event.stopPropagation());
main.append(runButton);
}
element.append(main);
return element;
}
/**
* Route one selected result through the page's existing navigation, exactly as
* the app does. The search is closed and cleared first, so every selection leaves
* the panel; a known payload then opens the pipeline detail (at the result
* version, 0 = latest), the run detail, the run-detail tab holding a text match,
* or the recorded visit's stage pane (the artifact route is that same pane). A
* visit that cannot be located falls back to the plain run detail. An unknown
* result has no target and never navigates.
*/
async function routeSearchResult(hit) {
const target = searchTarget(hit);
if (!target) return;
// All artifact types open in the browser. In-app preview is an explicit
// gallery action, never an unexpected navigation away from the installed app.
if (hit?.kind === "artifact" && hit.artifact?.url) {
const artifact = hit.artifact;
const resolved = resolveArtifactUrl(state.url, artifact.url);
if (!resolved) return;
closeSearch();
openArtifactInBrowser(resolved);
return;
}
closeSearch();
state.error = "";
if (target.kind === "pipeline") {
state.view = "pipelines";
state.selectedRunId = null;
await selectPipeline({ id: target.pipelineId, version: target.version });
return;
}
state.view = "runs";
await selectRun(target.runId);
if (!state.runDetail) return;
const resolved = resolveRunTarget(target, target.runId, state.runDetail.steps ?? []);
if (resolved.tab === "input" || resolved.tab === "output") {
// Input and Output are run Summary sections now, so a field hit opens the
// Summary with the matching section expanded rather than a dead tab.
state.runTab = "summary";
state.runSections = new Set([...state.runSections, `summary-${resolved.tab}`]);
renderContent();
} else if (resolved.tab) {
state.runTab = resolved.tab;
renderContent();
} else if (resolved.stageKey != null) {
openStagePane(resolved.stageKey, resolved.visitIndex);
}
}
// Ctrl+/ (Cmd+/ on macOS) is the Spotlight shortcut: toggle from anywhere.
document.addEventListener("keydown", (event) => {
if (!(event.ctrlKey || event.metaKey) || event.key !== "/") return;
event.preventDefault();
if (state.searchOpen) closeSearch();
else openSearch();
});
return {
openSearch,
closeSearch,
renderSearch,
onSearchInput,
sendSearchNow,
};
}
-423
View File
@@ -1,423 +0,0 @@
// The Settings destination: Connection, Workspace, Notifications and the
// Templates card. Every string and validation rule comes from settings.js /
// notify.js; this module owns the DOM, the local drafts and the shared client's
// connection controls.
import { h } from "../dom.js";
import {
SERVER_URL_HELPER,
SERVER_URL_PLACEHOLDER,
TEMPLATES_CARD_LABEL,
TEMPLATES_CARD_SECONDARY,
TRUST_BODY,
TRUST_TITLE,
WORKSPACE_HELPER,
WORKSPACE_PLACEHOLDER,
canSaveWorkspace,
connectionActionKind,
connectionActions,
connectionCard,
savedWorkspaceLine,
workspaceErrorText,
writeWorkspace,
} from "../settings.js";
import {
NOTIFICATION_RATIONALE,
notificationEnvironment,
notificationPermissionState,
} from "../notify.js";
import { bannerState, protocolMismatch } from "../connection.js";
import { PROTOCOL_VERSION } from "../protocol.js";
export function createSettingsView(rt) {
const { state, repo, setServerUrlDraft, endpointConfigured } = rt;
const renderContent = (...args) => rt.renderContent(...args);
const pushRoute = (...args) => rt.pushRoute(...args);
const applyRoute = (...args) => rt.applyRoute(...args);
const openConfiguredEndpoint = (...args) => rt.openConfiguredEndpoint(...args);
const onReconnectClicked = (...args) => rt.onReconnectClicked(...args);
const persistNotifyAsked = (...args) => rt.views.attention.persistNotifyAsked(...args);
/**
* The Settings destination: the app's three sections (Connection, Workspace,
* Templates) in one pane. It is wiring only — every string, the workspace
* validation and the connection card's lines come from the pure `settings.js`,
* and the connection controls drive the page's existing single client through
* the same handlers the header uses (no second socket or path). Every
* server-derived string is set with textContent.
*/
function renderSettingsView() {
const pane = h("div", { class: "settings" });
pane.append(
h(
"div",
{ class: "settings-head" },
h("h1", { class: "settings-page-title", id: "detailTitle", tabindex: "-1", text: "Settings" }),
h("button", {
id: "settingsRefresh",
class: "ghost settings-refresh",
type: "button",
text: "Refresh",
onclick: () => window.location.reload(),
}),
),
renderSettingsConnection(),
renderSettingsWorkspace(),
renderSettingsNotifications(),
renderSettingsTemplates(),
);
return pane;
}
function renderSettingsConnection() {
const section = h("section", { class: "settings-section" });
section.append(h("h2", { class: "settings-title", text: "Connection" }));
section.append(
h(
"label",
{ class: "settings-field", for: "settingsServerUrl" },
h("span", { class: "settings-field-label", text: "Server URL" }),
h("input", {
id: "settingsServerUrl",
type: "text",
placeholder: SERVER_URL_PLACEHOLDER,
value: state.url,
spellcheck: "false",
autocomplete: "off",
"aria-describedby": "settingsUrlHelper",
"aria-invalid": state.urlError ? "true" : null,
oninput: (event) => {
setServerUrlDraft(event.target.value, "settingsServerUrl");
},
}),
),
);
// Android's `urlError ?: helper` supporting text. The error clears on the next
// edit (AppViewModel.updateServerUrlDraft) and is announced as the field's own
// invalid state rather than as a page-level banner.
section.append(
h(
"p",
{
id: "settingsUrlHelper",
class: `settings-helper${state.urlError ? " settings-helper-error" : ""}`,
role: state.urlError ? "alert" : null,
},
serverUrlSupportingText(),
),
);
const actions = connectionActions(state.connection);
section.append(
h(
"div",
{ class: "settings-actions" },
h("button", {
id: "settingsPrimary",
class: "primary",
type: "button",
text: actions.primary,
onclick: () => runConnectionAction(actions.primary),
}),
h("button", {
id: "settingsSecondary",
class: "ghost",
type: "button",
text: actions.secondary,
onclick: () => runConnectionAction(actions.secondary),
}),
),
);
const tone = bannerState(state.connection, { hasEndpoint: endpointConfigured() }).tone;
const card = h("div", { class: `settings-status status-${tone}` });
const lines = connectionCard(state.connection, {
version: state.serverBuild?.version,
commit: state.serverBuild?.commit,
serverTime: state.serverTime,
});
lines.forEach((line, index) => {
// Android's Connecting card leads its one line with a CircularProgressIndicator;
// the shared spinner is drawn only for that state, inline with the text, so the
// other three stay plain text.
if (index === 0 && state.connection.kind === "connecting") {
const row = h("div", { class: "settings-status-head" });
row.append(h("span", { class: "spinner settings-status-spinner", "aria-hidden": "true" }));
row.append(h("p", { class: "settings-status-line", text: line }));
card.append(row);
return;
}
card.append(h("p", { class: "settings-status-line", text: line }));
});
section.append(card, renderTrustWarning());
const warning = protocolMismatch(PROTOCOL_VERSION, state.serverProtocol);
if (warning) {
section.append(
h("p", { class: "settings-warning-line settings-protocol-warning", role: "alert", text: warning }),
);
}
return section;
}
/**
* The Notifications section (L5). The Android rationale is shown verbatim; the
* status line is the pure permission view for this page's real browser facts.
* Only the explicit control asks for permission, never page load. When the API
* is unavailable, the page is insecure or permission is denied, the wording says
* plainly that the in-app Needs you surface is the only channel — no fake
* notification is ever drawn.
*/
function renderSettingsNotifications() {
const view = notificationPermissionState({
...notificationEnvironment(),
asked: state.notifyAsked,
});
const section = h("section", { class: "settings-section", id: "settingsNotifications" });
section.append(h("h2", { class: "settings-title", text: "Notifications" }));
section.append(h("p", { class: "settings-helper", text: NOTIFICATION_RATIONALE }));
section.append(
h("p", {
id: "settingsNotificationState",
class: `settings-notify-state settings-notify-${view.state}`,
role: "status",
text: view.body,
}),
);
if (view.canRequest) {
section.append(
h(
"div",
{ class: "settings-actions" },
h("button", {
id: "settingsEnableNotifications",
class: "primary",
type: "button",
text: view.actionLabel,
onclick: requestNotifications,
}),
),
);
}
return section;
}
/**
* Ask for notification permission from the operator's explicit click. The asked
* flag is persisted first and the page re-renders from the browser's real answer;
* a refused/dismissed prompt leaves the honest default/denied wording in place.
*/
function requestNotifications() {
persistNotifyAsked(true);
const ctor = globalThis.Notification;
if (typeof ctor !== "function" || !globalThis.isSecureContext) {
renderContent();
return;
}
try {
const result = ctor.requestPermission();
if (result && typeof result.then === "function") {
result.then(
() => renderContent(),
() => renderContent(),
);
return;
}
} catch {
// A browser that refuses the request keeps the honest fallback wording.
}
renderContent();
}
/** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */
function renderTrustWarning() {
return h(
"div",
{ class: "settings-warning" },
h("p", { class: "settings-warning-title", text: TRUST_TITLE }),
h("p", { class: "settings-warning-body", text: TRUST_BODY }),
);
}
/**
* Route a Settings connection control through the page's existing single client,
* mirroring AppViewModel: Disconnect closes the shared socket, Connect is
* connect-only (validate + persist + open — never a toggle), and
* Reconnect re-opens the same validated endpoint now. Nothing here opens a second
* connection.
*/
function runConnectionAction(label) {
const kind = connectionActionKind(label);
if (kind === "disconnect") {
repo.disconnect();
return;
}
if (kind === "reconnect") {
onReconnectClicked();
return;
}
// The `Connect` label must never fall through to the header's toggle: while
// connected that would tear the live socket down (Android's connect() is
// connect-only).
openConfiguredEndpoint();
}
/** Android's `urlError ?: helper` supporting text for the Server URL field. */
function serverUrlSupportingText() {
return state.urlError || SERVER_URL_HELPER;
}
/**
* Update the Server URL field's own error state in place (supporting text,
* aria-invalid and the error tint) so an invalid Connect never needs a full
* re-render and the field being typed in is never rebuilt.
*/
function refreshServerUrlError() {
const field = document.getElementById("settingsServerUrl");
const helper = document.getElementById("settingsUrlHelper");
if (field) {
if (state.urlError) field.setAttribute("aria-invalid", "true");
else field.removeAttribute("aria-invalid");
}
if (helper) {
helper.textContent = serverUrlSupportingText();
helper.classList.toggle("settings-helper-error", Boolean(state.urlError));
if (state.urlError) helper.setAttribute("role", "alert");
else helper.removeAttribute("role");
}
}
function renderSettingsWorkspace() {
const section = h("section", { class: "settings-section" });
section.append(h("h2", { class: "settings-title", text: "Workspace" }));
section.append(
h(
"label",
{ class: "settings-field", for: "settingsWorkspace" },
h("span", { class: "settings-field-label", text: "Workspace path (on the server)" }),
h("input", {
id: "settingsWorkspace",
type: "text",
placeholder: WORKSPACE_PLACEHOLDER,
value: state.workspaceDraft,
spellcheck: "false",
autocomplete: "off",
"aria-describedby": "workspaceHelper",
"aria-invalid": workspaceErrorText(state.workspaceDraft) ? "true" : null,
oninput: (event) => {
state.workspaceDraft = event.target.value;
refreshWorkspaceControls();
},
}),
),
);
section.append(
h(
"p",
{
id: "workspaceHelper",
class: `settings-helper${workspaceErrorText(state.workspaceDraft) ? " settings-helper-error" : ""}`,
},
workspaceSupportingText(),
),
);
section.append(
h("button", {
id: "saveWorkspace",
class: "primary settings-save",
type: "button",
text: "Save workspace",
disabled: !canSaveWorkspace(state.workspaceDraft),
onclick: saveWorkspace,
}),
);
section.append(h("p", { id: "savedWorkspace", class: "settings-saved", text: savedWorkspaceLine(state.workspace) }));
return section;
}
/** Android's `workspaceError ?: helper` supporting text for the workspace field. */
function workspaceSupportingText() {
return workspaceErrorText(state.workspaceDraft) || WORKSPACE_HELPER;
}
/**
* Update the workspace field's dependent controls in place (the helper/error line
* and the Save button's enabled state) so typing never re-renders — and so never
* blurs — the field being typed in.
*/
function refreshWorkspaceControls() {
const helper = document.getElementById("workspaceHelper");
const invalid = Boolean(workspaceErrorText(state.workspaceDraft));
if (helper) {
helper.textContent = workspaceSupportingText();
helper.classList.toggle("settings-helper-error", invalid);
}
const field = document.getElementById("settingsWorkspace");
if (field) {
if (invalid) field.setAttribute("aria-invalid", "true");
else field.removeAttribute("aria-invalid");
}
const save = document.getElementById("saveWorkspace");
if (save) save.disabled = !canSaveWorkspace(state.workspaceDraft);
}
/** Persist the workspace (trimmed) and update the `Saved workspace:` line. */
function saveWorkspace() {
if (!canSaveWorkspace(state.workspaceDraft)) return;
state.workspace = writeWorkspace(localStorage, state.workspaceDraft);
state.workspaceDraft = state.workspace;
// Show the trimmed value that was actually stored, in the field as well as the
// saved line (both updated in place so the keyboard focus is not disturbed).
const field = document.getElementById("settingsWorkspace");
if (field) field.value = state.workspace;
const saved = document.getElementById("savedWorkspace");
if (saved) saved.textContent = savedWorkspaceLine(state.workspace);
}
function openTemplatesFromSettings() {
const route = { kind: "templates" };
pushRoute(route);
applyRoute(route);
}
function renderSettingsTemplates() {
const section = h("section", { class: "settings-section" });
section.append(h("h2", { class: "settings-title", text: "Templates" }));
const card = h(
"button",
{
id: "browseTemplates",
class: "card settings-card",
type: "button",
onclick: openTemplatesFromSettings,
},
// SettingsScreen.kt's row idiom: a leading glyph, the label and secondary
// line, then a forward chevron.
h("span", { class: "settings-card-glyph", "aria-hidden": "true", text: "\u25a4" }),
h(
"span",
{ class: "settings-card-text" },
h("span", { class: "card-name", text: TEMPLATES_CARD_LABEL }),
h("span", { class: "card-desc", text: TEMPLATES_CARD_SECONDARY }),
),
h("span", { class: "settings-card-chevron", "aria-hidden": "true", text: "\u203a" }),
);
section.append(card);
return section;
}
return {
renderSettingsView,
renderSettingsConnection,
requestNotifications,
runConnectionAction,
serverUrlSupportingText,
refreshServerUrlError,
renderSettingsWorkspace,
workspaceSupportingText,
refreshWorkspaceControls,
saveWorkspace,
openTemplatesFromSettings,
renderSettingsTemplates,
};
}
-44
View File
@@ -1,44 +0,0 @@
import { h } from "../dom.js";
import { describeError } from "../format.js";
import { stageSource } from "../stageDefinition.js";
/** Both modes use the same authored source, including unknown/custom blocks. */
export function definitionDocument(detail, key, renderMarkdown) {
const wrap = h("div", { class: "audit-doc stage-definition-document" });
const toggle = h("div", { class: "audit-doc-toggle", role: "group", "aria-label": "Definition view" });
const out = h("div", { class: "audit-doc-body", "aria-live": "polite" });
let mode = "rendered";
let source = null;
const buttons = ["rendered", "raw"].map((value) => h("button", {
class: "audit-doc-mode",
type: "button",
text: value === "raw" ? "Raw" : "Rendered",
onclick: () => { mode = value; draw(); },
}));
const draw = () => {
buttons.forEach((button, index) => {
const selected = mode === ["rendered", "raw"][index];
button.classList.toggle("active", selected);
button.setAttribute("aria-pressed", String(selected));
});
if (source === null) return;
out.replaceChildren(mode === "raw"
? h("pre", { class: "field-block" }, h("code", { text: source }))
: h("div", { class: "field-markdown" }, renderMarkdown(source)));
};
toggle.append(...buttons);
wrap.append(h("div", { class: "audit-doc-bar" }, toggle), out);
out.append(h("div", { class: "muted", text: "Loading stage definition…" }));
draw();
Promise.resolve(detail).then((pipeline) => {
source = stageSource(pipeline?.source, key);
if (source === null) {
out.replaceChildren(h("div", { class: "muted", text: key.startsWith("#")
? "Terminal nodes have no authored stage definition."
: "The server did not include source for this stage. No definition has been reconstructed." }));
} else draw();
}).catch((error) => {
out.replaceChildren(h("div", { class: "muted", text: `Could not load stage definition: ${describeError(error)}` }));
});
return wrap;
}
-384
View File
@@ -1,384 +0,0 @@
// The Templates gallery and detail, including the create-from-template dialog
// and its validate-then-submit flow. Pure wording/model helpers live in
// templates.js; this module owns the DOM and the page's template state.
import { h, kvMono } from "../dom.js";
import { describeError } from "../format.js";
import {
CREATE_ACTION_LABEL,
CREATE_NAME_LABEL,
CREATE_NOTE,
createConfirmLabel,
createDismissLabel,
createFormTitle,
createFormValid,
createSuccessMessage,
createdPipelineName,
effectiveStageType,
templateCard,
templateDetailName,
templateGalleryName,
templateGraphNote,
templateStageCountLabel,
templateStageSummary,
TEMPLATE_UNPARSED_SOURCE_NOTE,
} from "../templates.js";
export function createTemplatesView(rt) {
const { state, repo, modal } = rt;
const renderContent = (...args) => rt.renderContent(...args);
const focusDetailHeading = (...args) => rt.focusDetailHeading(...args);
const pushRoute = (...args) => rt.pushRoute(...args);
const setError = (...args) => rt.setError(...args);
const refreshPipelines = (...args) => rt.views.pipelines.refreshPipelines(...args);
/**
* Reset the template detail/create state that belongs to a selection. Shared by
* selecting a template and opening the gallery from Settings, so the two lists of
* fields can never drift.
*/
function resetTemplateCreateState() {
// The section is sticky across template selections (it is persisted by the shell).
// A different template reseeds the create dialog, so a name typed for one
// template can never be submitted against another.
state.templateCreateOpen = false;
state.templateCreateName = "";
state.templateCreateSending = false;
state.templateCreateError = "";
state.templateCreateCreated = null;
}
/** Clear the selection and everything that belongs to it. */
function resetTemplateSelection() {
state.selectedTemplateKey = null;
resetTemplateCreateState();
}
/** The cached parsed graph for a template key, or null when it did not parse. */
function templateGraphFor(key) {
return state.templateGraphs.has(key) ? state.templateGraphs.get(key) : null;
}
function renderTemplateGallery() {
const pane = h("div", { class: "list gallery" });
if (state.templateLoading && !state.templates.length) {
pane.append(h("div", { class: "muted pad", text: "Loading templates…" }));
return pane;
}
if (!state.templates.length) {
pane.append(h("div", { class: "muted pad", text: "No templates are available on this server." }));
return pane;
}
const cards = h("div", { class: "cards list-scroll" });
for (const entry of state.templates) {
const card = templateCard(entry, templateGraphFor(entry.key));
cards.append(
h(
"button",
{
class: `card${state.selectedTemplateKey === entry.key ? " selected" : ""}`,
"data-template-key": entry.key,
onclick: () => selectTemplate(entry.key),
},
h("span", { class: "card-name", text: templateGalleryName(card.name) }),
h("span", { class: "card-desc", text: card.description }),
h("span", { class: "card-meta", text: templateStageCountLabel(card.stageCount) }),
),
);
}
pane.append(cards);
return pane;
}
function renderTemplateDetail() {
const pane = h("div", { class: "detail" });
const entry = state.templates.find((t) => t.key === state.selectedTemplateKey);
if (!entry) {
pane.append(h("div", { class: "muted pad", text: "Select a template." }));
return pane;
}
const graph = templateGraphFor(entry.key);
pane.append(renderTemplateDetailActions());
pane.append(h("h1", { class: "detail-title", id: "detailTitle", tabindex: "-1", text: templateDetailName(entry) }));
if (state.templateTab === "graph") pane.append(renderTemplateGraphTab(graph));
else if (state.templateTab === "source") pane.append(renderTemplateSourceTab(entry, graph));
else pane.append(renderTemplateSummaryTab(entry, graph));
if (state.templateCreateOpen) pane.append(renderTemplateCreateDialog(entry));
return pane;
}
/**
* The template detail's action row: the one "Create pipeline from this
* template" action (P5), matching the app's top-bar add action. It opens the
* dialog; it never submits on its own.
*/
function renderTemplateDetailActions() {
return h(
"div",
{ class: "detail-actions" },
h("button", {
class: "ghost template-create-open",
type: "button",
text: CREATE_ACTION_LABEL,
onclick: () => openTemplateCreateDialog(),
}),
);
}
/** Open the create dialog with a fresh, empty name; nothing is sent until Create. */
function openTemplateCreateDialog() {
state.templateCreateOpen = true;
state.templateCreateName = "";
state.templateCreateSending = false;
state.templateCreateError = "";
state.templateCreateCreated = null;
renderContent();
}
/** Dismiss the create dialog (never while a validate+submit is in flight). */
function closeTemplateCreateDialog() {
if (state.templateCreateSending) return;
state.templateCreateOpen = false;
state.templateCreateName = "";
state.templateCreateError = "";
state.templateCreateCreated = null;
renderContent();
}
/**
* The create dialog (P5): the title, the one required name field, the note, the
* server's refusal text or the success line, and Create/Cancel (Cancel reads
* Close after a success). Create is disabled while the name is blank or while
* sending; the field locks while sending and after a success. Every server
* string is set with textContent.
*/
function renderTemplateCreateDialog(entry) {
const title = createFormTitle(entry);
const overlay = h("div", {
class: "template-create-dialog",
role: "dialog",
"aria-modal": "true",
"aria-label": title,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeTemplateCreateDialog();
});
const panel = h("div", { class: "template-create-panel" });
panel.append(h("h2", { class: "template-create-title", text: title }));
const field = h("label", { class: "template-create-field" });
field.append(h("span", { class: "template-create-label", text: CREATE_NAME_LABEL }));
field.append(
h("input", {
class: "template-create-name",
type: "text",
value: state.templateCreateName,
spellcheck: "false",
autocomplete: "off",
disabled: state.templateCreateSending || state.templateCreateCreated != null,
oninput: (event) => {
// Update in place (no re-render) so the field keeps focus and its caret;
// only the confirm button's enabled state depends on the name.
state.templateCreateName = event.target.value;
const confirm = overlay.querySelector(".template-create-confirm");
if (confirm) {
confirm.disabled = !createFormValid(state.templateCreateName, {
sending: state.templateCreateSending,
created: state.templateCreateCreated,
});
}
},
}),
);
panel.append(field);
panel.append(h("p", { class: "template-create-note muted", text: CREATE_NOTE }));
if (state.templateCreateError) {
panel.append(h("div", { class: "template-create-error bad", text: state.templateCreateError }));
}
if (state.templateCreateCreated != null) {
panel.append(
h("div", {
class: "template-create-success",
text: createSuccessMessage(state.templateCreateCreated),
}),
);
}
const actions = h("div", { class: "template-create-actions" });
actions.append(
h("button", {
class: "ghost template-create-cancel",
type: "button",
text: createDismissLabel(state.templateCreateCreated),
disabled: state.templateCreateSending,
onclick: closeTemplateCreateDialog,
}),
);
actions.append(
h("button", {
class: "template-create-confirm",
type: "button",
text: createConfirmLabel(state.templateCreateSending),
disabled: !createFormValid(state.templateCreateName, {
sending: state.templateCreateSending,
created: state.templateCreateCreated,
}),
onclick: () => createFromTemplate(entry),
}),
);
panel.append(actions);
overlay.append(panel);
modal.stage("template-create", overlay, {
onClose: () => closeTemplateCreateDialog(),
triggerSelector: ".template-create-open",
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return overlay;
}
/**
* The P5 submit flow, exactly the app's: validate the template's source first
* and, when the server refuses to parse it, show its own error in the dialog and
* send nothing; otherwise submit the source create-only with the chosen name. On
* success remember the created name, refresh the pipeline list so the new row is
* visible and leave the dialog open (Cancel now reads Close); on failure show
* the server's error without closing.
*/
async function createFromTemplate(entry) {
if (
!createFormValid(state.templateCreateName, {
sending: state.templateCreateSending,
created: state.templateCreateCreated,
})
) {
return;
}
const name = state.templateCreateName;
state.templateCreateSending = true;
state.templateCreateError = "";
renderContent();
try {
await repo.validate(entry.source);
} catch (error) {
state.templateCreateSending = false;
state.templateCreateError = describeError(error);
renderContent();
return;
}
try {
const detail = await repo.submit(name, entry.source);
state.templateCreateSending = false;
state.templateCreateCreated = createdPipelineName(detail, name);
await refreshPipelines();
} catch (error) {
state.templateCreateSending = false;
state.templateCreateError = describeError(error);
}
renderContent();
}
function renderTemplateSummaryTab(entry, graph) {
const wrap = h("div", { class: "tabbody" });
if ((entry.description ?? "").trim()) {
wrap.append(h("p", { class: "body", text: entry.description }));
}
wrap.append(h("div", { class: "kv" }, kvMono("Key", entry.key)));
wrap.append(
h("div", { class: "meta-line", text: templateStageCountLabel(graph?.stages?.length ?? null) }),
);
if (entry.scheduled) wrap.append(h("div", { class: "meta-line", text: "Includes a schedule" }));
const summary = templateStageSummary(graph);
if (summary.note) {
wrap.append(h("div", { class: "muted pad", text: summary.note }));
return wrap;
}
wrap.append(h("h3", { text: "Stages" }));
const ul = h("ul", { class: "stages" });
for (const stage of summary.stages) {
ul.append(
h(
"li",
{},
h("code", { text: stage.key }),
h("span", { class: "chip", text: effectiveStageType(stage.type) }),
),
);
}
wrap.append(ul);
return wrap;
}
function renderTemplateGraphTab(graph) {
const wrap = h("div", { class: "tabbody" });
wrap.append(h("p", { class: "muted", text: templateGraphNote(graph) }));
return wrap;
}
function renderTemplateSourceTab(entry, graph) {
const wrap = h("div", { class: "tabbody" });
if (graph == null) {
wrap.append(h("p", { class: "muted", text: TEMPLATE_UNPARSED_SOURCE_NOTE }));
}
wrap.append(
h(
"div",
{ class: "codeblock" },
h("div", { class: "codeblock-label", text: "Definition source" }),
h("pre", { class: "codeblock-body", text: entry.source ?? "" }),
),
);
return wrap;
}
/**
* Loads the template catalogue, then validates each template's source once and
* caches the parsed graph (null when it did not parse) so a card's stage count
* and the detail's stage list read the same result and can never disagree.
*/
async function loadTemplates(force = false) {
state.templateLoading = true;
state.error = "";
renderContent();
try {
state.templates = await repo.listTemplates();
for (const entry of state.templates) {
if (force || !state.templateGraphs.has(entry.key)) {
state.templateGraphs.set(entry.key, await validateTemplate(entry));
}
}
state.templateLoading = false;
renderContent();
} catch (err) {
state.templateLoading = false;
setError(err);
}
}
/** The parsed graph for a template, or null when the server cannot parse its source. */
async function validateTemplate(entry) {
try {
return await repo.validate(entry.source);
} catch {
return null;
}
}
function selectTemplate(key) {
if (key) pushRoute({ kind: "template", key });
else pushRoute({ kind: "templates" });
state.selectedTemplateKey = key || null;
resetTemplateCreateState();
renderContent();
if (key) focusDetailHeading();
}
return {
resetTemplateCreateState,
resetTemplateSelection,
renderTemplateGallery,
renderTemplateDetail,
loadTemplates,
selectTemplate,
};
}