web: chat reasoning block and tool calls for the whole lifecycle (C6)

This commit is contained in:
2026-10-19 06:14:48 +01:00
parent f48e53d5c8
commit 7df4891f14
6 changed files with 1200 additions and 17 deletions
+1 -1
View File
@@ -93,7 +93,7 @@ the pipeline list already carries — rather than a pluralised verb.
| C3 | Open / close / reopen a session | `chat_close`, `chat_reopen` | done — captured 2026-10-19: `captures/49-chat-close-confirm.png`. Selecting a row opens the conversation (see C4); an open row offers `Close chat…` and a closed row offers `Reopen`. The confirm is the Android copy verbatim: title `Close chat?`, the body naming the session title (`Closes "{title}" and marks it closed on every device. A turn that is running is stopped first. Nothing is deleted — the chat and its history are kept, and you can reopen it from the list.`), confirm `Close chat`, dismiss `Cancel`; only the confirm sends `chat_close` (and `Reopen` sends `chat_reopen`), then the list is refreshed from the server. The `Close chat…` action is offered on every open row, so its confirm is rendered from the pane's overlays **whether or not a conversation is open** — the smoke exercises the row-level path with no session selected (`ui-smoke` asserts the confirm appears and dismisses it), not only the path after opening the row. **Shown, not executed**: the live server has exactly one session — `ses_eae413f50ffeLQDExlg8cYnscN`, the operator's own — so the dialog was shown, captured and dismissed with `Cancel`; **no `chat_close` was sent** and that session was not closed or reopened by this stage |
| C4 | History with paging / "load older" | `chat_messages` | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the opened `ses_eae413f50ffeLQDExlg8cYnscN` transcript with the `Load older messages` control beside the conversation's identity while the server reports `has_more`) and `captures/48-chat-load-older-empty.png` (after pressing it: the live session's own opaque cursor returned an empty older page, so `has_more` went false and the control disappeared — the honest result of the server's cursor, distinct from 45). The request is exactly `{type:"chat_messages",chat_query:{session_id,limit:200,cursor}}`; the newest page is read with an empty cursor and an older page with the server's own opaque `next_cursor` passed back verbatim (never interpreted), and the reply is `chat_history.{messages,next_cursor,has_more}` with an older server's bare `chat_messages` falling back to `hasMore:false`. `mergeHistoryPage` prepends an older page, dedupes by id (order-preserving, the page's copy winning) and replaces `nextCursor`/`hasMore`; the prepend itself is unit-tested (`test/chat.test.mjs`) because the live server returned no older rows. Nothing auto-loads on scroll and there is no end-of-history row |
| C5 | Live transcript: user/assistant text, one reply = one turn | `chat_subscribe`, `chat_event` | todo |
| C6 | Reasoning block + tool calls with name/input for the whole lifecycle | `chat_event` | todo |
| C6 | Reasoning block + tool calls with name/input for the whole lifecycle | `chat_event` | done — the assistant turn draws, in order, its one collapsible reasoning block and its one tool-call chip (then the answer). Reasoning labels match the app: `Thinking…` / `Reasoning` for a single step and `Thinking · {N} steps` / `Reasoning · {N} steps` for several, with ` · {duration}` appended when the parts' timing gives a settled span (earliest start → latest completed), through chevrons named `Show reasoning` / `Hide reasoning`. The chip reads `1 tool called` / `{N} tools called`, announces `… expand for details`, wears the shared spinner while a call is in flight and an error tint once one failed, and opens a fixed overlay panel under the chip (flipped above / clamped into the viewport when there is no room) with the same count, a `Close tool calls` control and an internally scrolling, independently-expandable row per call: the name (else `tool`), the first of `description`/`command`/`filePath`/`file_path`/`path`/`pattern`/`query`/`url` collapsed and elided to 72 characters, the `+N -M` edit stat when present, the `formatToolDuration` value (`340ms`/`1.2s`/`2m 3s`), and `Expand {name}`/`Collapse {name}`; a failed row is marked `Failed tool call`. An expanded row shows INPUT (pretty-printed JSON, or the raw partial string), the LCS edit diff (at most 200 rendered lines with the remaining `… {N} more changed line(s) not shown`), then ERROR (the server's `error.message`, else the output) or OUTPUT (`(no output)` when settled and empty, nothing while in flight). Lifecycle words `streaming`/`running` are in flight and `completed`/`error` settled; a settled call never spins or wears the ` · long` mark. Because the panel is a fixed overlay, opening or closing it never re-flows the transcript nor moves its scroll (C14). Captured 2026-10-19 against `ses_eae413f50ffeLQDExlg8cYnscN` (one folded turn, 80 reasoning steps, 122 tool calls): `captures/51-chat-reasoning-collapsed.png`, `captures/52-chat-reasoning-expanded.png`, `captures/53-chat-tool-chip.png`, `captures/54-chat-tool-panel.png` (an opened `read` row showing INPUT + OUTPUT) and `captures/55-chat-edit-diff-sample.png`. The live history carries no failed or edit-family call, so that capture renders a labelled page-rendered sample — a `shell` row marked `Failed tool call` with INPUT + ERROR and an `edit` row with a `+2 -1` diff — through the page's own row builder; the transcript stayed put across open/close (top 43065 → 43065). **Live arrival over `chat_event` is C5**: the renderer is built from the same part shapes (`ChatPart{type,name,state{status,input,content,error},time}`) and takes a `streaming` flag plus a live elapsed source so C5 can drive in-flight calls; the chip's in-flight spinner, the ` · long` 60s mark, the panel flip-above and an edit-family call are not reachable against the live server, so they are unit-tested (`test/chat.test.mjs`) rather than claimed as captured |
| C7 | Markdown rendering + code blocks | — | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (opened at the newest content: bold, bullet lists, a `|` table with its `---` delimiter row and inline code spans from the live assistant answer), `captures/47b-chat-markdown-code.png` (a rendered fenced code block — label `js`, the pre body `const answer = 42;` — drawn in the live browser by the page's own `renderMarkdown`, the same function that renders the answer) and `captures/47-chat-reasoning-code.png`. The subset is exactly `Markdown.kt`: paragraphs, `#`–`######` headings, fenced code (```/~~~, the language label else `code`), block quotes, bullet/ordered lists, `|` tables with a `---` delimiter row, thematic rules, inline code, bold, italic (underscore only at word boundaries, so `snake_case` stays plain), `[label](url)` links and bare http(s) autolinks; HTML entities are decoded first in one pass, and HTML, reference links, strikethrough and nested lists render as plain text and are never dropped. **Code-block caveat, stated plainly**: the live assistant answer carries **no** fenced block — its four fences live in the reasoning transcript, which the app draws as plain text, not as markdown (`captures/47-chat-reasoning-code.png` shows one such fence as muted plain text; that is C6 material, not the markdown path). So the rendered `<pre>` code block is captured from a labelled sample through the page's real renderer (`47b`), and the same path plus its `code`-else-language label is unit-tested in `test/markdown.test.mjs`. Only `http(s)` link targets become clickable — the transcript is untrusted model output, so a `javascript:`/`data:` target renders as its label, never as a live link |
| C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | todo |
| C9 | Slash commands | client-side | todo |
+272 -10
View File
@@ -229,6 +229,7 @@ import {
groupSessionsByDirectory,
mergeHistoryPage,
reasoningLabel,
runningToolElapsedMillis,
sessionActivity,
sessionActivityBadge,
sessionChipLabel,
@@ -236,8 +237,16 @@ import {
sessionStatusLabel,
sessionTitle,
sessionWorkLabel,
toolCallCount,
toolCallRow,
toolCallsAnnouncement,
toolCallsLabel,
toolFailed,
toolLongRunning,
toolRunning,
toolsRunning,
transcriptRows,
turnElapsedMillis,
} from "./chat.js";
import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js";
@@ -374,6 +383,11 @@ const state = {
chatPlaced: null,
chatFollowing: true,
chatReasoning: new Set(),
// The tool-call panel (C6): the turns whose panel is open and the individual
// rows the operator has expanded, both keyed the same way as chatReasoning so
// a re-render keeps them.
chatToolPanels: new Set(),
chatToolRows: new Set(),
chatScroll: readChatScrollStore(),
// The scroll restore across a prepended older page, the position captured
// from the live transcript just before a re-render (so a dialog, a refresh or
@@ -3275,6 +3289,8 @@ async function openChatSession(id) {
state.chatPlaced = null;
state.chatFollowing = true;
state.chatReasoning = new Set();
state.chatToolPanels = new Set();
state.chatToolRows = new Set();
const existing = state.chatThreads.get(id);
state.chatThreads.set(id, {
messages: existing?.messages ?? [],
@@ -3706,15 +3722,14 @@ function renderChatUserMessage(message) {
}
/** One folded agent reply, left-aligned: reasoning, tool-call chip, answer. */
function renderChatAgentTurn(turn) {
function renderChatAgentTurn(turn, streaming = false) {
const wrap = h("div", { class: "chat-turn chat-turn-agent" });
const bubble = h("div", { class: "chat-bubble agent-bubble" });
const steps = turn.reasoningSteps;
if (steps.length > 0) bubble.append(renderChatReasoning(turn));
if (steps.length > 0) bubble.append(renderChatReasoning(turn, streaming));
if (turn.tools.length > 0) {
bubble.append(
h("div", { class: "chat-tools" }, h("span", { class: "chip chat-tool-chip", text: toolCallsLabel(turn.tools.length) })),
);
const tools = renderChatToolCalls(turn, { streaming });
if (tools) bubble.append(tools);
}
if (turn.answer.trim() !== "") bubble.append(renderMarkdown(turn.answer));
wrap.append(bubble);
@@ -3724,9 +3739,13 @@ function renderChatAgentTurn(turn) {
/**
* The turn's one collapsible reasoning block. The open/closed state lives on the
* conversation keyed by the turn, so it survives a re-render; toggling it never
* rebuilds the transcript (and so never moves the operator's scroll).
* rebuilds the transcript (and so never moves the operator's scroll). The label is
* the app's own (see `reasoningLabel`) with the turn's server-reported duration
* appended when it has one; a settled history turn reads `Reasoning` (or
* `Reasoning · N steps`), a live one `Thinking…`/`Thinking · N steps`. Live
* elapsed time is C5's; this renders the parts' own timing.
*/
function renderChatReasoning(turn) {
function renderChatReasoning(turn, streaming = false) {
const expanded = state.chatReasoning.has(turn.key);
const block = h("div", { class: "chat-reasoning" });
const toggle = h("button", {
@@ -3735,16 +3754,31 @@ function renderChatReasoning(turn) {
"aria-expanded": String(expanded),
});
toggle.append(
h("span", { class: "chat-reasoning-icon", "aria-hidden": "true", text: expanded ? "\u25be" : "\u25b8" }),
h("span", {
class: "chat-reasoning-icon",
role: "img",
"aria-label": expanded ? "Hide reasoning" : "Show reasoning",
text: expanded ? "\u25be" : "\u25b8",
}),
);
const label = reasoningLabel(turn.reasoningSteps.length, streaming);
const elapsedMillis = turnElapsedMillis(turn.parts);
const duration = elapsedMillis == null ? null : formatDuration(Math.trunc(elapsedMillis / 1000));
toggle.append(
h("span", {
class: "chat-reasoning-label",
text: duration == null ? label : `${label} · ${duration}`,
}),
);
toggle.append(h("span", { class: "chat-reasoning-label", text: reasoningLabel(turn.reasoningSteps.length) }));
const body = h("div", { class: "chat-reasoning-body", text: turn.reasoning });
body.hidden = !expanded;
toggle.addEventListener("click", () => {
const next = body.hidden;
body.hidden = !next;
toggle.setAttribute("aria-expanded", String(next));
toggle.querySelector(".chat-reasoning-icon").textContent = next ? "\u25be" : "\u25b8";
const icon = toggle.querySelector(".chat-reasoning-icon");
icon.textContent = next ? "\u25be" : "\u25b8";
icon.setAttribute("aria-label", next ? "Hide reasoning" : "Show reasoning");
if (next) state.chatReasoning.add(turn.key);
else state.chatReasoning.delete(turn.key);
});
@@ -3752,6 +3786,234 @@ function renderChatReasoning(turn) {
return block;
}
/**
* One turn's tool calls behind a single summary chip (C6), the browser's port of
* `ui/chat/ChatToolCalls.kt`: `N tools called`, a spinner while any call is in
* flight, a `· long` mark (error tint) once a running call has passed
* [TOOL_LONG_RUNNING_MILLIS], error styling once a call failed, and a chevron
* naming the panel it opens. The panel is a fixed overlay anchored below the chip
* (flipped above when there is no room), with a header count, a close control, an
* internally scrolling list, and per-row expand state; because it never joins the
* transcript's flow, opening or closing it cannot re-flow the conversation nor
* move its scroll position (C14).
*
* [streaming] is whether the turn is still live, and [elapsedMillis] the live age
* of a running call (the conversation supplies it from its own clock, so the
* `long` mark is derived from real time, never guessed). A settled history turn
* passes neither, so a stored `running` status cannot spin or wear the mark.
*/
function renderChatToolCalls(turn, { streaming = false, elapsedMillis = () => 0 } = {}) {
const parts = turn.tools;
if (parts.length === 0) return null;
const count = toolCallCount(turn.parts);
const running = streaming && toolsRunning(turn.parts);
const failed = parts.some((part) => toolFailed(part.state));
const long = running && parts.some((part) => toolRunning(part) && toolLongRunning(elapsedMillis(part)));
const turnKey = turn.key;
const wrap = h("div", { class: "chat-tools" });
const open = state.chatToolPanels.has(turnKey);
const chip = h("button", {
class: `chip chat-tool-chip${failed ? " chat-tool-chip-failed" : ""}`,
type: "button",
"aria-label": toolCallsAnnouncement(count),
"aria-expanded": String(open),
});
if (running) {
chip.append(h("span", { class: "spinner chat-tool-spinner", "aria-hidden": "true" }));
} else {
chip.append(
h("span", {
class: `chat-tool-icon${failed ? " chat-tool-icon-failed" : ""}`,
"aria-hidden": "true",
text: failed ? "\u26a0" : "\u29c9",
}),
);
}
chip.append(h("span", { class: "chat-tool-label", text: toolCallsLabel(count) }));
if (long) chip.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
const chevron = h("span", {
class: "chat-tool-chevron",
role: "img",
"aria-label": open ? "Hide tool calls" : "Show tool calls",
text: open ? "\u25b4" : "\u25be",
});
chip.append(chevron);
wrap.append(chip);
const panel = h("div", { class: "chat-tool-panel", role: "dialog", "aria-label": toolCallsLabel(count) });
panel.hidden = !open;
const head = h("div", { class: "chat-tool-panel-head" });
head.append(h("span", { class: "chat-tool-panel-count", text: toolCallsLabel(count) }));
const close = h("button", {
class: "ghost chat-tool-close",
type: "button",
"aria-label": "Close tool calls",
title: "Close tool calls",
text: "\u00d7",
});
head.append(close);
panel.append(head);
const list = h("div", { class: "chat-tool-list" });
for (const part of parts) {
const id = String(part?.id ?? "");
const holder = h("div", { class: "chat-tool-row-holder" });
const build = () =>
renderToolCallRow(part, {
expanded: state.chatToolRows.has(id),
onToggle: () => {
if (state.chatToolRows.has(id)) state.chatToolRows.delete(id);
else state.chatToolRows.add(id);
holder.replaceChild(build(), holder.firstChild);
},
});
holder.append(build());
list.append(holder);
}
panel.append(list);
wrap.append(panel);
const setOpen = (next) => {
if (next) state.chatToolPanels.add(turnKey);
else state.chatToolPanels.delete(turnKey);
panel.hidden = !next;
chip.setAttribute("aria-expanded", String(next));
chevron.setAttribute("aria-label", next ? "Hide tool calls" : "Show tool calls");
chevron.textContent = next ? "\u25b4" : "\u25be";
if (next) positionChatToolPanel(panel, chip);
};
chip.addEventListener("click", (event) => {
event.stopPropagation();
setOpen(panel.hidden);
});
close.addEventListener("click", () => setOpen(false));
if (open) {
// The panel is built before its turn is attached to the document, so its
// rect is not measurable yet; place it on the next frame, when it is.
const place = () => positionChatToolPanel(panel, chip);
if (typeof requestAnimationFrame === "function") requestAnimationFrame(place);
else setTimeout(place, 0);
}
return wrap;
}
/**
* Places the tool panel below its chip, or above it when there is no room, keeping
* it inside the viewport margins — the browser's port of
* `ToolPanelPositionProvider`. Resolved in px from the live rects, so it is
* independent of any layout guess.
*/
function positionChatToolPanel(panel, chip) {
const gap = 4;
const margin = 8;
const chipRect = chip.getBoundingClientRect();
const rect = panel.getBoundingClientRect();
let top = chipRect.bottom + gap;
if (top + rect.height > window.innerHeight - margin) top = chipRect.top - rect.height - gap;
top = Math.max(margin, Math.min(top, window.innerHeight - rect.height - margin));
const left = Math.max(margin, Math.min(chipRect.left, window.innerWidth - rect.width - margin));
panel.style.top = `${Math.round(top)}px`;
panel.style.left = `${Math.round(left)}px`;
}
/**
* One call inside the panel: a header naming the call, its `+N -M` stat for an
* edit and its duration, and — expanded in place — the pretty-printed INPUT, the
* synthesised edit diff, then the ERROR block for a failed call or the OUTPUT for
* a settled one. Rows expand and collapse independently. Exported so the smoke can
* render a representative row through this same builder.
*/
export function renderToolCallRow(part, { expanded = false, onToggle = null } = {}) {
const row = toolCallRow(part);
const node = h("div", { class: `chat-tool-row${row.error != null ? " chat-tool-row-failed" : ""}` });
const head = h("button", {
class: "chat-tool-row-head",
type: "button",
"aria-expanded": String(expanded),
});
head.append(
h("span", {
class: `chat-tool-icon${row.error != null ? " chat-tool-icon-failed" : ""}`,
role: "img",
"aria-label": row.error != null ? "Failed tool call" : "",
"aria-hidden": row.error != null ? null : "true",
text: row.error != null ? "\u26a0" : row.diff != null ? "\u270e" : "\u29c9",
}),
);
const titles = h("span", { class: "chat-tool-row-titles" });
titles.append(h("span", { class: "chat-tool-name", text: row.name }));
if (row.detail != null) titles.append(h("span", { class: "chat-tool-detail", text: row.detail }));
head.append(titles);
if (row.diff != null) {
head.append(h("span", { class: "chat-tool-stat", text: changeStat(row.diff.added, row.diff.removed) }));
}
if (row.duration != null) head.append(h("span", { class: "chat-tool-duration", text: row.duration }));
head.append(
h("span", {
class: "chat-tool-row-chevron",
role: "img",
"aria-label": expanded ? `Collapse ${row.name}` : `Expand ${row.name}`,
text: expanded ? "\u25b4" : "\u25be",
}),
);
node.append(head);
if (expanded) {
const body = h("div", { class: "chat-tool-body" });
const input = toolSection("INPUT", row.input);
if (input) body.append(input);
if (row.diff != null) body.append(renderToolDiff(row.diff));
if (row.error != null) {
const error = toolSection("ERROR", row.error);
if (error) body.append(error);
} else {
const output = toolSection("OUTPUT", row.output);
if (output) body.append(output);
}
node.append(body);
}
if (typeof onToggle === "function") {
head.addEventListener("click", () => onToggle());
}
return node;
}
/** One monospace section card (INPUT/OUTPUT/ERROR); blank content renders none. */
function toolSection(label, text) {
if (text == null || String(text).trim() === "") return null;
const section = h("div", { class: "chat-tool-section" });
section.append(h("div", { class: "chat-tool-section-label", text: label }));
section.append(h("pre", { class: "chat-tool-section-body", text }));
return section;
}
/**
* The unified diff body of an edit call: line-by-line monospace with `+`/`-`
* gutter symbols and the app's success/failure hues, the shared line language of
* the run Changes viewer. A diff longer than the rendered cap is summarised with
* an omitted note. Exported so the smoke can render a representative sample.
*/
export function renderToolDiff(diff) {
const card = h("div", { class: "chat-tool-diff" });
if (diff.omitted > 0) {
card.append(
h("div", {
class: "chat-tool-diff-note",
text: `\u2026 ${diff.omitted} more changed ${diff.omitted === 1 ? "line" : "lines"} not shown`,
}),
);
}
for (const line of diff.lines) {
card.append(
h("div", {
class: `chat-tool-diff-line ${diffLineClass(line.kind)}`,
text: `${diffLineSymbol(line.kind)} ${line.text}`,
}),
);
}
return card;
}
/**
* Render assistant markdown by building DOM nodes, never by assigning innerHTML.
* Exported so the live UI smoke can exercise the page's own renderer for the
+328 -5
View File
@@ -4,7 +4,16 @@
// ui/chat/ChatFormat.kt sessionTitle, sessionTagLabel, sessionWorkLabel,
// sessionMeta, sessionActivity, sessionStatusLabel,
// chatHeaderMeta, transcriptRows, ChatTurn,
// partRendering, closeChatConfirmation
// partRendering, closeChatConfirmation,
// reasoningLabel, turnElapsedMillis, toolRunning,
// toolFailed, toolCallCount, toolsRunning,
// toolCallsAnnouncement, toolDetail, prettyToolInput,
// toolOutputText, toolErrorText, toolDurationMillis,
// runningToolElapsedMillis, formatToolDuration,
// toolEditDiff, lineDiff, toolCallRow
// ui/chat/ChatToolCalls.kt toolCallsLabel, toolCallsAnnouncement, toolDetail,
// toolCallRow, TOOL_LONG_RUNNING_MILLIS/
// toolLongRunning (the chip and its panel)
// ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions,
// groupChatSessionsByDirectory
// ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt,
@@ -17,6 +26,12 @@
// unit-tested without a browser. The caller sets each server string with
// textContent, never innerHTML.
// The one diff-line vocabulary, shared with the run summary's Changes viewer
// (ui/chat/ChatDiffCard.kt diffLineSymbol/diffLineColor) so an edit call's
// synthesised diff and the Changes viewer can never disagree about what a line
// kind is called or coloured.
import { ChangeLineKind } from "./changes.js";
/** ChatMessage.Role values (internal/protocol/chat.go). */
export const ROLE_USER = "user";
export const ROLE_ASSISTANT = "assistant";
@@ -46,11 +61,24 @@ export const SESSION_ID_TITLE_LENGTH = 18;
/** The pixels within which the transcript still counts as at the bottom. */
export const CHAT_FOLLOW_THRESHOLD_PX = 32;
/** The reasoning block's settled label, and its multi-step form. */
/** The settled label of a single-step turn's reasoning block. */
export const REASONING_LABEL = "Reasoning";
export function reasoningLabel(count) {
return count > 1 ? `${REASONING_LABEL} · ${count} steps` : REASONING_LABEL;
/** The in-flight label of a single-step turn's reasoning block. */
export const REASONING_STREAMING_LABEL = "Thinking…";
/**
* The collapsed thinking line's label. A turn that reasoned several times reads
* as its step count — `Thinking · N steps` while in flight, `Reasoning · N steps`
* once settled — so the operator can tell before opening it how much thinking
* there is; a turn that reasoned once keeps the plain one-block wording, because
* a count of one is never shown.
*/
export function reasoningLabel(count, streaming = false) {
if (count > 1 && streaming) return `Thinking · ${count} steps`;
if (count > 1) return `${REASONING_LABEL} · ${count} steps`;
if (streaming) return REASONING_STREAMING_LABEL;
return REASONING_LABEL;
}
// ---------------------------------------------------------------------------
@@ -133,9 +161,19 @@ export function toolCallsLabel(count) {
return count === 1 ? "1 tool called" : `${count} tools called`;
}
/**
* The tool lifecycle statuses (internal/protocol/chat.go ChatToolState.Status)
* that mean a call is still in flight: `streaming` and `running`. `completed`
* and `error` are settled, and a missing status is settled too.
*/
function toolStatusRunning(status) {
const value = str(status);
return value === "streaming" || value === "running";
}
/** True while [part] is a tool call the stream still reports as running. */
export function toolRunning(part) {
return part?.type === PART_TOOL && str(part?.state?.status) === "running";
return part?.type === PART_TOOL && toolStatusRunning(part?.state?.status);
}
/** The tool calls of [parts] that are still in flight, in transcript order. */
@@ -143,6 +181,268 @@ export function runningTools(parts) {
return (parts ?? []).filter((part) => toolRunning(part));
}
/** True when a tool call ended in an error state. */
export function toolFailed(state) {
return str(state?.status) === "error";
}
/** How many tool calls [parts] holds, counted by kind rather than by length. */
export function toolCallCount(parts) {
return (parts ?? []).filter((part) => part?.type === PART_TOOL).length;
}
/** True while any tool call in [parts] is still in flight. */
export function toolsRunning(parts) {
return (parts ?? []).some((part) => toolRunning(part));
}
/**
* What the summary chip announces to a screen reader, since the individual calls
* only exist inside the panel: the count, plus how to reach the detail. Singular
* and plural follow [toolCallsLabel] so the two never disagree.
*/
export function toolCallsAnnouncement(count) {
return count === 1 ? "1 tool call, expand for details" : `${count} tool calls, expand for details`;
}
/**
* A tool call running longer than this reads as unusually long and is marked, so
* a genuinely stuck call is visible without a fabricated ETA. One minute.
*/
export const TOOL_LONG_RUNNING_MILLIS = 60000;
/** Whether a running call has been going long enough to be marked unusual. */
export function toolLongRunning(elapsedMillis) {
return elapsedMillis >= TOOL_LONG_RUNNING_MILLIS;
}
/** Wall-clock duration of a tool call, or null while it has no completion time. */
export function toolDurationMillis(part) {
const time = part?.time;
if (time == null) return null;
const start = Number(time.ran) > 0 ? Number(time.ran) : Number(time.created);
const completed = Number(time.completed);
if (!(start > 0) || !(completed > 0) || completed < start) return null;
return completed - start;
}
/**
* How long a running [part] has been going at [nowMillis]. The protocol's own
* timing wins whenever the part carries it (a running call from stored history
* has `time.ran`, the moment it started); otherwise the elapsed is measured
* locally from [startedAt] — the wall clock at which this client first saw the
* part running. Zero when neither is usable, so a caller never shows a time it
* cannot stand behind.
*/
export function runningToolElapsedMillis(part, startedAt, nowMillis) {
const time = part?.time;
const protocolStart = time == null ? 0 : Number(time.ran) > 0 ? Number(time.ran) : Number(time.created);
const start = protocolStart > 0 ? protocolStart : startedAt;
return start >= 1 && start < nowMillis ? nowMillis - start : 0;
}
/** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */
export function formatToolDuration(millis) {
const value = Number(millis) || 0;
if (value < 1000) return `${value}ms`;
if (value < 60000) return `${(value / 1000).toFixed(1)}s`;
return `${Math.floor(value / 60000)}m ${Math.floor((value % 60000) / 1000)}s`;
}
/**
* The input keys, in preference order, that carry a human-facing command or a
* short description of what a tool call is doing. OpenCode's tools put the
* substance in different places (`command` for a shell, `description` for a task,
* a path or pattern for the file/search tools), so the first one present is shown
* rather than the raw arguments.
*/
export const TOOL_DETAIL_KEYS = [
"description",
"command",
"filePath",
"file_path",
"path",
"pattern",
"query",
"url",
];
/** How much of a command/description is shown before it is elided. */
export const TOOL_DETAIL_MAX_LENGTH = 72;
/**
* A one-line command or short description for [part], taken from the input the
* part actually carries: the first of [TOOL_DETAIL_KEYS] present, collapsed to a
* single line and elided past [TOOL_DETAIL_MAX_LENGTH]. Null when the input
* carries no such key (a partial-JSON string while the call is still streaming,
* or a tool that reports none), so a caller shows the name alone rather than a
* fabricated summary.
*/
export function toolDetail(part) {
const input = part?.state?.input;
if (input == null || typeof input !== "object" || Array.isArray(input)) return null;
for (const key of TOOL_DETAIL_KEYS) {
const value = input[key];
if (typeof value !== "string") continue;
const text = value.trim().replace(/\s+/g, " ");
if (text === "") continue;
return text.length <= TOOL_DETAIL_MAX_LENGTH
? text
: text.slice(0, TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…";
}
return null;
}
/**
* The INPUT section of a tool call: pretty-printed JSON once the arguments are an
* object/array, the raw partial-JSON string while still streaming, or empty when
* there is nothing.
*/
export function prettyToolInput(input) {
if (input == null) return "";
if (typeof input === "string") return input;
if (typeof input === "object") return JSON.stringify(input, null, 2);
return String(input);
}
/**
* The OUTPUT section of a tool call: the concatenated textual content, the
* literal `(no output)` when it settled with nothing, and an empty string while
* the call is still in flight.
*/
export function toolOutputText(state) {
if (state == null) return "";
const text = (state.content ?? [])
.filter((item) => item?.type === "text" && !isBlank(item.text))
.map((item) => str(item.text))
.join("\n");
if (!isBlank(text)) return text;
if (toolStatusRunning(state.status)) return "";
return "(no output)";
}
/**
* The ERROR section of a failed tool call. The server's error message takes
* precedence over any partial output the call had already produced, falling back
* to the output text so the block is never blank when the failure carries no
* message.
*/
export function toolErrorText(state) {
const message = state?.error?.message;
return !isBlank(message) ? str(message) : toolOutputText(state);
}
/** How many diff lines are rendered before the remainder is summarised. */
export const MAX_RENDERED_DIFF_LINES = 200;
/** The larger algorithm guard that bounds the quadratic LCS table. */
export const MAX_DIFF_LINES = 400;
/**
* A minimal line diff (LCS) so only the changed lines are marked, not the whole
* block. A pathologically large edit falls back to a plain remove-then-add block
* to bound the quadratic table. Each line carries a [ChangeLineKind].
*/
export function lineDiff(oldLines, newLines) {
const old = oldLines ?? [];
const next = newLines ?? [];
if (old.length > MAX_DIFF_LINES || next.length > MAX_DIFF_LINES) {
return [
...old.map((text) => ({ kind: ChangeLineKind.Remove, text })),
...next.map((text) => ({ kind: ChangeLineKind.Add, text })),
];
}
const m = old.length;
const n = next.length;
const lcs = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
for (let i = m - 1; i >= 0; i -= 1) {
for (let j = n - 1; j >= 0; j -= 1) {
lcs[i][j] =
old[i] === next[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
}
}
const result = [];
let i = 0;
let j = 0;
while (i < m && j < n) {
if (old[i] === next[j]) {
result.push({ kind: ChangeLineKind.Context, text: old[i] });
i += 1;
j += 1;
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
result.push({ kind: ChangeLineKind.Remove, text: old[i] });
i += 1;
} else {
result.push({ kind: ChangeLineKind.Add, text: next[j] });
j += 1;
}
}
while (i < m) {
result.push({ kind: ChangeLineKind.Remove, text: old[i] });
i += 1;
}
while (j < n) {
result.push({ kind: ChangeLineKind.Add, text: next[j] });
j += 1;
}
return result;
}
/**
* Derives a unified diff for an `edit`-family tool call from its
* `oldString`/`newString` arguments. A diff longer than
* [MAX_RENDERED_DIFF_LINES] is summarised — only that many lines are kept, with
* `omitted` carrying the rest — so a very large edit cannot flood the transcript.
* Returns null for any other tool, so a non-edit call keeps only INPUT/OUTPUT.
*/
export function toolEditDiff(input) {
if (input == null || typeof input !== "object" || Array.isArray(input)) return null;
const old = stringField(input, ["oldString", "old_string"]);
const next = stringField(input, ["newString", "new_string"]);
if (old == null || next == null) return null;
if (old === "" && next === "") return null;
const lines = lineDiff(old.split("\n"), next.split("\n"));
return {
file: stringField(input, ["filePath", "file_path", "file"]) ?? "",
added: lines.filter((line) => line.kind === ChangeLineKind.Add).length,
removed: lines.filter((line) => line.kind === ChangeLineKind.Remove).length,
lines: lines.slice(0, MAX_RENDERED_DIFF_LINES),
omitted: Math.max(0, lines.length - MAX_RENDERED_DIFF_LINES),
};
}
/** The first present string value among [keys], or null. */
function stringField(object, keys) {
for (const key of keys) {
const value = object[key];
if (typeof value === "string") return value;
}
return null;
}
/**
* Everything one row of the tool panel shows for a single call, derived once so
* the row, the summary chip and their unit test agree: the call's real name (the
* name the earlier frames taught it, only falling back to `tool` when none was
* ever seen), its one-line detail, its duration, the pretty-printed INPUT, the
* OUTPUT, the ERROR text for a failed call and the synthesised edit diff.
* `error` is null for a call that did not fail, and `diff` is null for every
* non-edit call, so the row shows only the sections that have content.
*/
export function toolCallRow(part) {
const state = part?.state;
const duration = toolDurationMillis(part);
return {
name: toolLabel(part),
detail: toolDetail(part),
duration: duration == null ? null : formatToolDuration(duration),
input: prettyToolInput(state?.input),
output: toolOutputText(state),
error: toolFailed(state) ? toolErrorText(state) : null,
diff: toolEditDiff(state?.input),
};
}
/**
* The status a session row reports while a turn is in flight: it names the tool
* call it is parked on (or how many, when several run at once), so a working chat
@@ -345,6 +645,29 @@ export class ChatTurn {
}
}
/**
* The elapsed time the server's own timing gives a settled turn: from the
* earliest start to the latest completion across the parts that carry a timing
* envelope (a tool call reports both). Null when the turn carries no usable
* timing, so the collapsed line shows a duration only when there is one to show
* rather than guessing one.
*/
export function turnElapsedMillis(parts) {
const list = parts ?? [];
const starts = [];
for (const part of list) {
const time = part?.time;
if (time == null) continue;
const value = Number(time.ran) > 0 ? Number(time.ran) : Number(time.created);
if (value > 0) starts.push(value);
}
if (starts.length === 0) return null;
const ends = list.map((part) => Number(part?.time?.completed)).filter((value) => value > 0);
if (ends.length === 0) return null;
const elapsed = Math.max(...ends) - Math.min(...starts);
return elapsed > 0 ? elapsed : null;
}
/**
* The transcript's rows for [messages]: each run of consecutive assistant
* messages folds into one `{kind:"agent", key, turn}`, and each of the operator's
+130
View File
@@ -1477,6 +1477,136 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
.chat-jump { position: absolute; right: 14px; bottom: 14px; border-color: var(--accent); color: var(--accent); }
/* The tool-call chip and its panel (C6). The panel is a fixed overlay, so it
never joins the transcript's flow and opening it cannot re-flow or scroll it. */
.chat-tool-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px;
background: var(--surface-2);
font-size: 12px;
cursor: pointer;
}
.chat-tool-chip-failed { border-color: var(--bad); color: var(--bad); }
.chat-tool-icon { font-size: 12px; line-height: 1; }
.chat-tool-icon-failed { color: var(--bad); }
.chat-tool-long { color: var(--bad); }
.chat-tool-chevron { color: var(--muted); }
.chat-tool-spinner { width: 11px; height: 11px; border-width: 2px; }
.chat-tool-panel {
position: fixed;
z-index: 40;
display: flex;
flex-direction: column;
width: min(420px, calc(100vw - 16px));
max-height: 440px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
overflow: hidden;
}
.chat-tool-panel[hidden] { display: none; }
.chat-tool-panel-head {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 8px 8px 12px;
border-bottom: 1px solid var(--border);
}
.chat-tool-panel-count { flex: 1 1 auto; font-size: 13px; font-weight: 600; }
.chat-tool-close { padding: 2px 8px; font-size: 14px; line-height: 1; }
.chat-tool-list { flex: 1 1 auto; min-height: 0; overflow-y: auto; }
.chat-tool-row { border-bottom: 1px solid var(--border); }
.chat-tool-row:last-child { border-bottom: 0; }
.chat-tool-row-head {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 7px 12px;
background: transparent;
border: 0;
border-radius: 0;
text-align: left;
cursor: pointer;
}
.chat-tool-row-head:hover { background: var(--surface); }
.chat-tool-row-titles { display: flex; flex-direction: column; flex: 1 1 auto; min-width: 0; gap: 1px; }
.chat-tool-name { font-size: 12px; }
.chat-tool-detail {
font-size: 11px;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.chat-tool-stat { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; }
.chat-tool-duration { font-size: 11px; color: var(--muted); }
.chat-tool-row-chevron { color: var(--muted); font-size: 11px; }
.chat-tool-body { display: grid; gap: 8px; padding: 0 12px 10px 32px; }
.chat-tool-section { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
.chat-tool-section-label {
padding: 3px 10px;
font-size: 10px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted);
background: var(--surface);
border-bottom: 1px solid var(--border);
}
.chat-tool-section-body {
margin: 0;
padding: 8px 10px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
max-height: 220px;
overflow: auto;
}
.chat-tool-diff {
padding: 6px 10px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
max-height: 220px;
overflow: auto;
}
.chat-tool-diff-note { font-size: 11px; color: var(--muted); margin-bottom: 4px; }
.chat-tool-diff-line { white-space: pre-wrap; overflow-wrap: anywhere; }
/* A clearly-labelled overlay for the UI smoke's page-rendered tool-row samples
(a failed row and an edit diff the live history does not carry). */
.chat-tool-sample {
position: fixed;
top: 70px;
left: 24px;
right: 24px;
z-index: 60;
max-height: calc(100vh - 140px);
overflow: auto;
padding: 10px 12px;
background: var(--surface);
border: 1px solid var(--accent);
border-radius: 10px;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.chat-tool-sample-note {
margin-bottom: 8px;
padding-bottom: 6px;
border-bottom: 1px dashed var(--border);
font-size: 11px;
color: var(--accent);
}
/* The rendered markdown subset. Every node is created, never parsed from HTML. */
.markdown { display: grid; gap: 8px; min-width: 0; }
.markdown > * { margin: 0; }
+221 -1
View File
@@ -7,6 +7,9 @@ import assert from "node:assert/strict";
import {
CHAT_FOLLOW_THRESHOLD_PX,
ChatTurn,
MAX_RENDERED_DIFF_LINES,
TOOL_DETAIL_MAX_LENGTH,
TOOL_LONG_RUNNING_MILLIS,
chatBottomDistancePx,
chatFirstScroll,
chatFollowsAt,
@@ -17,10 +20,14 @@ import {
closeChatConfirmation,
directoryLabel,
filterSessions,
formatToolDuration,
groupSessionsByDirectory,
lineDiff,
mergeHistoryPage,
partRendering,
prettyToolInput,
reasoningLabel,
runningToolElapsedMillis,
sessionActivity,
sessionActivityBadge,
sessionChipLabel,
@@ -29,9 +36,23 @@ import {
sessionStatusLabel,
sessionTitle,
sessionWorkLabel,
toolCallCount,
toolCallRow,
toolCallsAnnouncement,
toolCallsLabel,
toolDetail,
toolDurationMillis,
toolEditDiff,
toolErrorText,
toolFailed,
toolLongRunning,
toolOutputText,
toolRunning,
toolsRunning,
transcriptRows,
turnElapsedMillis,
} from "../src/chat.js";
import { ChangeLineKind } from "../src/changes.js";
import { PipelinesClient, ProtocolError } from "../src/client.js";
import { PipelinesRepository } from "../src/repository.js";
@@ -97,11 +118,210 @@ test("toolCallsLabel never pluralises a count of one", () => {
assert.equal(toolCallsLabel(4), "4 tools called");
});
test("reasoningLabel keeps the one-block wording and counts multiple steps", () => {
test("reasoningLabel is Thinking/Reasoning with the step count and streaming word", () => {
assert.equal(reasoningLabel(1, false), "Reasoning");
assert.equal(reasoningLabel(1, true), "Thinking…");
assert.equal(reasoningLabel(3, false), "Reasoning · 3 steps");
assert.equal(reasoningLabel(3, true), "Thinking · 3 steps");
assert.equal(reasoningLabel(1), "Reasoning");
assert.equal(reasoningLabel(3), "Reasoning · 3 steps");
});
// --- Tool-call lifecycle, detail and the edit diff (C6) ---------------------
test("toolRunning treats streaming and running as in flight, completed/error as settled", () => {
assert.equal(toolRunning({ type: "tool", state: { status: "streaming" } }), true);
assert.equal(toolRunning({ type: "tool", state: { status: "running" } }), true);
assert.equal(toolRunning({ type: "tool", state: { status: "completed" } }), false);
assert.equal(toolRunning({ type: "tool", state: { status: "error" } }), false);
assert.equal(toolRunning({ type: "tool" }), false);
assert.equal(toolRunning({ type: "text", state: { status: "running" } }), false);
});
test("toolsRunning and toolFailed summarise the lifecycle", () => {
const call = (status) => ({ type: "tool", state: { status } });
assert.equal(toolsRunning([call("completed"), call("running")]), true);
assert.equal(toolsRunning([call("completed"), call("error")]), false);
assert.equal(toolsRunning([]), false);
assert.equal(toolFailed({ status: "error" }), true);
assert.equal(toolFailed({ status: "completed" }), false);
assert.equal(toolFailed(undefined), false);
});
test("toolCallCount counts only tool parts and toolCallsAnnouncement matches the plural", () => {
const parts = [{ type: "tool" }, { type: "text" }, { type: "reasoning" }, { type: "tool" }];
assert.equal(toolCallCount(parts), 2);
assert.equal(toolCallCount([]), 0);
assert.equal(toolCallsAnnouncement(1), "1 tool call, expand for details");
assert.equal(toolCallsAnnouncement(3), "3 tool calls, expand for details");
});
test("toolDetail takes the first present detail key, collapsed and trimmed to 72", () => {
const part = (input) => ({ type: "tool", state: { input } });
assert.equal(toolDetail(part({ command: "ls -la" })), "ls -la");
assert.equal(toolDetail(part({ description: "do a thing", command: "x" })), "do a thing");
assert.equal(toolDetail(part({ filePath: "/a/b.ts" })), "/a/b.ts");
assert.equal(toolDetail(part({ path: "p", command: "c" })), "c");
assert.equal(toolDetail(part({ command: " a b\tc\n d " })), "a b c d");
const detail = toolDetail(part({ command: "x".repeat(100) }));
assert.equal(detail.length, TOOL_DETAIL_MAX_LENGTH);
assert.ok(detail.endsWith("…"));
assert.equal(toolDetail(part({ other: "nope" })), null);
assert.equal(toolDetail(part("partial json")), null);
assert.equal(toolDetail(part({ command: 42 })), null);
assert.equal(toolDetail({ type: "tool" }), null);
});
test("formatToolDuration renders ms, one-decimal seconds and minutes", () => {
assert.equal(formatToolDuration(340), "340ms");
assert.equal(formatToolDuration(999), "999ms");
assert.equal(formatToolDuration(1000), "1.0s");
assert.equal(formatToolDuration(1200), "1.2s");
assert.equal(formatToolDuration(59600), "59.6s");
assert.equal(formatToolDuration(60000), "1m 0s");
assert.equal(formatToolDuration(123000), "2m 3s");
});
test("toolDurationMillis reads ran-else-created to completed, null when unusable", () => {
assert.equal(toolDurationMillis({ time: { created: 10, ran: 20, completed: 120 } }), 100);
assert.equal(toolDurationMillis({ time: { created: 10, ran: 0, completed: 110 } }), 100);
assert.equal(toolDurationMillis({ time: { created: 10, ran: 20 } }), null);
assert.equal(toolDurationMillis({ time: { created: 10, ran: 20, completed: 5 } }), null);
assert.equal(toolDurationMillis({}), null);
});
test("runningToolElapsedMillis prefers the protocol start and falls back to the local stamp", () => {
const part = { type: "tool", time: { created: 100, ran: 500 } };
assert.equal(runningToolElapsedMillis(part, 999, 1500), 1000);
assert.equal(runningToolElapsedMillis({ type: "tool" }, 1000, 4000), 3000);
assert.equal(runningToolElapsedMillis({ type: "tool" }, 0, 4000), 0);
assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS), true);
assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1), false);
});
test("toolOutputText joins text content, (no output) when settled-empty and '' in flight", () => {
const state = (status, content) => ({ status, content });
assert.equal(
toolOutputText(state("completed", [{ type: "text", text: "a" }, { type: "text", text: "b" }])),
"a\nb",
);
assert.equal(toolOutputText(state("completed", [{ type: "text", text: " " }])), "(no output)");
assert.equal(toolOutputText(state("running", [])), "");
assert.equal(toolOutputText(state("streaming", [])), "");
assert.equal(toolOutputText(state("error", [])), "(no output)");
assert.equal(toolOutputText(null), "");
});
test("toolErrorText prefers the server's error message over the output", () => {
assert.equal(
toolErrorText({ status: "error", error: { message: "boom" }, content: [{ type: "text", text: "partial" }] }),
"boom",
);
assert.equal(toolErrorText({ status: "error", content: [{ type: "text", text: "partial" }] }), "partial");
assert.equal(toolErrorText({ status: "error", error: { message: " " }, content: [] }), "(no output)");
});
test("prettyToolInput pretty-prints objects, keeps a partial string and blanks nothing", () => {
assert.equal(prettyToolInput(null), "");
assert.equal(prettyToolInput("{\"a\":"), "{\"a\":");
assert.equal(prettyToolInput({ a: 1 }), '{\n "a": 1\n}');
assert.equal(prettyToolInput([1, 2]), "[\n 1,\n 2\n]");
});
test("lineDiff LCS marks only changed lines and carries ChangeLineKind values", () => {
const lines = lineDiff(["one", "two", "three"], ["one", "TWO", "three"]);
assert.deepEqual(lines, [
{ kind: ChangeLineKind.Context, text: "one" },
{ kind: ChangeLineKind.Remove, text: "two" },
{ kind: ChangeLineKind.Add, text: "TWO" },
{ kind: ChangeLineKind.Context, text: "three" },
]);
});
test("toolEditDiff derives the file, true counts and the LCS line kinds", () => {
const diff = toolEditDiff({ filePath: "a.ts", oldString: "one\ntwo\nthree", newString: "one\nTWO\nthree" });
assert.equal(diff.file, "a.ts");
assert.equal(diff.added, 1);
assert.equal(diff.removed, 1);
assert.equal(diff.omitted, 0);
assert.deepEqual(diff.lines, [
{ kind: ChangeLineKind.Context, text: "one" },
{ kind: ChangeLineKind.Remove, text: "two" },
{ kind: ChangeLineKind.Add, text: "TWO" },
{ kind: ChangeLineKind.Context, text: "three" },
]);
assert.equal(toolEditDiff({ oldString: "", newString: "" }), null);
assert.equal(toolEditDiff({ oldString: "x" }), null);
assert.equal(toolEditDiff({ command: "ls" }), null);
assert.equal(toolEditDiff("nope"), null);
});
test("toolEditDiff caps rendered lines at MAX_RENDERED_DIFF_LINES and counts the rest", () => {
const oldLines = Array.from({ length: 300 }, (_, i) => `old-${i}`);
const newLines = Array.from({ length: 300 }, (_, i) => `new-${i}`);
const diff = toolEditDiff({ oldString: oldLines.join("\n"), newString: newLines.join("\n") });
assert.equal(diff.lines.length, MAX_RENDERED_DIFF_LINES);
assert.equal(diff.added, 300);
assert.equal(diff.removed, 300);
assert.equal(diff.omitted, 600 - MAX_RENDERED_DIFF_LINES);
});
test("lineDiff falls back to remove-then-add past the algorithm guard", () => {
const lines = lineDiff(Array.from({ length: 401 }, () => "a"), ["b"]);
assert.equal(lines.length, 402);
assert.equal(lines[0].kind, ChangeLineKind.Remove);
assert.equal(lines.at(-1).kind, ChangeLineKind.Add);
});
test("toolCallRow composes the name, detail, duration, input, output, error and diff", () => {
const part = {
type: "tool",
id: "t1",
name: "edit",
state: {
status: "completed",
input: { filePath: "a.ts", oldString: "one", newString: "two" },
content: [{ type: "text", text: "done" }],
},
time: { created: 10, ran: 20, completed: 120 },
};
const row = toolCallRow(part);
assert.equal(row.name, "edit");
assert.equal(row.detail, "a.ts");
assert.equal(row.duration, "100ms");
assert.equal(row.input, '{\n "filePath": "a.ts",\n "oldString": "one",\n "newString": "two"\n}');
assert.equal(row.output, "done");
assert.equal(row.error, null);
assert.equal(row.diff.file, "a.ts");
assert.equal(row.diff.added, 1);
assert.equal(row.diff.removed, 1);
});
test("toolCallRow marks a failed call with its error text and no diff", () => {
const row = toolCallRow({
type: "tool",
id: "t2",
name: "shell",
state: { status: "error", input: { command: "false" }, error: { message: "exit 1" } },
});
assert.equal(row.name, "shell");
assert.equal(row.detail, "false");
assert.equal(row.duration, null);
assert.equal(row.error, "exit 1");
assert.equal(row.diff, null);
});
test("turnElapsedMillis spans earliest start to latest completion and is null when unusable", () => {
const parts = [
{ time: { created: 1000, ran: 1200, completed: 5000 } },
{ time: { created: 800, ran: 0, completed: 4000 } },
];
assert.equal(turnElapsedMillis(parts), 4200);
assert.equal(turnElapsedMillis([{ time: { created: 1000, ran: 1200 } }]), null);
assert.equal(turnElapsedMillis([{}]), null);
assert.equal(turnElapsedMillis([{ time: { created: 1000, ran: 1000, completed: 1000 } }]), null);
});
// --- Session identity -------------------------------------------------------
test("sessionTitle falls back from the title to the first 18 characters of the id", () => {
+248
View File
@@ -2344,6 +2344,254 @@ try {
await shot("47b-chat-markdown-code.png");
await page.evaluate(`document.querySelector("#markdownCodeSample")?.remove()`);
// C6: the turn's reasoning block and its tool-call chip + panel. The live
// operator session carries one folded agent turn with real reasoning and tool
// parts, so the chip, the panel and the rows are exercised against live data.
// Labels, aria names and the C14 scroll-invariance are asserted, not assumed.
step("C6: the reasoning block and the tool-call chip + panel");
const reasoningNow = await page.evaluate(`(() => {
const block = document.querySelector("#chatTranscript .chat-reasoning");
if (!block) return null;
const icon = block.querySelector(".chat-reasoning-icon");
const body = block.querySelector(".chat-reasoning-body");
return {
label: block.querySelector(".chat-reasoning-label")?.textContent ?? "",
aria: icon?.getAttribute("aria-label") ?? "",
expanded: body ? !body.hidden : false,
};
})()`);
if (!reasoningNow) throw new Error("C6: no reasoning block rendered in the live transcript");
if (reasoningNow.aria !== "Hide reasoning") {
throw new Error(`C6: the expanded reasoning chevron should read 'Hide reasoning', got ${reasoningNow.aria}`);
}
if (!/^Reasoning( · \d+ steps)?( · \d+[a-z].*)?$/.test(reasoningNow.label)) {
throw new Error(`C6: settled reasoning label: ${reasoningNow.label}`);
}
const reasoningCollapsed = await page.evaluate(`(() => {
const block = document.querySelector("#chatTranscript .chat-reasoning");
block.querySelector(".chat-reasoning-toggle").click();
const el = document.querySelector("#chatTranscript");
const br = block.getBoundingClientRect();
el.scrollTop = Math.max(0, el.scrollTop + Math.round(br.top - el.getBoundingClientRect().top) - 60);
return {
hidden: block.querySelector(".chat-reasoning-body").hidden,
aria: block.querySelector(".chat-reasoning-icon").getAttribute("aria-label"),
expanded: block.querySelector(".chat-reasoning-toggle").getAttribute("aria-expanded"),
};
})()`);
if (!reasoningCollapsed.hidden || reasoningCollapsed.aria !== "Show reasoning" || reasoningCollapsed.expanded !== "false") {
throw new Error(`C6: collapsing the reasoning block: ${JSON.stringify(reasoningCollapsed)}`);
}
console.log(` reasoning block "${reasoningNow.label}" collapsed (chevron "Show reasoning")`);
await shot("51-chat-reasoning-collapsed.png");
const expandedReasoning = await page.evaluate(`(() => {
const block = document.querySelector("#chatTranscript .chat-reasoning");
block.querySelector(".chat-reasoning-toggle").click();
const el = document.querySelector("#chatTranscript");
const br = block.getBoundingClientRect();
el.scrollTop = Math.max(0, el.scrollTop + Math.round(br.top - el.getBoundingClientRect().top) - 60);
return {
hidden: block.querySelector(".chat-reasoning-body").hidden,
aria: block.querySelector(".chat-reasoning-icon").getAttribute("aria-label"),
length: block.querySelector(".chat-reasoning-body").textContent.length,
};
})()`);
if (expandedReasoning.hidden || expandedReasoning.aria !== "Hide reasoning" || expandedReasoning.length === 0) {
throw new Error(`C6: expanding the reasoning block: ${JSON.stringify(expandedReasoning)}`);
}
console.log(` reasoning block expanded again (${expandedReasoning.length} chars, chevron "Hide reasoning")`);
await shot("52-chat-reasoning-expanded.png");
// The chip: its count, its screen-reader announcement and its chevron. The
// count is the number of rows the panel carries, so the two can never disagree.
const chipInfo = await page.evaluate(`(() => {
const chip = document.querySelector("#chatTranscript .chat-tool-chip");
if (!chip) return null;
chip.scrollIntoView({ block: "center" });
return {
text: chip.textContent ?? "",
aria: chip.getAttribute("aria-label") ?? "",
chevron: chip.querySelector(".chat-tool-chevron")?.getAttribute("aria-label") ?? "",
rows: document.querySelectorAll(".chat-tool-panel .chat-tool-row").length,
};
})()`);
if (!chipInfo) throw new Error("C6: no tool-call chip rendered in the live transcript");
const toolCount = chipInfo.rows;
const toolLabel = toolCount === 1 ? "1 tool called" : `${toolCount} tools called`;
const toolAria =
toolCount === 1 ? "1 tool call, expand for details" : `${toolCount} tool calls, expand for details`;
if (!chipInfo.text.includes(toolLabel)) {
throw new Error(`C6: the chip should read "${toolLabel}", got ${JSON.stringify(chipInfo.text)}`);
}
if (chipInfo.aria !== toolAria) {
throw new Error(`C6: chip aria-label ${chipInfo.aria} (expected ${toolAria})`);
}
if (chipInfo.chevron !== "Show tool calls") {
throw new Error(`C6: collapsed chip chevron: ${chipInfo.chevron}`);
}
console.log(` tool chip "${toolLabel}" (aria "${chipInfo.aria}", ${toolCount} live row(s))`);
await shot("53-chat-tool-chip.png");
// Open the panel by dispatching the chip's own click (not a synthetic scroll),
// then assert the header, the close control and the C14 invariant: opening the
// panel must not move the transcript behind it.
const scrollBeforePanel = await page.evaluate(
`Math.round(document.querySelector("#chatTranscript").scrollTop)`,
);
const openedPanel = await page.evaluate(`(() => {
const chip = document.querySelector("#chatTranscript .chat-tool-chip");
chip.click();
const panel = document.querySelector(".chat-tool-panel");
return {
hidden: panel?.hidden ?? true,
head: panel?.querySelector(".chat-tool-panel-count")?.textContent ?? "",
close: panel?.querySelector(".chat-tool-close")?.getAttribute("aria-label") ?? "",
chevron: chip.querySelector(".chat-tool-chevron")?.getAttribute("aria-label") ?? "",
rows: panel?.querySelectorAll(".chat-tool-row").length ?? 0,
};
})()`);
if (openedPanel.hidden) throw new Error("C6: the tool panel did not open");
if (openedPanel.head !== toolLabel) throw new Error(`C6: panel header ${openedPanel.head}`);
if (openedPanel.close !== "Close tool calls") {
throw new Error(`C6: panel close control ${openedPanel.close}`);
}
if (openedPanel.chevron !== "Hide tool calls") {
throw new Error(`C6: open chip chevron ${openedPanel.chevron}`);
}
if (openedPanel.rows !== toolCount) {
throw new Error(`C6: the panel lists ${openedPanel.rows} rows, the chip counts ${toolCount}`);
}
const scrollAfterOpen = await page.evaluate(
`Math.round(document.querySelector("#chatTranscript").scrollTop)`,
);
if (Math.abs(scrollAfterOpen - scrollBeforePanel) > 2) {
throw new Error(`C6: opening the tool panel moved the transcript (${scrollBeforePanel} -> ${scrollAfterOpen})`);
}
console.log(
` tool panel open: header "${openedPanel.head}", close "Close tool calls", ${openedPanel.rows} row(s)`,
);
// Expand the first row in place and assert its chevron name, its INPUT and its
// OUTPUT (the live first call is a settled `read` carrying both).
const firstToolRow = await page.evaluate(`(() => {
const panel = document.querySelector(".chat-tool-panel");
const list = panel.querySelector(".chat-tool-list");
list.scrollTop = 0;
const first = () => panel.querySelector(".chat-tool-row-head");
const name = first().querySelector(".chat-tool-name")?.textContent ?? "";
const chevronBefore = first().querySelector(".chat-tool-row-chevron")?.getAttribute("aria-label") ?? "";
first().click();
const head = first();
const row = head.closest(".chat-tool-row");
return {
name,
chevronBefore,
chevronAfter: head.querySelector(".chat-tool-row-chevron")?.getAttribute("aria-label") ?? "",
sections: [...row.querySelectorAll(".chat-tool-section-label")].map((n) => n.textContent),
bodies: [...row.querySelectorAll(".chat-tool-section-body")].map((n) => n.textContent),
};
})()`);
if (firstToolRow.chevronBefore !== `Expand ${firstToolRow.name}`) {
throw new Error(`C6: collapsed row chevron ${firstToolRow.chevronBefore} for ${firstToolRow.name}`);
}
if (firstToolRow.chevronAfter !== `Collapse ${firstToolRow.name}`) {
throw new Error(`C6: expanded row chevron ${firstToolRow.chevronAfter} for ${firstToolRow.name}`);
}
if (!firstToolRow.sections.includes("INPUT") || !firstToolRow.sections.includes("OUTPUT")) {
throw new Error(`C6: first row sections ${JSON.stringify(firstToolRow.sections)}`);
}
if (firstToolRow.bodies.some((body) => body.trim() === "")) {
throw new Error(`C6: a first-row section rendered blank: ${JSON.stringify(firstToolRow.bodies)}`);
}
console.log(
` first row "${firstToolRow.name}": ${firstToolRow.sections.join(" + ")} (chevron "${firstToolRow.chevronAfter}")`,
);
await shot("54-chat-tool-panel.png");
// Closing it must put the transcript back exactly where it was.
const closedPanel = await page.evaluate(`(() => {
document.querySelector(".chat-tool-close").click();
const panel = document.querySelector(".chat-tool-panel");
const chip = document.querySelector("#chatTranscript .chat-tool-chip");
return {
hidden: panel.hidden,
chevron: chip.querySelector(".chat-tool-chevron").getAttribute("aria-label"),
top: Math.round(document.querySelector("#chatTranscript").scrollTop),
};
})()`);
if (!closedPanel.hidden || closedPanel.chevron !== "Show tool calls") {
throw new Error(`C6: closing the tool panel: ${JSON.stringify(closedPanel)}`);
}
if (Math.abs(closedPanel.top - scrollBeforePanel) > 2) {
throw new Error(`C6: opening/closing the tool panel moved the transcript (${scrollBeforePanel} -> ${closedPanel.top})`);
}
console.log(
` the tool panel left the transcript where it was across open/close (top ${scrollBeforePanel} -> ${closedPanel.top})`,
);
// The live history carries no failed call and no edit-family call, so render
// both through the page's own row builder (the 47b precedent): a failed row
// marked "Failed tool call" with an ERROR section, and an edit row with the LCS
// diff and its true "+N -M" stat. The sample is removed straight after.
const sampleRows = await page.evaluate(`(async () => {
const app = await import("/src/app.js");
const host = document.createElement("div");
host.id = "chatToolSample";
host.className = "chat-tool-sample";
const note = document.createElement("div");
note.className = "chat-tool-sample-note";
note.textContent =
"Page-rendered sample — the live history carries no failed or edit call " +
"(the chip, panel and rows above are live)";
host.append(note);
const failedPart = {
type: "tool", id: "sample-failed", name: "shell",
state: { status: "error", input: { command: "false" }, error: { message: "exit status 1" } },
};
const failedRow = app.renderToolCallRow(failedPart, { expanded: true });
host.append(failedRow);
const editPart = {
type: "tool", id: "sample-edit", name: "edit",
state: {
status: "completed",
input: { filePath: "web/src/chat.js", oldString: "const a = 1;\\nconst b = 2;", newString: "const a = 1;\\nconst b = 3;\\nconst c = 4;" },
content: [{ type: "text", text: "applied" }],
},
time: { created: 1, ran: 2, completed: 103 },
};
const editRow = app.renderToolCallRow(editPart, { expanded: true });
host.append(editRow);
document.body.append(host);
return {
failedAria: failedRow.querySelector('.chat-tool-icon[aria-label="Failed tool call"]') ? "Failed tool call" : "",
failedSections: [...failedRow.querySelectorAll(".chat-tool-section-label")].map((n) => n.textContent),
editStat: editRow.querySelector(".chat-tool-stat")?.textContent ?? "",
diffLines: [...editRow.querySelectorAll(".chat-tool-diff-line")].map((n) => ({ cls: n.className, text: n.textContent })),
};
})()`);
if (!sampleRows) throw new Error("C6: could not render the page-rendered tool-row samples");
if (sampleRows.failedAria !== "Failed tool call") {
throw new Error(`C6: the failed row is not marked 'Failed tool call': ${JSON.stringify(sampleRows)}`);
}
if (!sampleRows.failedSections.includes("INPUT") || !sampleRows.failedSections.includes("ERROR")) {
throw new Error(`C6: failed row sections ${JSON.stringify(sampleRows.failedSections)}`);
}
if (sampleRows.editStat !== "+2 -1") {
throw new Error(`C6: edit diff stat ${sampleRows.editStat}`);
}
if (
!sampleRows.diffLines.some((line) => line.cls.includes("diff-remove") && line.text === "- const b = 2;") ||
!sampleRows.diffLines.some((line) => line.cls.includes("diff-add") && line.text === "+ const b = 3;")
) {
throw new Error(`C6: the edit diff lines: ${JSON.stringify(sampleRows.diffLines)}`);
}
console.log(
` page-rendered samples: failed row "Failed tool call" (${sampleRows.failedSections.join(" + ")}), ` +
`edit row stat ${sampleRows.editStat} with ${sampleRows.diffLines.length} diff line(s)`,
);
await shot("55-chat-edit-diff-sample.png");
await page.evaluate(`document.querySelector("#chatToolSample")?.remove()`);
if (transcript.hasLoadOlder) {
// The control was present in capture 45. Press it and capture the honest
// result: the live session's own cursor returns an empty older page, so the