web: chat reasoning block and tool calls for the whole lifecycle (C6)
This commit is contained in:
+272
-10
@@ -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
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user