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 (
); }; const renderTaskActions = (t) => { const actionError = actionErrors.get(t.id); const errorMsg = actionError ? renderActionError(actionError) : null; const busy = actionsInFlight.has(t.id); const variantToken = (kind) => kind === "quiet" ? "btn-quiet" : kind === "danger" ? "btn-danger" : ""; const controls = (t.actions || []).map(action => { const meta = actionFor(action); if (!meta) return null; const title = t.title || "this task"; const confirmText = meta.confirm ? meta.confirm.replaceAll("{title}", title) : undefined; const cls = ["button", "btn", "btn-small", variantToken(meta.kind)].filter(Boolean).join(" "); if (meta.kind === "link") { if (action === "open_pr") return taskLink(t, "pull_request", t.pr_number, meta.label); if (action === "open_issue") return taskLink(t, "issue", t.issue_number, meta.label); } return ( ); }).filter(Boolean); if (!controls.length && !errorMsg) return "—"; return
{errorMsg}{controls}
; }; const taskLink = (t, kind, number, label) => { const href = kind === "issue" ? t.issue_url : t.pr_url; if (!href || !number || (kind === "issue" && t.source === "chat")) { return ( ); } return ( e.stopPropagation()}> {label} ); }; const repoLink = (t) => { const base = t.repo_url; if (!base) return null; return ( e.stopPropagation()} > {t.owner}/{t.repo} ); }; const issueLink = (t) => { const href = t.issue_url; if (t.source === "chat" || !href || !t.issue_number) return null; return ( e.stopPropagation()} > #{t.issue_number} ); }; const renderTimelineRow = (t) => { const logKey = logCacheKey(t.id, t.attempt); const cached = eventCache.get(t.id); const logsExpandedForTask = logsExpanded.has(t.id); return (
Available actions
{renderTaskActions(t)}
{t.status === "waiting_human" && t.plan && (
Decision required
{t.plan}
)} {t.status === "parked" && t.park_reason && (
Park reason
{t.park_reason}
)} {cached === undefined ? (
Loading timeline…
) : cached === null ? (
Could not load timeline
archied did not answer for this task's events. It may be restarting — retry, or check the daemon.
) : cached.length ? ( ) : ( )}
Attempt log
{logsExpandedForTask && ( loadTaskLogs(t.id, t.attempt)} onRetry={() => loadTaskLogs(t.id, t.attempt, { force: true })} /> )}
); }; const renderBody = () => { if (error) { return ( ); } if (!tasks) { return (
Loading tasks...
); } if (!tasks.length) { return ( ); } const filtered = tasks.filter(t => { if (!taskMatchesStatus(t, filterStatus)) return false; if (!search) return true; const hay = `${t.title} ${t.repo}`.toLowerCase(); return hay.includes(search); }); if (!filtered.length) { return ( ); } return filtered.map(t => { const expanded = expandedId === t.id; const timelineID = `task-timeline-${t.id}`; return ( { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleTask(t.id, e); } }} onClick={(e) => toggleTask(t.id, e)} {...taskRowA11y(t, expanded)} > {repoLink(t) ?? `${t.owner}/${t.repo}`} {issueLink(t) ?? `#${t.issue_number}`} e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} > {t.title || "(untitled)"} {t.workflow || "—"} {t.stage || "—"} {ago(t.updated_at)} {renderTaskActions(t)} {expanded && renderTimelineRow(t)} ); }); }; return (

Tasks

Every issue archied has picked up, and where it stands.

{error ? (
) : ( renderSummary() )}

All tasks

Click a row for its timeline

setSearch(e.target.value.trim().toLowerCase())} />
{["Repo", "Issue", "Title", "Status", "Workflow", "Stage", "Last activity", "Action"].map(hText => ( ))} {renderBody()}
{hText}
); } export function tasksPage(query) { return ; }