web: attention / "Needs you" surface — bell, sheet, dismissals (R15, R2)

This commit is contained in:
2026-10-19 04:52:34 +01:00
parent 9555bfe58f
commit f3bc6ed126
6 changed files with 1107 additions and 5 deletions
+277 -3
View File
@@ -133,6 +133,18 @@ import {
runChangesHeader,
runChangesNote,
} from "./changes.js";
import {
ATTENTION_STORAGE_KEY,
AttentionKind,
attentionBadgeLabel,
attentionDismissAll,
attentionDismiss,
attentionDismissalSnapshot,
attentionEntries,
attentionRowDescription,
decodeAttentionDismissals,
encodeAttentionDismissals,
} from "./attention.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
@@ -209,6 +221,14 @@ const state = {
runSections: new Set(),
runStagePane: null,
runStageSections: new Set(),
// The attention / "Needs you" surface (R15). `attentionDismissed` is the set
// of `{runId}:{kind}` identities the operator has explicitly dealt with, loaded
// once at boot from localStorage. `attentionSheetOpen` drives the sheet and
// `attentionSnapshot` holds the entries captured when it opened, so Clear all
// only ever removes identities the operator actually saw.
attentionDismissed: new Set(),
attentionSheetOpen: false,
attentionSnapshot: null,
};
let runPoll = null;
@@ -260,7 +280,10 @@ const header = h("header", { class: "topbar" });
// the header (never fixed/overlaying), so it can never cover the content.
const connBanner = h("div", { id: "connBanner", class: "conn-banner", hidden: true });
const content = h("main", { id: "content" });
document.body.append(header, connBanner, content);
// The attention sheet lives in its own layer so it can overlay any view without
// being torn down by a content re-render; renderAttentionSheet rebuilds it.
const attentionLayer = h("div", { id: "attentionLayer" });
document.body.append(header, connBanner, content, attentionLayer);
/** Whether the URL field currently holds a usable endpoint for Reconnect. */
function endpointConfigured() {
@@ -297,11 +320,77 @@ function renderHeader() {
h("span", { class: "state", id: "stateBadge" }, connectionLabel()),
);
header.replaceChildren(
h("div", { class: "brand" }, h("strong", { text: "Pipelines" }), h("span", { class: "muted", text: "web spike" })),
h(
"div",
{ class: "brand" },
h("strong", { text: "Pipelines" }),
h("span", { class: "muted", text: "web spike" }),
renderAttentionBell(),
),
h("div", { class: "connbar" }, ...controls),
);
}
/**
* The attention bell action, shown in the top bar on every view (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(h("span", { class: "attention-bell-glyph", "aria-hidden": "true", text: "\uD83D\uDD14" }));
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).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 button = document.querySelector("#attentionBell");
if (!button) return;
const count = attentionCount();
const label = attentionBadgeLabel(count);
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 persistent connection banner. Its copy/tone come from the pure
* `bannerState`, and it also carries the last server build and a protocol
@@ -327,10 +416,183 @@ function connectionLabel() {
return h("span", { class: `dot ${info.tone}`, text: info.text });
}
// --- Attention / "Needs you" surface (R15) ---------------------------------
/**
* The attention sheet: the ordered list from the pure `attentionEntries` model,
* opened from the bell in the top bar. 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();
return;
}
const entries = attentionEntries(state.runs, state.attentionDismissed);
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" });
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));
}
const sheet = h("div", { class: "attention-sheet-panel", tabindex: "-1" }, head, body);
overlay.append(sheet);
attentionLayer.replaceChildren(overlay);
}
/** One attention row: status icon, the two text lines, and a trailing Dismiss. */
function renderAttentionRow(entry) {
const glyphState = entry.kind === AttentionKind.Decision ? "waiting" : "failed";
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": "Dismiss",
title: "Dismiss",
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),
);
render();
document.querySelector(".attention-sheet-close")?.focus();
}
/** Close the sheet, dropping the snapshot; focus returns to the bell. */
function closeAttentionSheet({ restoreFocus = true } = {}) {
if (!state.attentionSheetOpen) return;
state.attentionSheetOpen = false;
state.attentionSnapshot = null;
render();
if (restoreFocus) document.querySelector("#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.
}
}
/** The dismissed identities from storage at boot; anything unreadable is empty. */
function loadAttentionDismissed() {
try {
return decodeAttentionDismissals(localStorage.getItem(ATTENTION_STORAGE_KEY));
} catch {
return new Set();
}
}
function render() {
renderHeader();
renderBanner();
renderContent();
renderAttentionSheet();
}
function renderContent() {
@@ -2366,6 +2628,9 @@ async function loadCurrentView(force = false) {
}
state.loading = false;
renderContent();
// The run list the attention surface derives from has just (re)loaded, so
// bring the bell's badge up to date.
refreshAttentionBell();
// Keep the current selection fresh after a refresh.
if (force && state.view === "runs" && state.selectedRunId) {
await selectRun(state.selectedRunId, { silent: true });
@@ -2543,10 +2808,16 @@ client.addEventListener("state", (event) => {
// The stage pane is a modal dialog: Escape closes it (a stacked overlay — the
// artifact viewer or the diff viewer, when either is above — owns Escape first).
// The attention sheet, when open, is the topmost overlay and owns Escape first.
// Registered once; it is a no-op when no pane is open.
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
if (state.attentionSheetOpen) {
event.preventDefault();
closeAttentionSheet();
return;
}
if (
event.key === "Escape" &&
state.runStagePane &&
!document.querySelector(".artifact-viewer") &&
!document.querySelector(".change-viewer")
@@ -2565,4 +2836,7 @@ document.addEventListener("visibilitychange", () => {
window.addEventListener("online", onForegroundActive);
// Prefill from a previous session only; the user still confirms with Connect.
// The attention surface's dismissed identities are loaded once here, before the
// first render, so the bell's badge is correct from the very first paint.
state.attentionDismissed = loadAttentionDismissed();
render();
+209
View File
@@ -0,0 +1,209 @@
// 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, the live
// `run_event` fold, is a separate item: when it lands it will feed these same
// pure functions the pushed summaries, and neither the ordering nor the wording
// will change.
//
// 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) {
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) {
const dismissedKeys =
dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []);
return (runs ?? [])
.map((run) => {
const kind = attentionKindOf(run?.status);
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 ?? "");
return {
runId: run.id,
pipeline: String(run.name ?? ""),
label: title !== "" ? title : String(run.name ?? ""),
kind,
detail: attentionDetail(kind, run),
recency: finished.trim() !== "" ? finished : String(run.created_at ?? ""),
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),
);
}
/**
* 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;
}