fix(webui): wire the Logs page to per-task attempt-log detail

GET /api/tasks/{id}/logs was fully working -- internal/logging's
decode() already captures every JSON field generically (stage,
tokens, iterations, model, everything) -- but nothing in the
dashboard ever called it. The only Logs page hit the daemon-wide
feed, which never carries this per-stage/per-agent-run detail in the
first place. An operator could never see why a task took as long as
it did or its token spend breakdown, even though the daemon already
recorded and could already serve it.

Adds a collapsible attempt-log section to each task's existing
timeline drill-down, reusing the daemon-wide page's row rendering
(extracted to ui/src/base/log-row.js as the shared second consumer).
This commit is contained in:
sam committed 2026-09-02 21:26:52 +10:00
1 parent 52a460ebf9
commit a9375a2899
8 files changed
+249 -41

No files matched your search

+1
View File
@@ -111,6 +111,7 @@ export const api = {
return res.json();
},
logs: (params) => req("/api/logs" + qs(params)),
taskLogs: (id, params) => req(`/api/tasks/${id}/logs` + qs(params)),
captures: (limit) => req("/api/captures" + qs({ limit })),
mappings: () => req("/api/mappings"),
mappingCreate: async (mapping) => {
+50
View File
@@ -0,0 +1,50 @@
import { el } from "./dom.js";
/**
* Shared log-entry rendering. Both the daemon-wide log page
* (ui/src/logs/logs.js) and a task's own attempt log
* (ui/src/tasks/task-logs.js) render the same Entry shape from
* internal/logging, so the row markup lives here rather than being
* duplicated a second time -- see CLAUDE.md's "extract to base on the
* second distinct consumer".
*/
export function levelKind(level) {
switch ((level || "").toUpperCase()) {
case "ERROR":
return "danger";
case "WARN":
return "warn";
case "DEBUG":
return "idle";
default:
return "info";
}
}
export function logRow(entry) {
const fields = entry.fields || {};
return el(
`div.log-row.log-${levelKind(entry.level)}`,
el("span.log-time.mono", shortTime(entry.time)),
el("span.log-level", (entry.level || "info").toUpperCase()),
el(
"span.log-body",
el("span.log-msg", entry.message || entry.msg || ""),
...Object.entries(fields).map(([k, v]) =>
el("span.log-field", el("span.log-field-key", k), String(fmtValue(v))),
),
),
);
}
export function fmtValue(v) {
if (v == null) return "";
return typeof v === "object" ? JSON.stringify(v) : v;
}
export function shortTime(value) {
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) return "--:--:--";
return d.toTimeString().slice(0, 8);
}
+2 -41
View File
@@ -1,6 +1,7 @@
import "./logs.css";
import { api, subscribeLogs } from "../base/api.js";
import { el, empty, mount, pill } from "../base/dom.js";
import { logRow } from "../base/log-row.js";
/**
* The log view: history from the file on disk, then live lines appended from
@@ -20,19 +21,6 @@ const LEVELS = [
{ value: "DEBUG", label: "Debug only" },
];
function levelKind(level) {
switch ((level || "").toUpperCase()) {
case "ERROR":
return "danger";
case "WARN":
return "warn";
case "DEBUG":
return "idle";
default:
return "info";
}
}
export function logsPage() {
const root = el("div");
const list = el("div.log-list");
@@ -162,7 +150,7 @@ export function logsPage() {
mount(list, empty(durableUnavailable ? "Durable history unavailable" : "Nothing matches", durableUnavailable ? "Live daemon logs will appear here while this page is open." : "Try a wider level or clear the search."));
return;
}
mount(list, ...entries.map(row));
mount(list, ...entries.map(logRow));
list.scrollTop = list.scrollHeight;
}
@@ -186,33 +174,6 @@ function entryKey(entry) {
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
}
function row(entry) {
const fields = entry.fields || {};
return el(
`div.log-row.log-${levelKind(entry.level)}`,
el("span.log-time.mono", shortTime(entry.time)),
el("span.log-level", (entry.level || "info").toUpperCase()),
el(
"span.log-body",
el("span.log-msg", entry.message || entry.msg || ""),
...Object.entries(fields).map(([k, v]) =>
el("span.log-field", el("span.log-field-key", k), String(fmtValue(v))),
),
),
);
}
function fmtValue(v) {
if (v == null) return "";
return typeof v === "object" ? JSON.stringify(v) : v;
}
function shortTime(value) {
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) return "--:--:--";
return d.toTimeString().slice(0, 8);
}
function sameList(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
+35
View File
@@ -0,0 +1,35 @@
import { el, empty } from "../base/dom.js";
import { logRow } from "../base/log-row.js";
/**
* Renders one task's persisted attempt log (GET /api/tasks/:id/logs) --
* stage timings, iteration counts, model, token/prompt/completion/cached
* breakdowns -- the detail the daemon-wide log page never carries because it
* only sees the daemon's own component-scoped lines.
*
* `state` is one of the values loadTaskLogs (in tasks.js) puts in its cache:
* undefined while loading, null on fetch failure, or the API response body
* once it lands. Row rendering itself is shared with the daemon-wide log via
* ui/src/base/log-row.js -- this module only owns the task-attempt framing
* and the "no persisted log for this attempt" / "log unavailable" states.
*/
export function taskLogPanel(state, opts = {}) {
if (state === undefined) {
return el("div.task-log-loading", "Loading attempt log…");
}
if (state === null) {
return el(
"div.task-log-error",
el("div.task-timeline-detail", "Could not load this attempt's log."),
el("button.btn", { onclick: opts.onRetry }, "Retry"),
);
}
if (state.disabled) {
return empty("No persisted log for this attempt", "Task logging is optional and was not enabled for this run.");
}
const entries = state.entries || [];
if (!entries.length) {
return empty("Nothing recorded", "This attempt's log file has no entries matching the current filter.");
}
return el("div.log-list.task-log-list", ...entries.map(logRow));
}
+25
View File
@@ -130,6 +130,31 @@
white-space: pre-wrap;
}
.task-logs-section {
margin-top: var(--sp-4);
}
.task-logs-section .task-decision-title {
display: flex;
align-items: center;
justify-content: space-between;
}
.task-log-list {
max-height: 40vh;
overflow-y: auto;
font-family: var(--font-mono);
font-size: var(--text-xs);
border-top: 1px solid var(--border);
margin-top: var(--sp-2);
}
.task-log-loading,
.task-log-error {
padding: var(--sp-3) 0;
color: var(--fg-muted);
}
/* On phones the filter controls take their own row and full width instead of
crowding the card title. */
@media (max-width: 700px) {
+38
View File
@@ -5,6 +5,7 @@ import { statTile } from "../base/statTile.js";
import { taskRowA11y } from "./task-row.js";
import { initialTaskFilter, taskMatchesStatus } from "./task-filters.js";
import { describeTimelineEvent } from "./timeline-event.js";
import { taskLogPanel } from "./task-logs.js";
import { actionFor, statusIds, statusKind, statusLabel } from "../base/task-meta.js";
/**
@@ -24,6 +25,8 @@ export function tasksPage(params = new URLSearchParams()) {
let expandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null;
let focusRequestedTask = expandedId !== null;
const eventCache = new Map();
const logCache = new Map();
const logsExpanded = new Set();
// Keyed by task id. A single shared string leaked one row's failure into
// every other row's action cell.
const actionErrors = new Map();
@@ -400,10 +403,45 @@ export function tasksPage(params = new URLSearchParams()) {
: cached.length
? el("ul.task-timeline", ...cached.map(timelineEntry))
: empty("No events yet", "This task has not recorded any transitions."),
logsSection(t),
),
);
}
function logsSection(t) {
const expanded = logsExpanded.has(t.id);
const toggle = () => {
if (expanded) {
logsExpanded.delete(t.id);
} else {
logsExpanded.add(t.id);
if (!logCache.has(t.id)) loadTaskLogs(t.id);
}
renderRows();
};
return el(
"div.task-logs-section",
el(
"div.task-decision-title",
"Attempt log",
el("button.btn.btn-small", { onclick: toggle }, expanded ? "Hide" : "Show"),
),
expanded ? taskLogPanel(logCache.get(t.id), { onRetry: () => loadTaskLogs(t.id) }) : null,
);
}
async function loadTaskLogs(id) {
logCache.delete(id);
renderRows();
try {
const res = await api.taskLogs(id, { limit: 500 });
logCache.set(id, res);
} catch {
logCache.set(id, null);
}
renderRows();
}
function timelineEntry(ev) {
const description = describeTimelineEvent(ev);
return el(
+44
View File
@@ -0,0 +1,44 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import "./shim.js";
import { logRow, levelKind, fmtValue, shortTime } from "../src/base/log-row.js";
test("levelKind maps known levels to their pill kind", () => {
assert.equal(levelKind("ERROR"), "danger");
assert.equal(levelKind("warn"), "warn");
assert.equal(levelKind("Debug"), "idle");
assert.equal(levelKind("info"), "info");
assert.equal(levelKind(""), "info");
});
test("fmtValue stringifies objects, passes scalars through, and blanks nullish", () => {
assert.equal(fmtValue(null), "");
assert.equal(fmtValue(undefined), "");
assert.equal(fmtValue(5), 5);
assert.equal(fmtValue({ a: 1 }), JSON.stringify({ a: 1 }));
});
test("shortTime falls back to a placeholder for an unparsable time", () => {
assert.equal(shortTime("not a date"), "--:--:--");
});
test("logRow renders every field generically, including the ones the daemon-wide feed drops", () => {
const row = logRow({
time: "2026-01-01T00:00:00Z",
level: "info",
msg: "attempt finished",
fields: {
stage: "tdd",
prompt_tokens: 100,
completion_tokens: 40,
cached_tokens: 10,
stop_reason: "end_turn",
model: "sonnet-5",
},
});
assert.match(row.className, /log-row/);
assert.match(row.textContent, /attempt finished/);
for (const key of ["stage", "prompt_tokens", "completion_tokens", "cached_tokens", "stop_reason", "model"]) {
assert.match(row.textContent, new RegExp(key), `missing field ${key}`);
}
});
+54
View File
@@ -0,0 +1,54 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import "./shim.js";
import { taskLogPanel } from "../src/tasks/task-logs.js";
test("loading state renders a loading placeholder", () => {
const node = taskLogPanel(undefined, {});
assert.match(node.className, /task-log-loading/);
assert.match(node.textContent, /Loading/);
});
test("fetch failure renders a retry control", () => {
const node = taskLogPanel(null, { onRetry: () => {} });
assert.match(node.className, /task-log-error/);
const btn = node.querySelector("button");
assert.ok(btn, "a retry button should render");
assert.equal(btn.textContent, "Retry");
});
test("disabled response (task logging not enabled) renders a placeholder, not a crash", () => {
const node = taskLogPanel({ disabled: true, entries: [] });
assert.match(node.textContent, /No persisted log/);
});
test("empty entries render a placeholder distinct from the disabled state", () => {
const node = taskLogPanel({ disabled: false, entries: [] });
assert.match(node.textContent, /Nothing recorded/);
});
test("entries render one row per entry with fields visible, surfacing stage/token detail", () => {
const node = taskLogPanel({
entries: [
{
time: "2026-01-01T00:00:00Z",
level: "info",
msg: "stage complete",
fields: { stage: "implement", tokens: 1234, model: "sonnet" },
},
{
time: "2026-01-01T00:01:00Z",
level: "error",
msg: "agent failed",
fields: { iteration: 3 },
},
],
});
assert.equal(node.children.length, 2, "one .log-row per entry");
assert.match(node.textContent, /stage complete/);
assert.match(node.textContent, /implement/);
assert.match(node.textContent, /1234/);
assert.match(node.textContent, /sonnet/);
assert.match(node.textContent, /agent failed/);
assert.match(node.textContent, /iteration/);
});