Files
archie/ui/src/tasks/tasks.jsx
T
sam 278b7fc600 refactor(ui): finish the Preact port and delete the imperative DOM layer
The dashboard was a hybrid: a Preact page per route rendered into a shell
built by a hand-rolled el() helper. Every route was Preact and the shell was
not, which is why nothing failed -- the last of the vanilla layer was the
part that composed the app.

Removed:
- ui/src/base/dom.jsx -- el/append/mount, the unused pill/empty pair, and a
  statusKind re-export that duplicated task-meta for one caller
- ui/src/chat/chat-tools.jsx and the el-based bubble builders in
  chat-render.jsx: nothing in src/ called them, only their own tests did
- the chatPage() DOM bridge, which existed so an imperative shell could embed
  a VNode

Ported:
- base/icons.jsx: icon() -> <Icon>; the glyph path table stays data
- base/gauge.jsx, base/statTile.jsx, base/log-row.jsx: DOM builders ->
  components, with inline SVG instead of innerHTML
- base/format.jsx: ago/compact, which never were DOM
- chat/markdown.jsx: renderMarkdown() -> <ChatMarkdown>, so a streamed reply
  is diffed rather than rebuilt block by block
- main.jsx: shell, nav, jump-to search, theme and chat drawer are one App;
  pages still render into one long-lived outlet

Routing stays wired at import rather than from an effect. A page installs its
own hash-sensitive state as it mounts, and task detail writes its tab
selection back with replaceState as it settles: if the outgoing page is still
mounted when the hashchange lands it canonicalises the URL back to its own
route and the navigation is silently lost. The outlet and the two
navigation-owned pieces of chrome are published through a callback ref, which
runs at commit time, before any page effect.

Tests: dom.test.js (el) and chat-tools.test.js are gone. The statTile cases
in dom.test.js were not dropped -- they pinned the zero-value headline bug
that made fresh installs look broken, and moved to test/statTile.test.js
against the component. log-row and chat-markdown render their components.

ui/dist rebuilt: index.js 146977 -> 146010 bytes.

Closes archie-core-v9gv.2 and archie-core-v9gv.
2026-09-19 03:35:14 +10:00

602 lines
20 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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/format.jsx";
import { Pill } from "../base/pill.jsx";
import { StatTile } 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";
}
// 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 (
<span className="task-action-error task-action-error-session">
Your session has expired.{" "}
<button className="button btn btn-small" type="button" onClick={() => window.location.reload()}>
Reload to sign in
</button>
</span>
);
}
if (kind === "refused") {
return <span className="task-action-error task-action-error-refused">{message} — you can't do that.</span>;
}
return <span className="task-action-error task-action-error-broken">{message} — try again, or check the daemon.</span>;
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
// 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 <TaskLogPanel state={state} taskId={taskId} attempt={attempt} onRetry={onRetry} />;
}
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 (
<div className="grid grid-4 task-summary">
<StatTile
label="Total tasks"
value={total}
compare={total ? "Everything archied has ever picked up" : "No tasks yet"}
/>
<StatTile
label="Working now"
value={working}
compare={total ? `${working} of ${total} in progress` : "Nothing running"}
/>
<StatTile
label="Needs you"
value={needsYou}
compare={needsYou ? "Parked or awaiting a reply" : "Nothing is blocked"}
goodDirection="down"
/>
<StatTile
label="Delivered"
value={delivered}
compare={total ? `${Math.round((delivered / total) * 100)}% of all tasks` : "No tasks yet"}
/>
</div>
);
};
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 (
<button
key={action}
className={cls}
type="button"
disabled={busy}
onClick={(e) => {
e.stopPropagation();
if (confirmText && !window.confirm(confirmText)) return;
performAction(t.id, action);
}}
>
{meta.label}
</button>
);
}).filter(Boolean);
if (!controls.length && !errorMsg) return "—";
return <div className="task-actions">{errorMsg}{controls}</div>;
};
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 (
<button className="btn btn-small" type="button" disabled title={`${label} is unavailable`}>
{label}
</button>
);
}
return (
<a className="btn btn-small" href={href} target="_blank" rel="noreferrer" onClick={e => e.stopPropagation()}>
{label}
</a>
);
};
const repoLink = (t) => {
const base = t.repo_url;
if (!base) return null;
return (
<a
className="task-source-link"
href={base}
target="_blank"
rel="noreferrer"
title={`Open ${t.owner}/${t.repo} on the forge`}
onClick={e => e.stopPropagation()}
>
{t.owner}/{t.repo}
</a>
);
};
const issueLink = (t) => {
const href = t.issue_url;
if (t.source === "chat" || !href || !t.issue_number) return null;
return (
<a
className="task-source-link"
href={href}
target="_blank"
rel="noreferrer"
title={`Open issue #${t.issue_number} on the forge`}
onClick={e => e.stopPropagation()}
>
#{t.issue_number}
</a>
);
};
const renderTimelineRow = (t) => {
const logKey = logCacheKey(t.id, t.attempt);
const cached = eventCache.get(t.id);
const logsExpandedForTask = logsExpanded.has(t.id);
return (
<tr className="task-timeline-row" id={`task-timeline-${t.id}`}>
<td colSpan={8}>
<div className="task-detail-actions">
<div className="task-decision-title">Available actions</div>
{renderTaskActions(t)}
</div>
{t.status === "waiting_human" && t.plan && (
<div className="task-decision">
<div className="task-decision-title">Decision required</div>
<div className="task-decision-plan">{t.plan}</div>
</div>
)}
{t.status === "parked" && t.park_reason && (
<div className="task-decision">
<div className="task-decision-title">Park reason</div>
<div className="task-decision-plan">{t.park_reason}</div>
</div>
)}
{cached === undefined ? (
<div className="task-timeline-loading">Loading timeline…</div>
) : cached === null ? (
<div className="task-timeline-error">
<div className="task-timeline-title">Could not load timeline</div>
<div className="task-timeline-detail">archied did not answer for this task's events. It may be restarting — retry, or check the daemon.</div>
<button className="btn" onClick={() => loadTimeline(t.id)}>Retry</button>
</div>
) : cached.length ? (
<ul className="task-timeline">
{cached.map((ev, i) => {
const desc = describeTimelineEvent(ev);
return (
<li className="task-timeline-entry" key={i}>
<span className="task-timeline-dot"></span>
<div>
<div className="task-timeline-kind">{desc.title}</div>
{desc.detail && <div className="task-timeline-detail">{desc.detail}</div>}
<div className="task-timeline-when">{ago(ev.at)}</div>
</div>
</li>
);
})}
</ul>
) : (
<Empty title="No events yet" detail="This task has not recorded any transitions." />
)}
<div className="task-logs-section">
<div className="task-decision-title">
Attempt log
<button className="btn btn-small" onClick={() => toggleLogs(t.id)} style={{ marginLeft: "10px" }}>
{logsExpandedForTask ? "Hide" : "Show"}
</button>
</div>
{logsExpandedForTask && (
<TaskLogSection
taskId={t.id}
attempt={t.attempt}
state={logCache.has(logKey) ? logCache.get(logKey) : undefined}
onLoad={() => loadTaskLogs(t.id, t.attempt)}
onRetry={() => loadTaskLogs(t.id, t.attempt, { force: true })}
/>
)}
</div>
</td>
</tr>
);
};
const renderBody = () => {
if (error) {
return (
<tr>
<td colSpan={8}>
<Empty title="Cannot reach archied" detail={error} />
</td>
</tr>
);
}
if (!tasks) {
return (
<tr>
<td colSpan={8}>
<div className="task-timeline-loading">Loading tasks...</div>
</td>
</tr>
);
}
if (!tasks.length) {
return (
<tr>
<td colSpan={8}>
<Empty title="No tasks yet" detail="Tasks appear here once archied picks up an issue to work." />
</td>
</tr>
);
}
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 (
<tr>
<td colSpan={8}>
<Empty title="No matching tasks" detail="Try a different search or status filter." />
</td>
</tr>
);
}
return filtered.map(t => {
const expanded = expandedId === t.id;
const timelineID = `task-timeline-${t.id}`;
return (
<Fragment key={t.id}>
<tr
className="task-row"
id={`task-row-${t.id}`}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleTask(t.id, e);
}
}}
onClick={(e) => toggleTask(t.id, e)}
{...taskRowA11y(t, expanded)}
>
<td className="mono" data-label="Repository">
<button
className="task-expand"
type="button"
aria-expanded={String(expanded)}
aria-controls={timelineID}
aria-label={`${expanded ? "Collapse" : "Expand"} timeline for ${t.title || "untitled task"}`}
onClick={(e) => toggleTask(t.id, e)}
>
{expanded ? "−" : "+"}
</button>
{repoLink(t) ?? `${t.owner}/${t.repo}`}
</td>
<td className="mono" data-label="Issue">
{issueLink(t) ?? `#${t.issue_number}`}
</td>
<td className="strong" data-label="Title">
<a
className="task-detail-link"
href={`#/tasks/${t.id}`}
title="Open the run detail for this task"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
{t.title || "(untitled)"}
</a>
</td>
<td data-label="Status">
<Pill text={statusLabel(t.status)} kind={statusKind(t.status)} />
</td>
<td data-label="Workflow">{t.workflow || "—"}</td>
<td data-label="Stage">{t.stage || "—"}</td>
<td
data-label="Last activity"
title={t.created_at ? `Created ${ago(t.created_at)}` : ""}
>
{ago(t.updated_at)}
</td>
<td data-label="Actions">{renderTaskActions(t)}</td>
</tr>
{expanded && renderTimelineRow(t)}
</Fragment>
);
});
};
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Tasks</h1>
<p className="page-sub">Every issue archied has picked up, and where it stands.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
{error ? (
<div className="grid grid-4 task-summary">
<div className="card">
<Empty title="Cannot reach archied" detail={error} />
</div>
</div>
) : (
renderSummary()
)}
<div className="card">
<div className="card-head">
<div>
<h2 className="card-title">All tasks</h2>
<p className="card-sub">Click a row for its timeline</p>
</div>
<div className="task-filters">
<input
className="task-search"
type="search"
placeholder="Search by title or repo…"
value={search}
onInput={e => setSearch(e.target.value.trim().toLowerCase())}
/>
<select
className="task-filter"
value={filterStatus}
onChange={e => setFilterStatus(e.target.value)}
>
<option value="">All statuses</option>
<option value="needs_you">Needs you</option>
{statusIds().map(value => (
<option key={value} value={value}>{statusLabel(value)}</option>
))}
</select>
</div>
</div>
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Repo", "Issue", "Title", "Status", "Workflow", "Stage", "Last activity", "Action"].map(hText => (
<th key={hText}>{hText}</th>
))}
</tr>
</thead>
<tbody>{renderBody()}</tbody>
</table>
</div>
</div>
</div>
);
}
export function tasksPage(query) {
return <TasksApp query={query} />;
}