import { Fragment } from "preact";
import { useState, useEffect, useRef } from "preact/hooks";
import "./tasks.css";
import { api, classifyActionError } from "../base/api.jsx";
import { ago } from "../base/dom.jsx";
import { Pill } from "../base/pill.jsx";
import { statTile as renderStatTile } from "../base/statTile.jsx";
import { taskRowA11y } from "./task-row.jsx";
import { initialTaskFilter, taskMatchesStatus } from "./task-filters.jsx";
import { describeTimelineEvent } from "./timeline-event.jsx";
import { TaskLogPanel, logCacheKey } from "./task-logs.jsx";
import { actionFor, statusIds, statusKind, statusLabel } from "../base/task-meta.jsx";
// The shell's global reduced-motion rule switches CSS transitions and
// animations, NOT the JS smooth scroll this page performs when it reveals a
// deep-linked row. The decision therefore has to be made here, in JavaScript,
// and is exported so it can be tested directly (jsdom implements neither
// matchMedia nor scrollIntoView).
export function prefersReducedMotion() {
return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true;
}
export function revealBehavior() {
return prefersReducedMotion() ? "auto" : "smooth";
}
function StatTileNode(props) {
const ref = useRef(null);
useEffect(() => {
if (ref.current) ref.current.replaceChildren(renderStatTile(props));
}, [props]);
return
;
}
// renderActionError distinguishes a refused action ("you cannot do that" --
// bad input, a conflicting task state) from a broken one (5xx, network drop,
// timeout -- "try again or check the daemon"), and special-cases an expired
// session with a prompt to reload rather than either framing.
function renderActionError({ kind, message }) {
if (kind === "session-expired") {
return (
Your session has expired.{" "}
);
}
if (kind === "refused") {
return {message} — you can't do that.;
}
return {message} — try again, or check the daemon.;
}
function Empty({ title, detail }) {
return (
{title}
{detail &&
{detail}
}
);
}
// The open log pane loads its own attempt's log whenever it is showing an
// attempt it has no cached entry for: a retry moves the pane to a new attempt,
// a forced reload drops its own entry, and a row can be reopened long after the
// click that first opened it. Loading only from that click is what would leave
// the pane sitting on "Loading…" with nothing fetching it.
function TaskLogSection({ taskId, attempt, state, onLoad, onRetry }) {
const load = useRef(onLoad);
load.current = onLoad;
useEffect(() => {
if (state === undefined) load.current();
}, [state]);
return ;
}
function TasksApp({ query }) {
const [tasks, setTasks] = useState(null);
const [error, setError] = useState(null);
const [filterStatus, setFilterStatus] = useState(() => initialTaskFilter(query));
const [search, setSearch] = useState("");
const requestedTask = Number(query.get("task"));
const initialExpandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null;
const [expandedId, setExpandedId] = useState(initialExpandedId);
const [focusRequestedTask, setFocusRequestedTask] = useState(initialExpandedId !== null);
const [eventCache, setEventCache] = useState(new Map());
const [logCache, setLogCache] = useState(new Map());
const logRequests = useRef(new Set());
const [logsExpanded, setLogsExpanded] = useState(new Set());
const [actionErrors, setActionErrors] = useState(new Map());
const [actionsInFlight, setActionsInFlight] = useState(new Set());
const load = async () => {
try {
setError(null);
const res = await api.tasks();
setTasks(res);
if (expandedId && res.some(t => String(t.id) === String(expandedId))) {
if (!eventCache.has(expandedId)) {
loadTimeline(expandedId);
}
}
return res;
} catch (err) {
setError(String(err.message || err));
setTasks(null);
return null;
}
};
useEffect(() => {
load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const loadTimeline = async (id) => {
try {
const events = await api.task(id);
setEventCache(prev => new Map(prev).set(id, events || []));
} catch {
setEventCache(prev => new Map(prev).set(id, null));
}
};
const loadTaskLogs = async (id, attempt, { force = false } = {}) => {
// The cache entry is identified by the task AND the attempt: a task alone
// cannot tell two runs apart, so a retry used to leave the previous
// attempt's log on screen under the new run. One request per key, unless a
// control explicitly asks for the read again.
const key = logCacheKey(id, attempt);
if (logRequests.current.has(key) && !force) return;
logRequests.current.add(key);
if (force) {
setLogCache(prev => {
const next = new Map(prev);
next.delete(key);
return next;
});
}
try {
const res = await api.taskLogs(id, { attempt: attempt || undefined, limit: 500 });
setLogCache(prev => new Map(prev).set(key, res));
} catch {
setLogCache(prev => new Map(prev).set(key, null));
}
};
// An operator action can change a task's timeline -- a retry begins a new
// attempt -- so the events cached for that task are dropped rather than served
// against the new state. The log cache needs no invalidation here: its key
// already carries the attempt, so the new run is a different entry and can
// never be answered by the ended attempt's log.
const invalidateTaskCaches = (id) => {
setEventCache(prev => {
const next = new Map(prev);
next.delete(id);
return next;
});
};
const performAction = async (id, action) => {
setActionErrors(prev => {
const next = new Map(prev);
next.delete(id);
return next;
});
setActionsInFlight(prev => new Set(prev).add(id));
try {
await api.taskAction(id, action);
setActionsInFlight(prev => {
const next = new Set(prev);
next.delete(id);
return next;
});
if (action === "archive") setExpandedId(null);
invalidateTaskCaches(id);
const res = await load();
// A row that is still open reloads against the attempt the task now has;
// otherwise it would sit on "Loading…" with its cache entry gone.
const updated = Array.isArray(res) ? res.find(t => String(t.id) === String(id)) : null;
if (updated && expandedId === id) {
loadTimeline(id);
}
} catch (err) {
setActionsInFlight(prev => {
const next = new Set(prev);
next.delete(id);
return next;
});
setActionErrors(prev => new Map(prev).set(id, classifyActionError(err)));
}
};
useEffect(() => {
if (focusRequestedTask && expandedId && tasks) {
setFocusRequestedTask(false);
// requestAnimationFrame to ensure it has rendered
requestAnimationFrame(() => {
const row = document.getElementById(`task-row-${expandedId}`);
if (row) {
row.focus({ preventScroll: true });
// Optional call: focusing a deep-linked row is a nicety, and not every
// environment implements scrollIntoView on an element.
row.scrollIntoView?.({ block: "center", behavior: revealBehavior() });
}
});
}
}, [focusRequestedTask, expandedId, tasks]);
const toggleTask = (id, event) => {
if (event) event.stopPropagation();
const isExpanding = expandedId !== id;
setExpandedId(isExpanding ? id : null);
if (isExpanding) {
loadTimeline(id);
}
};
const toggleLogs = (id) => {
setLogsExpanded(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const renderSummary = () => {
if (!tasks) return null;
const total = tasks.length;
const counts = {};
for (const t of tasks) counts[t.status] = (counts[t.status] || 0) + 1;
const working = counts.running || 0;
const needsYou = (counts.waiting_human || 0) + (counts.parked || 0);
const delivered = (counts.merged || 0) + (counts.pr_open || 0);
return (