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
+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