Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(cli): refactor tui rendering, resume flow, and composer UX

gallonH3f81c7805647
diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.ts
index a0b4241dd2..4f686d652c 100644
--- a/jiuwenclaw/cli/src/app-state.ts
+++ b/jiuwenclaw/cli/src/app-state.ts
@@ -1,6 +1,17 @@
import type { CommandContext } from "./core/commands/types.js";
-import { isIgnorableHistoryRestoreError } from "./core/app-state-helpers.js";
+import {
+ computeTimeoutAt,
+ isIgnorableHistoryRestoreError,
+ rebuildToolExecutionStateFromEntries,
+ upsertToolGroupDisplay,
+} from "./core/app-state-helpers.js";
+import {
+ applyToolResult,
+ createToolCallDisplay,
+ parseHistoryFrame,
+} from "./core/history-parser.js";
import { generateSessionId } from "./core/session-state.js";
+import { getToolGroupIds } from "./core/transcript-timeline.js";
import {
handleIncomingFrame,
type AppEventDelegate,
@@ -13,7 +24,12 @@ import {
type ContextCompressionStats,
type HistoryItem,
type SubtaskState,
+ type TeamMemberEvent,
+ type TeamMessageEvent,
+ type TeamTaskEvent,
type TodoItem,
+ type ToolCallDisplay,
+ type ToolExecution,
} from "./core/types.js";
import {
getCurrentAccentColor,
@@ -35,6 +51,7 @@ export interface AppSnapshot {
transcriptFoldMode: "none" | "tools" | "thinking" | "all";
collapsedToolGroupIds: Set<string>;
entries: HistoryItem[];
+ toolExecutions: ToolExecution[];
streamingState: StreamingState;
pendingQuestion: PendingQuestion | null;
lastError: string | null;
@@ -42,6 +59,9 @@ export interface AppSnapshot {
isPaused: boolean;
activeSubtasks: SubtaskState[];
todos: TodoItem[];
+ teamMemberEvents: TeamMemberEvent[];
+ teamTaskEvents: TeamTaskEvent[];
+ teamMessageEvents: TeamMessageEvent[];
evolutionStatus: "idle" | "running";
contextCompression: ContextCompressionStats | null;
}
@@ -54,7 +74,7 @@ export class CliPiAppState {
private mode: "plan" | "agent" | "team" = "plan";
private themeName: ThemeName = getCurrentThemeName();
private accentColor: AccentColorName = getCurrentAccentColor();
- private transcriptMode: "compact" | "detailed" = "detailed";
+ private transcriptMode: "compact" | "detailed" = "compact";
private transcriptFoldMode: "none" | "tools" | "thinking" | "all" = "none";
private collapsedToolGroupIds = new Set<string>();
private streamingState: StreamingState = StreamingState.Idle;
@@ -62,10 +82,20 @@ export class CliPiAppState {
private lastError: string | null = null;
private activeSubtasks = new Map<string, SubtaskState>();
private todos: TodoItem[] = [];
+ private teamMemberEvents: TeamMemberEvent[] = [];
+ private teamTaskEvents: TeamTaskEvent[] = [];
+ private teamMessageEvents: TeamMessageEvent[] = [];
private evolutionStatus: "idle" | "running" = "idle";
private contextCompression: ContextCompressionStats | null = null;
+ private toolExecutions = new Map<string, ToolExecution>();
+ private toolExecutionOrder: string[] = [];
+ private orphanToolResults = new Map<
+ string,
+ { tool: ToolCallDisplay; requestId?: string; updatedAt: string }
+ >();
private historyEntries: HistoryItem[] = [];
private historyFlushTimer: ReturnType<typeof setTimeout> | null = null;
+ private toolTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
private historyRequestToken = 0;
private unlistenStatus: (() => void) | null = null;
private unlistenFrames: (() => void) | null = null;
@@ -95,12 +125,33 @@ export class CliPiAppState {
setTodos: (todos) => {
this.todos = todos;
},
+ appendTeamMemberEvent: (event) => {
+ this.teamMemberEvents = [...this.teamMemberEvents.slice(-99), event];
+ },
+ appendTeamTaskEvent: (event) => {
+ this.teamTaskEvents = [...this.teamTaskEvents.slice(-99), event];
+ },
+ appendTeamMessageEvent: (event) => {
+ this.teamMessageEvents = [...this.teamMessageEvents.slice(-99), event];
+ },
setEvolutionStatus: (status) => {
this.evolutionStatus = status;
},
setContextCompression: (stats) => {
this.contextCompression = stats;
},
+ addToolCallPayload: (payload, sessionId, requestId, startedAt) => {
+ this.addToolCallPayload(payload, sessionId, requestId, startedAt);
+ },
+ addToolResultPayload: (payload, sessionId, requestId, updatedAt) => {
+ this.addToolResultPayload(payload, sessionId, requestId, updatedAt);
+ },
+ addSyntheticToolExecution: (tool, sessionId, requestId, at) => {
+ this.addSyntheticToolExecution(tool, sessionId, requestId, at);
+ },
+ clearToolExecutionState: () => {
+ this.clearToolExecutionState();
+ },
pushHistoryEntry: (entry) => {
this.historyEntries.push(entry);
},
@@ -137,6 +188,10 @@ export class CliPiAppState {
clearTimeout(this.historyFlushTimer);
this.historyFlushTimer = null;
}
+ if (this.toolTimeoutTimer) {
+ clearTimeout(this.toolTimeoutTimer);
+ this.toolTimeoutTimer = null;
+ }
this.unlistenStatus?.();
this.unlistenStatus = null;
this.unlistenFrames?.();
@@ -165,6 +220,9 @@ export class CliPiAppState {
transcriptFoldMode: this.transcriptFoldMode,
collapsedToolGroupIds: new Set(this.collapsedToolGroupIds),
entries: [...this.entries],
+ toolExecutions: this.toolExecutionOrder
+ .map((toolCallId) => this.toolExecutions.get(toolCallId))
+ .filter((item): item is ToolExecution => Boolean(item)),
streamingState: this.streamingState,
pendingQuestion: this.pendingQuestion
? {
@@ -180,6 +238,9 @@ export class CliPiAppState {
isPaused: this.streamingState === StreamingState.Paused,
activeSubtasks: [...this.activeSubtasks.values()].sort((a, b) => a.index - b.index),
todos: [...this.todos],
+ teamMemberEvents: [...this.teamMemberEvents],
+ teamTaskEvents: [...this.teamTaskEvents],
+ teamMessageEvents: [...this.teamMessageEvents],
evolutionStatus: this.evolutionStatus,
contextCompression: this.contextCompression ? { ...this.contextCompression } : null,
};
@@ -187,6 +248,7 @@ export class CliPiAppState {
getCommandContext(): CommandContext {
const snapshot = this.getSnapshot();
+ const toolGroupIds = getToolGroupIds(snapshot.entries, snapshot.toolExecutions);
return {
sendEventOnly: this.sendEventOnly,
request: this.request,
@@ -212,7 +274,8 @@ export class CliPiAppState {
setTranscriptMode: this.setTranscriptMode,
transcriptFoldMode: snapshot.transcriptFoldMode,
setTranscriptFoldMode: this.setTranscriptFoldMode,
- collapsedToolGroupCount: snapshot.collapsedToolGroupIds.size,
+ collapsedToolGroupCount: toolGroupIds.filter((id) => snapshot.collapsedToolGroupIds.has(id))
+ .length,
collapseToolGroups: this.collapseToolGroups,
expandToolGroups: this.expandToolGroups,
};
@@ -260,8 +323,12 @@ export class CliPiAppState {
this.collapsedToolGroupIds.clear();
this.activeSubtasks.clear();
this.todos = [];
+ this.teamMemberEvents = [];
+ this.teamTaskEvents = [];
+ this.teamMessageEvents = [];
this.evolutionStatus = "idle";
this.contextCompression = null;
+ this.clearToolExecutionState();
this.historyEntries = [];
this.emitChange();
};
@@ -304,12 +371,12 @@ export class CliPiAppState {
};
readonly collapseToolGroups = (scope: "last" | "all"): void => {
- const ids = this.entries
- .filter(
- (entry): entry is Extract<HistoryItem, { kind: "tool_group" }> =>
- entry.kind === "tool_group",
- )
- .map((entry) => entry.id);
+ const ids = getToolGroupIds(
+ this.entries,
+ this.toolExecutionOrder
+ .map((toolCallId) => this.toolExecutions.get(toolCallId))
+ .filter((item): item is ToolExecution => Boolean(item)),
+ );
if (scope === "all") {
this.collapsedToolGroupIds = new Set(ids);
} else {
@@ -326,12 +393,12 @@ export class CliPiAppState {
if (scope === "all") {
this.collapsedToolGroupIds.clear();
} else {
- const ids = this.entries
- .filter(
- (entry): entry is Extract<HistoryItem, { kind: "tool_group" }> =>
- entry.kind === "tool_group",
- )
- .map((entry) => entry.id);
+ const ids = getToolGroupIds(
+ this.entries,
+ this.toolExecutionOrder
+ .map((toolCallId) => this.toolExecutions.get(toolCallId))
+ .filter((item): item is ToolExecution => Boolean(item)),
+ );
const last = ids[ids.length - 1];
if (last) {
this.collapsedToolGroupIds = new Set(this.collapsedToolGroupIds);
@@ -341,7 +408,10 @@ export class CliPiAppState {
this.emitChange();
};
- sendMessage(content: string, modeOverride?: "plan" | "agent" | "team"): string | null {
+ readonly sendMessage = (
+ content: string,
+ modeOverride?: "plan" | "agent" | "team",
+ ): string | null => {
if (this.connectionStatus !== "connected") return null;
const mode = modeOverride ?? this.mode;
const requestId = this.sendEventOnly("chat.send", { content, query: content, mode });
@@ -355,13 +425,28 @@ export class CliPiAppState {
content,
at: new Date().toISOString(),
},
+ ];
+ this.streamingState = StreamingState.Responding;
+ this.emitChange();
+ return requestId;
+ };
+
+ supplement(content: string): string | null {
+ if (this.connectionStatus !== "connected") return null;
+ const trimmed = content.trim();
+ if (!trimmed) return null;
+ const requestId = this.sendEventOnly("chat.interrupt", {
+ intent: "supplement",
+ new_input: trimmed,
+ });
+ this.lastError = null;
+ this.entries = [
+ ...this.entries,
{
- kind: "assistant",
- id: `assistant-${requestId}`,
+ kind: "user",
+ id: `user-${requestId}`,
sessionId: this.sessionId,
- content: "",
- streaming: true,
- requestId,
+ content: trimmed,
at: new Date().toISOString(),
},
];
@@ -401,20 +486,259 @@ export class CliPiAppState {
this.submitQuestionAnswers([{ selected_options: [answer], custom_input: answer }]);
}
- async restoreHistory(targetSessionId: string): Promise<void> {
+ readonly restoreHistory = async (targetSessionId: string): Promise<void> => {
this.historyRequestToken += 1;
const requestToken = this.historyRequestToken;
this.historyEntries = [];
+ this.clearToolExecutionState();
if (this.historyFlushTimer) {
clearTimeout(this.historyFlushTimer);
this.historyFlushTimer = null;
}
- await this.request("history.get", { session_id: targetSessionId });
+ const payload = await this.request<{
+ messages?: unknown[];
+ total_pages?: number;
+ page_idx?: number;
+ }>("history.get", { session_id: targetSessionId, page_idx: 1 });
+ if (Array.isArray(payload.messages)) {
+ for (const message of payload.messages) {
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
+ continue;
+ }
+ const entry = parseHistoryFrame({
+ type: "event",
+ event: "history.message",
+ payload: {
+ session_id: targetSessionId,
+ message: message as Record<string, unknown>,
+ total_pages: payload.total_pages,
+ page_idx: payload.page_idx,
+ },
+ });
+ if (entry) {
+ this.historyEntries.push(entry);
+ }
+ }
+ }
setTimeout(() => {
if (requestToken !== this.historyRequestToken) return;
this.entries = [...this.historyEntries];
+ this.rebuildToolExecutionState();
this.emitChange();
}, 80);
+ };
+
+ private readonly clearToolExecutionState = (): void => {
+ if (this.toolTimeoutTimer) {
+ clearTimeout(this.toolTimeoutTimer);
+ this.toolTimeoutTimer = null;
+ }
+ this.toolExecutions = new Map();
+ this.toolExecutionOrder = [];
+ this.orphanToolResults = new Map();
+ };
+
+ private scheduleToolTimeoutCheck(): void {
+ if (this.toolTimeoutTimer) {
+ clearTimeout(this.toolTimeoutTimer);
+ this.toolTimeoutTimer = null;
+ }
+ let nextTimeoutMs = Number.POSITIVE_INFINITY;
+ const now = Date.now();
+ for (const execution of this.toolExecutions.values()) {
+ if (execution.tool.status !== "running") {
+ continue;
+ }
+ const timeoutMs = Date.parse(execution.timeoutAt);
+ if (Number.isNaN(timeoutMs)) {
+ continue;
+ }
+ nextTimeoutMs = Math.min(nextTimeoutMs, timeoutMs);
+ }
+ if (!Number.isFinite(nextTimeoutMs)) {
+ return;
+ }
+ const delay = Math.max(0, nextTimeoutMs - now);
+ this.toolTimeoutTimer = setTimeout(() => {
+ this.toolTimeoutTimer = null;
+ if (this.markTimedOutExecutions()) {
+ this.emitChange();
+ } else {
+ this.scheduleToolTimeoutCheck();
+ }
+ }, delay + 10);
+ }
+
+ private markTimedOutExecutions(): boolean {
+ const nowIso = new Date().toISOString();
+ const nowMs = Date.parse(nowIso);
+ let changed = false;
+ for (const [toolCallId, execution] of this.toolExecutions) {
+ if (execution.tool.status !== "running") {
+ continue;
+ }
+ const timeoutMs = Date.parse(execution.timeoutAt);
+ if (Number.isNaN(timeoutMs) || timeoutMs > nowMs) {
+ continue;
+ }
+ const nextTool: ToolCallDisplay = {
+ ...execution.tool,
+ status: "timeout",
+ isError: false,
+ };
+ this.toolExecutions.set(toolCallId, {
+ ...execution,
+ tool: nextTool,
+ updatedAt: nowIso,
+ timedOutAt: nowIso,
+ });
+ this.entries = upsertToolGroupDisplay(
+ this.entries,
+ execution.sessionId,
+ execution.requestId,
+ nextTool,
+ );
+ changed = true;
+ }
+ this.scheduleToolTimeoutCheck();
+ return changed;
+ }
+
+ private addToolCallPayload(
+ payload: Record<string, unknown>,
+ sessionId: string,
+ requestId?: string,
+ startedAt?: string,
+ ): void {
+ const tool = createToolCallDisplay(payload);
+ if (!tool.callId) {
+ return;
+ }
+
+ if (this.toolExecutions.has(tool.callId)) {
+ return;
+ }
+
+ const started = startedAt ?? new Date().toISOString();
+ const orphan = this.orphanToolResults.get(tool.callId);
+ const nextTool = orphan
+ ? {
+ ...tool,
+ status: orphan.tool.status,
+ result: orphan.tool.result,
+ summary: orphan.tool.summary,
+ isError: orphan.tool.isError,
+ }
+ : tool;
+
+ this.toolExecutions.set(tool.callId, {
+ toolCallId: tool.callId,
+ sessionId,
+ requestId: requestId ?? orphan?.requestId,
+ tool: nextTool,
+ startedAt: started,
+ updatedAt: orphan?.updatedAt ?? started,
+ timeoutAt: computeTimeoutAt(started),
+ resultArrivedAfterTimeout: false,
+ });
+ this.toolExecutionOrder.push(tool.callId);
+ if (orphan) {
+ this.orphanToolResults.delete(tool.callId);
+ }
+ this.entries = upsertToolGroupDisplay(
+ this.entries,
+ sessionId,
+ requestId ?? orphan?.requestId,
+ nextTool,
+ );
+ this.scheduleToolTimeoutCheck();
+ }
+
+ private addToolResultPayload(
+ payload: Record<string, unknown>,
+ sessionId: string,
+ requestId?: string,
+ updatedAt?: string,
+ ): void {
+ const baseTool = createToolCallDisplay(payload);
+ const resultTool = applyToolResult(baseTool, payload);
+ if (!resultTool.callId) {
+ return;
+ }
+
+ const nowIso = updatedAt ?? new Date().toISOString();
+ const existing = this.toolExecutions.get(resultTool.callId);
+ if (!existing) {
+ this.orphanToolResults.set(resultTool.callId, {
+ tool: resultTool,
+ requestId,
+ updatedAt: nowIso,
+ });
+ this.entries = upsertToolGroupDisplay(this.entries, sessionId, requestId, resultTool);
+ return;
+ }
+
+ const wasTimedOut = existing.tool.status === "timeout";
+ const nextTool: ToolCallDisplay = {
+ ...existing.tool,
+ ...resultTool,
+ arguments: existing.tool.arguments,
+ description: existing.tool.description ?? resultTool.description,
+ formattedArgs: existing.tool.formattedArgs ?? resultTool.formattedArgs,
+ status: wasTimedOut && !resultTool.isError ? "timeout" : resultTool.status,
+ summary: wasTimedOut
+ ? resultTool.summary
+ ? `${resultTool.summary} (after timeout)`
+ : resultTool.isError
+ ? "failed after timeout"
+ : "completed after timeout"
+ : resultTool.summary,
+ };
+ this.toolExecutions.set(resultTool.callId, {
+ ...existing,
+ requestId: existing.requestId ?? requestId,
+ tool: nextTool,
+ updatedAt: nowIso,
+ resultArrivedAfterTimeout: wasTimedOut || existing.resultArrivedAfterTimeout,
+ });
+ this.entries = upsertToolGroupDisplay(
+ this.entries,
+ sessionId,
+ existing.requestId ?? requestId,
+ nextTool,
+ );
+ this.scheduleToolTimeoutCheck();
+ }
+
+ private addSyntheticToolExecution(
+ tool: ToolCallDisplay,
+ sessionId: string,
+ requestId?: string,
+ at?: string,
+ ): void {
+ const timestamp = at ?? new Date().toISOString();
+ this.toolExecutions.set(tool.callId, {
+ toolCallId: tool.callId,
+ sessionId,
+ requestId,
+ tool,
+ startedAt: timestamp,
+ updatedAt: timestamp,
+ timeoutAt: computeTimeoutAt(timestamp),
+ });
+ if (!this.toolExecutionOrder.includes(tool.callId)) {
+ this.toolExecutionOrder.push(tool.callId);
+ }
+ this.entries = upsertToolGroupDisplay(this.entries, sessionId, requestId, tool);
+ this.scheduleToolTimeoutCheck();
+ }
+
+ private rebuildToolExecutionState(): void {
+ const rebuilt = rebuildToolExecutionStateFromEntries(this.entries);
+ this.toolExecutions = rebuilt.toolExecutions;
+ this.toolExecutionOrder = rebuilt.toolExecutionOrder;
+ this.orphanToolResults = new Map();
+ this.scheduleToolTimeoutCheck();
}
private emitChange(): void {
@@ -438,6 +762,7 @@ export class CliPiAppState {
this.historyFlushTimer = setTimeout(() => {
this.historyFlushTimer = null;
this.entries = [...this.historyEntries];
+ this.rebuildToolExecutionState();
this.emitChange();
}, 50);
}
diff --git a/jiuwenclaw/cli/src/core/app-state-helpers.ts b/jiuwenclaw/cli/src/core/app-state-helpers.ts
index e509bd9011..34d7786440 100644
--- a/jiuwenclaw/cli/src/core/app-state-helpers.ts
+++ b/jiuwenclaw/cli/src/core/app-state-helpers.ts
@@ -1,5 +1,5 @@
import { applyToolResult, createToolCallDisplay } from "./history-parser.js";
-import type { HistoryItem } from "./types.js";
+import type { HistoryItem, ToolCallDisplay, ToolExecution } from "./types.js";
export function createId(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
@@ -21,6 +21,54 @@ export function isIgnorableHistoryRestoreError(error: unknown): boolean {
return message.includes("invalid page_idx or session history not found");
}
+const TOOL_TIMEOUT_MS = 12_000_000;
+
+export function computeTimeoutAt(baseIso: string): string {
+ return new Date(Date.parse(baseIso) + TOOL_TIMEOUT_MS).toISOString();
+}
+
+export function upsertToolGroupDisplay(
+ entries: HistoryItem[],
+ sessionId: string,
+ requestId: string | undefined,
+ tool: ToolCallDisplay,
+): HistoryItem[] {
+ const groupIndex = findLastIndex(
+ entries,
+ (item) =>
+ item.kind === "tool_group" &&
+ item.sessionId === sessionId &&
+ (item.tools.some((existingTool) => existingTool.callId === tool.callId) ||
+ (Boolean(requestId) && item.requestId === requestId)),
+ );
+
+ if (groupIndex === -1) {
+ return [
+ ...entries,
+ {
+ kind: "tool_group",
+ id: createId("tool-group"),
+ sessionId,
+ requestId,
+ tools: [tool],
+ at: new Date().toISOString(),
+ },
+ ];
+ }
+
+ return entries.map((item, index) => {
+ if (index !== groupIndex || item.kind !== "tool_group") return item;
+ const nextTools = [...item.tools];
+ const toolIndex = nextTools.findIndex((existingTool) => existingTool.callId === tool.callId);
+ if (toolIndex === -1) {
+ nextTools.push(tool);
+ } else {
+ nextTools[toolIndex] = tool;
+ }
+ return { ...item, tools: nextTools };
+ });
+}
+
export function upsertToolGroup(
entries: HistoryItem[],
sessionId: string,
@@ -81,3 +129,34 @@ export function upsertToolGroup(
return { ...item, tools: nextTools };
});
}
+
+export function rebuildToolExecutionStateFromEntries(entries: HistoryItem[]): {
+ toolExecutions: Map<string, ToolExecution>;
+ toolExecutionOrder: string[];
+} {
+ const toolExecutions = new Map<string, ToolExecution>();
+ const toolExecutionOrder: string[] = [];
+
+ for (const entry of entries) {
+ if (entry.kind !== "tool_group") {
+ continue;
+ }
+ for (const tool of entry.tools) {
+ if (!tool.callId || toolExecutions.has(tool.callId)) {
+ continue;
+ }
+ toolExecutions.set(tool.callId, {
+ toolCallId: tool.callId,
+ sessionId: entry.sessionId,
+ requestId: entry.requestId,
+ tool,
+ startedAt: entry.at,
+ updatedAt: entry.at,
+ timeoutAt: computeTimeoutAt(entry.at),
+ });
+ toolExecutionOrder.push(tool.callId);
+ }
+ }
+
+ return { toolExecutions, toolExecutionOrder };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/new.ts b/jiuwenclaw/cli/src/core/commands/builtins/new.ts
index 445a3477fc..068a057014 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/new.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/new.ts
@@ -12,7 +12,7 @@ export function createNewCommand(): SlashCommand {
takesArgs: true,
action: async (ctx, args) => {
if (ctx.isProcessing) {
- ctx.addItem(makeItem(ctx.sessionId, "error", "session is busy, run /cancel first"));
+ ctx.addItem(makeItem(ctx.sessionId, "error", "session is busy"));
return;
}
const nextId = args.trim() || generateSessionId();
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
index 4f98bb977d..1b277be79d 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
@@ -1,7 +1,7 @@
import { addError, addInfo } from "../helpers.js";
import { CommandKind, type SlashCommand } from "../types.js";
-interface SessionMeta {
+export interface SessionMeta {
session_id: string;
title?: string;
channel_id?: string;
@@ -10,14 +10,14 @@ interface SessionMeta {
message_count?: number;
}
-interface SessionListPayload {
+export interface SessionListPayload {
sessions?: SessionMeta[];
total?: number;
limit?: number;
offset?: number;
}
-interface ResumeResumePayload {
+export interface ResumeResumePayload {
session_id?: string;
query?: string;
resumed?: boolean;
@@ -28,15 +28,15 @@ export function createResumeCommand(): SlashCommand {
return {
name: "resume",
altNames: ["continue"],
- description: "Resume a previous conversation, or list sessions with /resume list",
+ description: "Resume a previous conversation, or list sessions with /resume",
usage: "/resume [list | conversation id or search term]",
- example: "/resume list",
+ example: "/resume",
kind: CommandKind.BUILT_IN,
takesArgs: true,
action: async (ctx, args) => {
const value = args.trim();
try {
- if (value === "list") {
+ if (value === "" || value === "list") {
const payload = await ctx.request<SessionListPayload>("session.list", {});
const sessions = payload.sessions ?? [];
const total = payload.total ?? sessions.length;
diff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.ts
index 06baae4067..9a499fc225 100644
--- a/jiuwenclaw/cli/src/core/commands/registry.ts
+++ b/jiuwenclaw/cli/src/core/commands/registry.ts
@@ -1,7 +1,5 @@
import type { SlashCommand } from "./types.js";
import { createAddDirCommand } from "./builtins/add-dir.js";
-import { createCancelCommand } from "./builtins/cancel.js";
-import { createChromeCommand } from "./builtins/chrome.js";
import { createClearCommand } from "./builtins/clear.js";
import { createColorCommand } from "./builtins/color.js";
import { createCompactCommand } from "./builtins/compact.js";
@@ -23,8 +21,6 @@ export function createBuiltinCommands(): SlashCommand[] {
const commands: SlashCommand[] = [
createHelpCommand(() => commands),
createAddDirCommand(),
- createCancelCommand(),
- createChromeCommand(),
createClearCommand(),
createColorCommand(),
createCompactCommand(),
diff --git a/jiuwenclaw/cli/src/core/event-handlers.ts b/jiuwenclaw/cli/src/core/event-handlers.ts
index e4dccfe321..a4c6a97c4a 100644
--- a/jiuwenclaw/cli/src/core/event-handlers.ts
+++ b/jiuwenclaw/cli/src/core/event-handlers.ts
@@ -1,4 +1,10 @@
-import { parseHistoryFrame, createSessionResultToolDisplay } from "./history-parser.js";
+import {
+ parseHistoryFrame,
+ createAttachmentInfoEntry,
+ createSessionResultToolDisplay,
+ extractMediaItems,
+} from "./history-parser.js";
+import { normalizeFinalContent } from "./final-content.js";
import type { EventFrame } from "./protocol.js";
import {
StreamingState,
@@ -6,15 +12,14 @@ import {
type HistoryItem,
type JsonObject,
type SubtaskState,
+ type TeamMemberEvent,
+ type TeamMessageEvent,
+ type TeamTaskEvent,
type TodoItem,
+ type ToolCallDisplay,
} from "./types.js";
import type { ConnectionStatus } from "./ws-client.js";
-import {
- createId,
- findLastIndex,
- isIgnorableHistoryRestoreError,
- upsertToolGroup,
-} from "./app-state-helpers.js";
+import { createId, findLastIndex, isIgnorableHistoryRestoreError } from "./app-state-helpers.js";
export interface PendingQuestion {
requestId: string;
@@ -51,8 +56,30 @@ export interface AppEventDelegate {
setLastError(error: string | null): void;
getActiveSubtasks(): Map<string, SubtaskState>;
setTodos(todos: TodoItem[]): void;
+ appendTeamMemberEvent(event: TeamMemberEvent): void;
+ appendTeamTaskEvent(event: TeamTaskEvent): void;
+ appendTeamMessageEvent(event: TeamMessageEvent): void;
setEvolutionStatus(status: "idle" | "running"): void;
setContextCompression(stats: ContextCompressionStats | null): void;
+ addToolCallPayload(
+ payload: Record<string, unknown>,
+ sessionId: string,
+ requestId?: string,
+ startedAt?: string,
+ ): void;
+ addToolResultPayload(
+ payload: Record<string, unknown>,
+ sessionId: string,
+ requestId?: string,
+ updatedAt?: string,
+ ): void;
+ addSyntheticToolExecution(
+ tool: ToolCallDisplay,
+ sessionId: string,
+ requestId?: string,
+ at?: string,
+ ): void;
+ clearToolExecutionState(): void;
pushHistoryEntry(entry: HistoryItem): void;
scheduleHistoryFlush(): void;
safeRestoreHistory(sessionId: string): void;
@@ -62,23 +89,48 @@ function appendEntry(delegate: AppEventDelegate, entry: HistoryItem): void {
delegate.setEntries([...delegate.getEntries(), entry]);
}
-function addSessionResultEntry(
+function appendThinkingChunk(
delegate: AppEventDelegate,
- payload: Record<string, unknown>,
activeSessionId: string,
- effectiveEvent: string,
+ content: string,
): void {
- const tool = createSessionResultToolDisplay(payload, effectiveEvent);
+ const entries = delegate.getEntries();
+ const lastEntry = entries[entries.length - 1];
+ if (lastEntry && lastEntry.kind === "thinking" && lastEntry.sessionId === activeSessionId) {
+ delegate.setEntries([
+ ...entries.slice(0, -1),
+ {
+ ...lastEntry,
+ content: `${lastEntry.content}${content}`,
+ },
+ ]);
+ return;
+ }
+
appendEntry(delegate, {
- kind: "tool_group",
- id: createId("session-result"),
+ kind: "thinking",
+ id: createId("reasoning"),
sessionId: activeSessionId,
- requestId: typeof payload.request_id === "string" ? payload.request_id : undefined,
- tools: [tool],
+ content,
at: new Date().toISOString(),
});
}
+function addSessionResultEntry(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+ effectiveEvent: string,
+): void {
+ const tool = createSessionResultToolDisplay(payload, effectiveEvent);
+ delegate.addSyntheticToolExecution(
+ tool,
+ activeSessionId,
+ typeof payload.request_id === "string" ? payload.request_id : undefined,
+ new Date().toISOString(),
+ );
+}
+
function handleConnectionAck(delegate: AppEventDelegate, frame: EventFrame): boolean {
if (frame.event !== "connection.ack") {
return false;
@@ -148,13 +200,7 @@ function handleDelta(
const entries = delegate.getEntries();
if (payload.source_chunk_type === "llm_reasoning") {
- appendEntry(delegate, {
- kind: "thinking",
- id: createId("reasoning"),
- sessionId: activeSessionId,
- content,
- at: new Date().toISOString(),
- });
+ appendThinkingChunk(delegate, activeSessionId, content);
return true;
}
@@ -194,7 +240,8 @@ function handleFinal(
payload: Record<string, unknown>,
activeSessionId: string,
): boolean {
- const content = typeof payload.content === "string" ? payload.content : "";
+ const content = normalizeFinalContent(payload);
+ const finalizedAt = new Date().toISOString();
const entries = delegate.getEntries();
const streamingIndex = findLastIndex(
entries,
@@ -219,6 +266,7 @@ function handleFinal(
: entries[streamingIndex]?.kind === "assistant"
? entries[streamingIndex].requestId
: undefined,
+ at: finalizedAt,
streaming: false,
},
]
@@ -231,7 +279,7 @@ function handleFinal(
content,
requestId: typeof payload.request_id === "string" ? payload.request_id : undefined,
streaming: false,
- at: new Date().toISOString(),
+ at: finalizedAt,
},
],
);
@@ -246,13 +294,7 @@ function handleReasoning(
): boolean {
const content = typeof payload.content === "string" ? payload.content : "";
if (!content) return false;
- appendEntry(delegate, {
- kind: "thinking",
- id: createId("reasoning"),
- sessionId: activeSessionId,
- content,
- at: new Date().toISOString(),
- });
+ appendThinkingChunk(delegate, activeSessionId, content);
return true;
}
@@ -288,24 +330,57 @@ function handleMediaEvent(
activeSessionId: string,
effectiveEvent: "chat.media" | "chat.file",
): boolean {
- const name =
- typeof payload.file_name === "string"
- ? payload.file_name
- : typeof payload.name === "string"
- ? payload.name
- : "";
- const content = name ? `[${effectiveEvent}: ${name}]` : `[${effectiveEvent}]`;
+ const at = new Date().toISOString();
+ const content = typeof payload.content === "string" ? payload.content.trim() : "";
+ const mediaItems = extractMediaItems(payload);
+ if (effectiveEvent === "chat.media" && (content || mediaItems.length > 0)) {
+ const entries = delegate.getEntries();
+ const assistantIndex = findLastIndex(
+ entries,
+ (entry) => entry.kind === "assistant" && (entry.streaming === true || !entry.streaming),
+ );
+ if (assistantIndex !== -1) {
+ delegate.setEntries(
+ entries.map((entry, index) =>
+ index === assistantIndex && entry.kind === "assistant"
+ ? {
+ ...entry,
+ ...(content ? { content } : {}),
+ ...(mediaItems.length > 0 ? { mediaItems } : {}),
+ streaming: false,
+ }
+ : entry,
+ ),
+ );
+ } else {
+ appendEntry(delegate, {
+ kind: "assistant",
+ id: createId("assistant-media"),
+ sessionId: activeSessionId,
+ content,
+ ...(mediaItems.length > 0 ? { mediaItems } : {}),
+ at,
+ streaming: false,
+ });
+ }
+ return true;
+ }
+
+ const infoEntry = createAttachmentInfoEntry(payload, activeSessionId, effectiveEvent, at);
+ if (infoEntry) {
+ appendEntry(delegate, infoEntry);
+ return true;
+ }
+
appendEntry(delegate, {
kind: "system",
id: createId("system"),
sessionId: activeSessionId,
- content,
- at: new Date().toISOString(),
+ content: `[${effectiveEvent}]`,
+ at,
meta: {
eventType: effectiveEvent,
rawPayload: payload as JsonObject,
- fileName: name || undefined,
- filePath: typeof payload.path === "string" ? payload.path : undefined,
},
});
return true;
@@ -373,6 +448,108 @@ function handleTodoUpdated(delegate: AppEventDelegate, payload: Record<string, u
return true;
}
+function normalizeNestedPayload(payload: Record<string, unknown>): Record<string, unknown> {
+ const nested = payload.payload;
+ if (nested && typeof nested === "object" && !Array.isArray(nested)) {
+ return nested as Record<string, unknown>;
+ }
+ return payload;
+}
+
+function normalizeTimestamp(value: unknown): number {
+ if (typeof value === "number" && Number.isFinite(value)) {
+ return value;
+ }
+ if (typeof value === "string") {
+ const parsed = Date.parse(value);
+ if (!Number.isNaN(parsed)) {
+ return parsed;
+ }
+ }
+ return Date.now();
+}
+
+function handleTeamMemberEvent(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+): boolean {
+ const normalized = normalizeNestedPayload(payload);
+ const event = normalized.event;
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
+ return false;
+ }
+ const record = event as Record<string, unknown>;
+ const memberId = typeof record.member_id === "string" ? record.member_id.trim() : "";
+ if (!memberId) {
+ return false;
+ }
+ delegate.appendTeamMemberEvent({
+ id: createId("team-member"),
+ type: typeof record.type === "string" ? record.type : "team.member",
+ teamId: typeof record.team_id === "string" ? record.team_id : "",
+ memberId,
+ oldStatus: typeof record.old_status === "string" ? record.old_status : undefined,
+ newStatus: typeof record.new_status === "string" ? record.new_status : undefined,
+ reason: typeof record.reason === "string" ? record.reason : undefined,
+ restartCount: typeof record.restart_count === "number" ? record.restart_count : undefined,
+ force: typeof record.force === "boolean" ? record.force : undefined,
+ timestamp: normalizeTimestamp(record.timestamp),
+ });
+ return true;
+}
+
+function handleTeamTaskEvent(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+): boolean {
+ const normalized = normalizeNestedPayload(payload);
+ const event = normalized.event;
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
+ return false;
+ }
+ const record = event as Record<string, unknown>;
+ const taskId = typeof record.task_id === "string" ? record.task_id.trim() : "";
+ if (!taskId) {
+ return false;
+ }
+ delegate.appendTeamTaskEvent({
+ id: createId("team-task"),
+ type: typeof record.type === "string" ? record.type : "team.task",
+ teamId: typeof record.team_id === "string" ? record.team_id : "",
+ taskId,
+ status: typeof record.status === "string" ? record.status : undefined,
+ timestamp: normalizeTimestamp(record.timestamp),
+ });
+ return true;
+}
+
+function handleTeamMessageEvent(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+): boolean {
+ const normalized = normalizeNestedPayload(payload);
+ const event = normalized.event;
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
+ return false;
+ }
+ const record = event as Record<string, unknown>;
+ const fromMember = typeof record.from_member === "string" ? record.from_member.trim() : "";
+ if (!fromMember) {
+ return false;
+ }
+ delegate.appendTeamMessageEvent({
+ id: createId("team-message"),
+ type: typeof record.type === "string" ? record.type : "team.message",
+ teamId: typeof record.team_id === "string" ? record.team_id : "",
+ messageId: typeof record.message_id === "string" ? record.message_id : undefined,
+ fromMember,
+ toMember: typeof record.to_member === "string" ? record.to_member : undefined,
+ content: typeof record.content === "string" ? record.content : "",
+ timestamp: normalizeTimestamp(record.timestamp),
+ });
+ return true;
+}
+
export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFrame): boolean {
const connectionChanged = handleConnectionAck(delegate, frame);
@@ -380,6 +557,9 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram
const effectiveEvent = typeof payload.event_type === "string" ? payload.event_type : frame.event;
const activeSessionId = delegate.getSessionId();
const eventSessionId = typeof payload.session_id === "string" ? payload.session_id : "";
+ if (effectiveEvent === "chat.processing_status" && !eventSessionId) {
+ return connectionChanged;
+ }
if (eventSessionId && eventSessionId !== activeSessionId) {
return connectionChanged;
}
@@ -398,26 +578,18 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram
return handleError(delegate, payload, activeSessionId) || connectionChanged;
case "chat.tool_call":
- delegate.setEntries(
- upsertToolGroup(
- delegate.getEntries(),
- activeSessionId,
- typeof payload.request_id === "string" ? payload.request_id : undefined,
- payload,
- false,
- ),
+ delegate.addToolCallPayload(
+ payload,
+ activeSessionId,
+ typeof payload.request_id === "string" ? payload.request_id : undefined,
);
return true;
case "chat.tool_result":
- delegate.setEntries(
- upsertToolGroup(
- delegate.getEntries(),
- activeSessionId,
- typeof payload.request_id === "string" ? payload.request_id : undefined,
- payload,
- true,
- ),
+ delegate.addToolResultPayload(
+ payload,
+ activeSessionId,
+ typeof payload.request_id === "string" ? payload.request_id : undefined,
);
return true;
@@ -433,7 +605,15 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram
case "chat.interrupt_result": {
const intent = typeof payload.intent === "string" ? payload.intent : "cancel";
- delegate.setStreamingState(intent === "cancel" ? StreamingState.Idle : StreamingState.Paused);
+ if (intent === "cancel") {
+ delegate.setStreamingState(StreamingState.Idle);
+ delegate.getActiveSubtasks().clear();
+ delegate.setEvolutionStatus("idle");
+ } else if (intent === "pause") {
+ delegate.setStreamingState(StreamingState.Paused);
+ } else {
+ delegate.setStreamingState(StreamingState.Responding);
+ }
return true;
}
@@ -492,6 +672,15 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram
return true;
}
+ case "team.member":
+ return handleTeamMemberEvent(delegate, payload);
+
+ case "team.task":
+ return handleTeamTaskEvent(delegate, payload);
+
+ case "team.message":
+ return handleTeamMessageEvent(delegate, payload);
+
default:
return connectionChanged;
}
diff --git a/jiuwenclaw/cli/src/core/final-content.ts b/jiuwenclaw/cli/src/core/final-content.ts
new file mode 100644
index 0000000000..a09a957793
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/final-content.ts
@@ -0,0 +1,49 @@
+function decodeQuotedPythonLikeString(raw: string): string {
+ return raw
+ .replace(/\\r/g, "\r")
+ .replace(/\\n/g, "\n")
+ .replace(/\\t/g, "\t")
+ .replace(/\\'/g, "'")
+ .replace(/\\"/g, '"')
+ .replace(/\\\\/g, "\\");
+}
+
+function normalizeFinalDisplayText(text: string): string {
+ return text.replace(/^(?:\r?\n)+/, "");
+}
+
+export function normalizeFinalContent(payload: Record<string, unknown>): string {
+ const rawContent = payload.content;
+ if (typeof rawContent !== "string") {
+ return "";
+ }
+
+ const trimmed = rawContent.trim();
+
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
+ try {
+ const parsed = JSON.parse(trimmed) as Record<string, unknown>;
+ if (typeof parsed.output === "string") {
+ return normalizeFinalDisplayText(parsed.output);
+ }
+ } catch {
+ // Ignore and fall through to Python-dict compatibility.
+ }
+ }
+
+ if (!trimmed.includes("result_type") || !trimmed.includes("output")) {
+ return normalizeFinalDisplayText(rawContent);
+ }
+
+ const singleQuoted = rawContent.match(/['"]output['"]\s*:\s*'((?:\\'|[^'])*)'/s);
+ if (singleQuoted?.[1] != null) {
+ return normalizeFinalDisplayText(decodeQuotedPythonLikeString(singleQuoted[1]));
+ }
+
+ const doubleQuoted = rawContent.match(/['"]output['"]\s*:\s*"((?:\\"|[^"])*)"/s);
+ if (doubleQuoted?.[1] != null) {
+ return normalizeFinalDisplayText(decodeQuotedPythonLikeString(doubleQuoted[1]));
+ }
+
+ return normalizeFinalDisplayText(rawContent);
+}
diff --git a/jiuwenclaw/cli/src/core/history-parser.ts b/jiuwenclaw/cli/src/core/history-parser.ts
index c782c1be9e..a67390f669 100644
--- a/jiuwenclaw/cli/src/core/history-parser.ts
+++ b/jiuwenclaw/cli/src/core/history-parser.ts
@@ -1,5 +1,6 @@
+import { normalizeFinalContent } from "./final-content.js";
import type { EventFrame } from "./protocol.js";
-import type { HistoryItem, JsonObject, JsonValue, ToolCallDisplay } from "./types.js";
+import type { HistoryItem, InfoMeta, JsonValue, MediaItem, ToolCallDisplay } from "./types.js";
function asString(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined;
@@ -9,14 +10,23 @@ function asBoolean(value: unknown): boolean | undefined {
return typeof value === "boolean" ? value : undefined;
}
-function toJsonObject(value: Record<string, unknown>): JsonObject {
- return value as unknown as JsonObject;
-}
-
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
+function pickFirstString(input: Record<string, unknown>, keys: string[]): string | undefined {
+ for (const key of keys) {
+ const value = input[key];
+ if (typeof value === "string") {
+ const trimmed = value.trim();
+ if (trimmed) {
+ return trimmed;
+ }
+ }
+ }
+ return undefined;
+}
+
function parseArguments(raw: unknown): Record<string, unknown> | undefined {
if (raw && typeof raw === "object") return raw as Record<string, unknown>;
if (typeof raw === "string") {
@@ -64,6 +74,166 @@ function resolveToolName(
);
}
+function normalizeHistoryRole(rawRole: unknown): "user" | "assistant" | "tool" | "system" {
+ if (typeof rawRole !== "string") return "assistant";
+ const role = rawRole.trim().toLowerCase();
+ if (role === "user" || role === "human") return "user";
+ if (role === "assistant" || role === "ai" || role === "bot") return "assistant";
+ if (role === "tool" || role === "tool_call" || role === "tool_result") return "tool";
+ if (role === "system") return "system";
+ return "assistant";
+}
+
+function recordTimestampIso(record: Record<string, unknown>): string {
+ const ts = record.timestamp;
+ if (typeof ts === "number" && Number.isFinite(ts)) {
+ const millis = ts > 1_000_000_000_000 ? ts : ts * 1000;
+ const d = new Date(millis);
+ if (!Number.isNaN(d.getTime())) {
+ return d.toISOString();
+ }
+ }
+ if (typeof ts === "string") {
+ const parsed = Date.parse(ts);
+ if (!Number.isNaN(parsed)) {
+ return new Date(parsed).toISOString();
+ }
+ }
+ return new Date().toISOString();
+}
+
+function buildEventPayloadForRecord(record: Record<string, unknown>): Record<string, unknown> {
+ const eventPayload = asRecord(record.event_payload);
+ const base = eventPayload ? { ...eventPayload } : {};
+ if (typeof record.content === "string" && typeof base.content !== "string") {
+ base.content = record.content;
+ }
+ if (typeof record.request_id === "string" && typeof base.request_id !== "string") {
+ base.request_id = record.request_id;
+ }
+ if (typeof record.session_id === "string" && typeof base.session_id !== "string") {
+ base.session_id = record.session_id;
+ }
+ return base;
+}
+
+function isHistoryDonePayload(payload: Record<string, unknown>): boolean {
+ const status = typeof payload.status === "string" ? payload.status.trim().toLowerCase() : "";
+ if (status === "done") {
+ return true;
+ }
+ const content = typeof payload.content === "string" ? payload.content.trim().toLowerCase() : "";
+ return content === "done";
+}
+
+function summarizePath(value: string): string {
+ const parts = value.split(/[\\/]/).filter(Boolean);
+ return parts.length <= 3 ? value : parts.slice(-3).join("/");
+}
+
+function inferMediaType(
+ explicitType: string | undefined,
+ mimeType: string | undefined,
+): MediaItem["type"] {
+ const normalizedType = explicitType?.trim().toLowerCase();
+ const normalizedMime = mimeType?.trim().toLowerCase();
+ if (normalizedType === "image" || normalizedMime?.startsWith("image/")) return "image";
+ if (normalizedType === "audio" || normalizedMime?.startsWith("audio/")) return "audio";
+ if (normalizedType === "video" || normalizedMime?.startsWith("video/")) return "video";
+ return "document";
+}
+
+export function extractMediaItems(payload: Record<string, unknown>): MediaItem[] {
+ const files = Array.isArray(payload.files) ? payload.files : [];
+ const mediaItems = Array.isArray(payload.media_items) ? payload.media_items : [];
+ const rawItems = [...mediaItems, ...files].filter((item): item is Record<string, unknown> =>
+ Boolean(item && typeof item === "object"),
+ );
+
+ return rawItems.map((item, index) => {
+ const mimeType =
+ pickFirstString(item, ["mimeType", "mime_type"]) ??
+ (Array.isArray(payload.files) ? "application/octet-stream" : "application/octet-stream");
+ const filename =
+ pickFirstString(item, ["filename", "file_name", "name", "title"]) ??
+ pickFirstString(item, ["path", "url"]) ??
+ `item-${index + 1}`;
+ const url = pickFirstString(item, ["url", "path", "fullPath", "full_path"]);
+ const base64Data = pickFirstString(item, ["base64Data", "base64_data", "data"]);
+ return {
+ type: inferMediaType(pickFirstString(item, ["type"]), mimeType),
+ mimeType,
+ filename,
+ ...(base64Data ? { base64Data } : {}),
+ ...(url ? { url } : {}),
+ };
+ });
+}
+
+function buildAttachmentItems(payload: Record<string, unknown>): NonNullable<InfoMeta["items"]> {
+ return extractMediaItems(payload).map((item) => {
+ return {
+ label: summarizePath(item.filename),
+ value: item.url ? summarizePath(item.url) : undefined,
+ description: item.type === "document" ? item.mimeType : item.type,
+ };
+ });
+}
+
+function summarizeAttachmentHeadline(
+ mediaItems: MediaItem[],
+ effectiveEvent: "chat.media" | "chat.file",
+): string {
+ if (mediaItems.length === 0) {
+ return effectiveEvent === "chat.file" ? "Attached file" : "Added media";
+ }
+
+ const counts = {
+ image: mediaItems.filter((item) => item.type === "image").length,
+ audio: mediaItems.filter((item) => item.type === "audio").length,
+ video: mediaItems.filter((item) => item.type === "video").length,
+ document: mediaItems.filter((item) => item.type === "document").length,
+ };
+
+ const parts: string[] = [];
+ if (counts.image > 0) parts.push(`${counts.image} image${counts.image === 1 ? "" : "s"}`);
+ if (counts.audio > 0) parts.push(`${counts.audio} audio`);
+ if (counts.video > 0) parts.push(`${counts.video} video${counts.video === 1 ? "" : "s"}`);
+ if (counts.document > 0) parts.push(`${counts.document} file${counts.document === 1 ? "" : "s"}`);
+ return `${effectiveEvent === "chat.file" ? "Attached" : "Added"} ${parts.join(", ")}`;
+}
+
+export function createAttachmentInfoEntry(
+ payload: Record<string, unknown>,
+ sessionId: string,
+ effectiveEvent: "chat.media" | "chat.file",
+ at = new Date().toISOString(),
+): Extract<HistoryItem, { kind: "info" }> | null {
+ const mediaItems = extractMediaItems(payload);
+ const items = buildAttachmentItems(payload);
+ const content =
+ pickFirstString(payload, ["content", "text", "message"]) ??
+ summarizeAttachmentHeadline(mediaItems, effectiveEvent);
+
+ if (items.length === 0 && !pickFirstString(payload, ["content", "text", "message"])) {
+ return null;
+ }
+
+ return {
+ kind: "info",
+ id: pickFirstString(payload, ["id", "message_id", "msg_id"]) ?? `media-${Date.now()}`,
+ sessionId,
+ content,
+ at,
+ ...(mediaItems.length > 0 ? { mediaItems } : {}),
+ meta: {
+ view: "list",
+ title: content,
+ items,
+ },
+ };
+}
+
export function createToolCallDisplay(payload: Record<string, unknown>): ToolCallDisplay {
const toolPayload = resolveToolPayload(payload, "tool_call");
return {
@@ -142,26 +312,48 @@ export function createSessionResultToolDisplay(
export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {
if (frame.event !== "history.message") return null;
- const payload = frame.payload;
- const sessionId = asString(payload.session_id) ?? "";
- const role = asString(payload.role) ?? "";
- const eventType = asString(payload.event_type) ?? asString(payload.type) ?? "";
- const sourceChunkType = asString(payload.source_chunk_type) ?? "";
- const at = asString(payload.at) ?? new Date().toISOString();
- const id = asString(payload.id) ?? `hist-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ const outerPayload = frame.payload;
+ if (isHistoryDonePayload(outerPayload)) {
+ return null;
+ }
+
+ const record = asRecord(outerPayload.message) ?? outerPayload;
+ const sessionId =
+ pickFirstString(record, ["session_id"]) ?? asString(outerPayload.session_id) ?? "";
+ const role = normalizeHistoryRole(record.role);
+ const at = recordTimestampIso(record);
+ const id =
+ pickFirstString(record, ["id", "message_id", "msg_id"]) ??
+ `hist-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
if (role === "user") {
- const content = asString(payload.content) ?? "";
+ const content = pickFirstString(record, ["content", "text", "body"]) ?? "";
if (!content) return null;
return { kind: "user", id, sessionId, content, at };
}
+ if (role !== "assistant") {
+ return null;
+ }
+
+ const sourceChunkType = pickFirstString(record, ["source_chunk_type"]) ?? "";
+ let eventType = pickFirstString(record, ["event_type", "type"]) ?? "";
+ if (!eventType) {
+ const rawContent = pickFirstString(record, ["content"]) ?? "";
+ if (!rawContent) {
+ return null;
+ }
+ eventType = "chat.final";
+ }
+
+ const payload = buildEventPayloadForRecord(record);
+
if (eventType === "chat.tool_call") {
return {
kind: "tool_group",
id,
sessionId,
- requestId: asString(payload.request_id),
+ requestId: pickFirstString(record, ["request_id"]) ?? asString(payload.request_id),
tools: [createToolCallDisplay(payload)],
at,
};
@@ -172,35 +364,38 @@ export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {
kind: "tool_group",
id,
sessionId,
- requestId: asString(payload.request_id),
+ requestId: pickFirstString(record, ["request_id"]) ?? asString(payload.request_id),
tools: [applyToolResult(createToolCallDisplay(payload), payload)],
at,
};
}
- if (eventType === "chat.media" || eventType === "chat.file") {
- const name = asString(payload.file_name) ?? asString(payload.name);
- const label = name ? `[${eventType}: ${name}]` : `[${eventType}]`;
+ if (eventType === "chat.media") {
+ const mediaItems = extractMediaItems(payload);
+ const content = pickFirstString(payload, ["content", "text", "message"]) ?? "";
+ if (!content && mediaItems.length === 0) {
+ return null;
+ }
return {
- kind: "system",
+ kind: "assistant",
id,
sessionId,
- content: label,
+ content,
+ ...(mediaItems.length > 0 ? { mediaItems } : {}),
+ requestId: pickFirstString(record, ["request_id"]) ?? asString(payload.request_id),
at,
- meta: {
- eventType,
- rawPayload: toJsonObject(payload),
- fileName: name,
- filePath: asString(payload.path),
- },
};
}
+ if (eventType === "chat.file") {
+ return createAttachmentInfoEntry(payload, sessionId, eventType, at);
+ }
+
if (
eventType === "chat.reasoning" ||
(eventType === "chat.delta" && sourceChunkType === "llm_reasoning")
) {
- const content = asString(payload.content) ?? "";
+ const content = pickFirstString(payload, ["content"]) ?? "";
if (!content) return null;
return {
kind: "thinking",
@@ -216,7 +411,7 @@ export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {
kind: "tool_group",
id,
sessionId,
- requestId: asString(payload.request_id),
+ requestId: pickFirstString(record, ["request_id"]) ?? asString(payload.request_id),
tools: [createSessionResultToolDisplay(payload, eventType)],
at,
};
@@ -233,14 +428,17 @@ export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {
return null;
}
- const content = asString(payload.content) ?? "";
+ const content =
+ eventType === "chat.final"
+ ? normalizeFinalContent(payload)
+ : (pickFirstString(payload, ["content"]) ?? "");
if (!content) return null;
return {
kind: "assistant",
id,
sessionId,
content,
- requestId: asString(payload.request_id),
+ requestId: pickFirstString(record, ["request_id"]) ?? asString(payload.request_id),
at,
};
}
diff --git a/jiuwenclaw/cli/src/core/transcript-timeline.ts b/jiuwenclaw/cli/src/core/transcript-timeline.ts
new file mode 100644
index 0000000000..42c1f7b4aa
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/transcript-timeline.ts
@@ -0,0 +1,247 @@
+import type { HistoryItem, ToolExecution } from "./types.js";
+
+type TimelineItem =
+ | {
+ type: "message";
+ timestampMs: number;
+ sourceIndex: number;
+ entry: Exclude<HistoryItem, { kind: "tool_group" }>;
+ }
+ | {
+ type: "tool_execution";
+ timestampMs: number;
+ sourceIndex: number;
+ execution: ToolExecution;
+ };
+
+function toTimestampMs(value: string | undefined): number {
+ if (!value) return Number.NaN;
+ const ts = Date.parse(value);
+ return Number.isNaN(ts) ? Number.NaN : ts;
+}
+
+function compareTimelineItems(a: TimelineItem, b: TimelineItem): number {
+ const aValid = Number.isFinite(a.timestampMs);
+ const bValid = Number.isFinite(b.timestampMs);
+ if (aValid && bValid && a.timestampMs !== b.timestampMs) {
+ return a.timestampMs - b.timestampMs;
+ }
+ if (aValid !== bValid) {
+ return aValid ? -1 : 1;
+ }
+ return a.sourceIndex - b.sourceIndex;
+}
+
+function buildTimelineItems(entries: HistoryItem[], executions: ToolExecution[]): TimelineItem[] {
+ const messageItems: TimelineItem[] = entries
+ .filter(
+ (entry): entry is Exclude<HistoryItem, { kind: "tool_group" }> => entry.kind !== "tool_group",
+ )
+ .map((entry, index) => ({
+ type: "message",
+ timestampMs: toTimestampMs(entry.at),
+ sourceIndex: index,
+ entry,
+ }));
+
+ const executionItems: TimelineItem[] = executions.map((execution, index) => ({
+ type: "tool_execution",
+ timestampMs: toTimestampMs(execution.startedAt),
+ sourceIndex: entries.length + index,
+ execution,
+ }));
+
+ return [...messageItems, ...executionItems].sort(compareTimelineItems);
+}
+
+function isReadLikeTool(name: string): boolean {
+ const normalized = name.trim().toLowerCase();
+ return (
+ normalized === "read" ||
+ normalized === "read_file" ||
+ normalized === "read_text_file" ||
+ normalized === "read_memory" ||
+ normalized === "memory_get" ||
+ normalized === "view"
+ );
+}
+
+function isSearchLikeTool(name: string): boolean {
+ const normalized = name.trim().toLowerCase();
+ return (
+ normalized === "search" ||
+ normalized === "grep" ||
+ normalized === "rg" ||
+ normalized === "ripgrep" ||
+ normalized === "memory_search" ||
+ normalized === "mcp_free_search" ||
+ normalized === "mcp_paid_search" ||
+ normalized === "glob" ||
+ normalized === "glob_files" ||
+ normalized === "glob_file_search"
+ );
+}
+
+function isListLikeTool(name: string): boolean {
+ const normalized = name.trim().toLowerCase();
+ return normalized === "ls" || normalized === "list_files" || normalized === "list_dir";
+}
+
+function isFetchLikeTool(name: string): boolean {
+ const normalized = name.trim().toLowerCase();
+ return (
+ normalized === "fetch" || normalized === "fetch_webpage" || normalized === "mcp_fetch_webpage"
+ );
+}
+
+function isCollapsibleTool(name: string): boolean {
+ return (
+ isReadLikeTool(name) || isSearchLikeTool(name) || isListLikeTool(name) || isFetchLikeTool(name)
+ );
+}
+
+type CollapsibleToolKind = "read" | "search" | "list" | "fetch" | null;
+
+function getCollapsibleToolKind(name: string): CollapsibleToolKind {
+ if (isReadLikeTool(name)) return "read";
+ if (isSearchLikeTool(name)) return "search";
+ if (isListLikeTool(name)) return "list";
+ if (isFetchLikeTool(name)) return "fetch";
+ return null;
+}
+
+function summarizePath(value: unknown): string | undefined {
+ if (typeof value !== "string" || !value.trim()) return undefined;
+ const parts = value.split(/[\\/]/).filter(Boolean);
+ return parts.slice(-3).join("/") || value;
+}
+
+function getLatestHintFromTool(execution: ToolExecution): string | undefined {
+ const tool = execution.tool;
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ if (isReadLikeTool(tool.name) || isListLikeTool(tool.name)) {
+ return summarizePath(args.path ?? args.file_path ?? args.file ?? args.dir_path);
+ }
+ if (isSearchLikeTool(tool.name)) {
+ const pattern =
+ typeof args.pattern === "string"
+ ? args.pattern
+ : typeof args.query === "string"
+ ? args.query
+ : typeof args.q === "string"
+ ? args.q
+ : undefined;
+ return pattern ? `"${pattern}"` : undefined;
+ }
+ if (isFetchLikeTool(tool.name)) {
+ return typeof args.url === "string" ? args.url : undefined;
+ }
+ return tool.formattedArgs ?? tool.description;
+}
+
+function buildCollapsedToolGroup(
+ executions: ToolExecution[],
+): Extract<HistoryItem, { kind: "collapsed_tool_group" }> {
+ const first = executions[0]!;
+ const counts = {
+ read: 0,
+ search: 0,
+ list: 0,
+ fetch: 0,
+ };
+ for (const execution of executions) {
+ if (isReadLikeTool(execution.tool.name)) counts.read += 1;
+ else if (isListLikeTool(execution.tool.name)) counts.list += 1;
+ else if (isFetchLikeTool(execution.tool.name)) counts.fetch += 1;
+ else if (isSearchLikeTool(execution.tool.name)) counts.search += 1;
+ }
+ const latestHint =
+ [...executions]
+ .reverse()
+ .map((execution) => getLatestHintFromTool(execution))
+ .find((hint) => typeof hint === "string" && hint.trim().length > 0) ?? undefined;
+ return {
+ kind: "collapsed_tool_group",
+ id: `collapsed-tool-group-${first.toolCallId}`,
+ sessionId: first.sessionId,
+ requestId: first.requestId,
+ tools: executions.map((execution) => execution.tool),
+ at: first.startedAt,
+ latestHint,
+ counts,
+ };
+}
+
+function pushExecutionChunk(renderEntries: HistoryItem[], executions: ToolExecution[]): void {
+ if (executions.length === 0) {
+ return;
+ }
+ const first = executions[0]!;
+ if (
+ executions.length >= 2 &&
+ executions.every((execution) => isCollapsibleTool(execution.tool.name))
+ ) {
+ renderEntries.push(buildCollapsedToolGroup(executions));
+ return;
+ }
+ renderEntries.push({
+ kind: "tool_group",
+ id: `tool-group-${first.toolCallId}`,
+ sessionId: first.sessionId,
+ requestId: first.requestId,
+ tools: executions.map((execution) => execution.tool),
+ at: first.startedAt,
+ });
+}
+
+export function buildTranscriptEntries(
+ entries: HistoryItem[],
+ executions: ToolExecution[],
+): HistoryItem[] {
+ const timeline = buildTimelineItems(entries, executions);
+ const renderEntries: HistoryItem[] = [];
+ let bufferedExecutions: ToolExecution[] = [];
+
+ const flushExecutions = () => {
+ if (bufferedExecutions.length === 0) {
+ return;
+ }
+ let chunk: ToolExecution[] = [];
+ for (const execution of bufferedExecutions) {
+ const previousKind =
+ chunk.length > 0 ? getCollapsibleToolKind(chunk[chunk.length - 1]!.tool.name) : null;
+ const currentKind = getCollapsibleToolKind(execution.tool.name);
+ if (chunk.length > 0 && previousKind !== currentKind) {
+ pushExecutionChunk(renderEntries, chunk);
+ chunk = [];
+ }
+ chunk.push(execution);
+ }
+ pushExecutionChunk(renderEntries, chunk);
+ bufferedExecutions = [];
+ };
+
+ for (const item of timeline) {
+ if (item.type === "tool_execution") {
+ bufferedExecutions.push(item.execution);
+ continue;
+ }
+ flushExecutions();
+ renderEntries.push(item.entry);
+ }
+
+ flushExecutions();
+ return renderEntries;
+}
+
+export function getToolGroupIds(entries: HistoryItem[], executions: ToolExecution[]): string[] {
+ return buildTranscriptEntries(entries, executions)
+ .filter(
+ (entry): entry is Extract<HistoryItem, { kind: "tool_group" | "collapsed_tool_group" }> =>
+ entry.kind === "tool_group" || entry.kind === "collapsed_tool_group",
+ )
+ .map((entry) => entry.id);
+}
diff --git a/jiuwenclaw/cli/src/core/types.ts b/jiuwenclaw/cli/src/core/types.ts
index 56ff44eb2b..cfc8254385 100644
--- a/jiuwenclaw/cli/src/core/types.ts
+++ b/jiuwenclaw/cli/src/core/types.ts
@@ -11,6 +11,14 @@ export interface JsonObject {
[key: string]: JsonValue;
}
+export interface MediaItem {
+ type: "image" | "audio" | "video" | "document";
+ mimeType: string;
+ filename: string;
+ base64Data?: string;
+ url?: string;
+}
+
export interface SystemMeta {
eventType?: "chat.media" | "chat.file" | "notice";
rawPayload?: JsonObject;
@@ -30,12 +38,26 @@ export interface ToolCallDisplay {
arguments?: unknown;
description?: string;
formattedArgs?: string;
- status: "running" | "completed" | "error";
+ status: "running" | "completed" | "error" | "timeout";
result?: string;
summary?: string;
isError?: boolean;
}
+export type ToolExecutionStatus = "pending" | "timeout" | "completed" | "error";
+
+export interface ToolExecution {
+ toolCallId: string;
+ sessionId: string;
+ requestId?: string;
+ tool: ToolCallDisplay;
+ startedAt: string;
+ updatedAt: string;
+ timeoutAt: string;
+ timedOutAt?: string;
+ resultArrivedAfterTimeout?: boolean;
+}
+
export type SubtaskStatus = "starting" | "tool_call" | "tool_result" | "completed" | "error";
export interface SubtaskState {
@@ -67,6 +89,39 @@ export interface TodoItem {
updatedAt: string;
}
+export interface TeamMemberEvent {
+ id: string;
+ type: string;
+ teamId: string;
+ memberId: string;
+ oldStatus?: string;
+ newStatus?: string;
+ reason?: string;
+ restartCount?: number;
+ force?: boolean;
+ timestamp: number;
+}
+
+export interface TeamTaskEvent {
+ id: string;
+ type: string;
+ teamId: string;
+ taskId: string;
+ status?: string;
+ timestamp: number;
+}
+
+export interface TeamMessageEvent {
+ id: string;
+ type: string;
+ teamId: string;
+ messageId?: string;
+ fromMember: string;
+ toMember?: string;
+ content: string;
+ timestamp: number;
+}
+
export type HistoryItem =
| { kind: "user"; id: string; sessionId: string; content: string; at: string }
| {
@@ -74,6 +129,9 @@ export type HistoryItem =
id: string;
sessionId: string;
content: string;
+ mediaItems?: MediaItem[];
+ audioBase64?: string;
+ audioMime?: string;
streaming?: boolean;
requestId?: string;
at: string;
@@ -87,6 +145,21 @@ export type HistoryItem =
tools: ToolCallDisplay[];
at: string;
}
+ | {
+ kind: "collapsed_tool_group";
+ id: string;
+ sessionId: string;
+ requestId?: string;
+ tools: ToolCallDisplay[];
+ at: string;
+ latestHint?: string;
+ counts: {
+ read: number;
+ search: number;
+ list: number;
+ fetch: number;
+ };
+ }
| {
kind: "system";
id: string;
@@ -103,5 +176,6 @@ export type HistoryItem =
content: string;
icon?: string;
meta?: InfoMeta;
+ mediaItems?: MediaItem[];
at: string;
};
diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.ts
index df8aa56216..4ed1795efa 100644
--- a/jiuwenclaw/cli/src/ui/app-screen.ts
+++ b/jiuwenclaw/cli/src/ui/app-screen.ts
@@ -8,15 +8,23 @@ import {
type Focusable,
type SlashCommand as TuiSlashCommand,
TUI,
+ matchesKey,
} from "@mariozechner/pi-tui";
+import { statSync } from "node:fs";
+import { basename, extname, resolve } from "node:path";
+import { spawnSync } from "node:child_process";
import type { CliPiAppState } from "../app-state.js";
import { CommandService, parseSlashCommand } from "../core/commands/CommandService.js";
+import { addError, addInfo } from "../core/commands/helpers.js";
+import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/resume.js";
import { handleAppScreenKeyInput } from "./keymap.js";
import { buildAppScreenLines } from "./screen-layout.js";
+import { orderedMemberIds } from "./components/team-shared.js";
import { padToWidth } from "./rendering/text.js";
import { editorTheme, palette, selectListTheme } from "./theme.js";
const END_CURSOR = "\x1b[7m \x1b[0m";
+const COMPOSER_ATTACHMENT_TOKEN_RE = /\[Image #(\d+)\]/g;
const PERMISSION_TOOL_RE = /工具\s+`([^`]+)`\s+需要授权/;
const PERMISSION_RISK_RE = /安全风险评估:\**\s*([^\s*]+)?\s*\**([^*\n]+?风险)\**/m;
const PERMISSION_QUOTE_RE = /^>\s*(.+)$/gm;
@@ -30,6 +38,175 @@ type PermissionSummary = {
description?: string;
};
+type ComposerAttachment = {
+ id: string;
+ kind: "image";
+ path: string;
+ filename: string;
+};
+
+type ResumeSessionListState = {
+ list: SelectList;
+ sessions: SessionMeta[];
+ total: number;
+};
+
+const IMAGE_MIME_TYPES: Record<string, string> = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+};
+
+function resolveFdBinary(): string | null {
+ for (const candidate of ["fd", "fdfind"]) {
+ const result = spawnSync(candidate, ["--version"], {
+ stdio: "ignore",
+ timeout: 400,
+ });
+ if (result.status === 0) {
+ return candidate;
+ }
+ }
+ return null;
+}
+
+function normalizeComposerPath(raw: string): string | null {
+ const trimmed = raw
+ .trim()
+ .replace(/^@/, "")
+ .replace(/^"(.*)"$/, "$1");
+ if (!trimmed) return null;
+ if (trimmed.startsWith("file://")) {
+ try {
+ return decodeURIComponent(trimmed.slice("file://".length));
+ } catch {
+ return trimmed.slice("file://".length);
+ }
+ }
+ return trimmed;
+}
+
+function looksLikeImagePath(path: string): boolean {
+ return extname(path).toLowerCase() in IMAGE_MIME_TYPES;
+}
+
+function expandUserPath(path: string): string {
+ if (path === "~") {
+ return process.env.HOME ?? path;
+ }
+ if (path.startsWith("~/")) {
+ return resolve(process.env.HOME ?? "~", path.slice(2));
+ }
+ return resolve(process.cwd(), path);
+}
+
+function formatComposerAttachmentPath(path: string): string {
+ return /\s/.test(path) ? `@"${path}"` : `@${path}`;
+}
+
+function composerAttachmentToken(index: number): string {
+ return `[Image #${index}] `;
+}
+
+function findAttachmentTokenAtCursor(
+ line: string,
+ cursorCol: number,
+): { start: number; end: number } | null {
+ for (const match of line.matchAll(COMPOSER_ATTACHMENT_TOKEN_RE)) {
+ const start = match.index ?? -1;
+ if (start < 0) continue;
+ const end = start + match[0].length;
+ if (cursorCol > start && cursorCol <= end) {
+ return { start, end };
+ }
+ }
+ return null;
+}
+
+function syncComposerImageTokens(
+ text: string,
+ existingAttachments: ComposerAttachment[],
+ shouldConsume: (path: string) => boolean,
+): { normalizedText: string; attachments: ComposerAttachment[] } {
+ let attachments = [...existingAttachments];
+ let working = text;
+
+ const findOrAddAttachment = (resolvedPath: string): number => {
+ const existingIndex = attachments.findIndex((attachment) => attachment.path === resolvedPath);
+ if (existingIndex >= 0) {
+ return existingIndex + 1;
+ }
+ attachments.push({
+ id: `attachment-${Date.now().toString(16)}-${attachments.length}`,
+ kind: "image",
+ path: resolvedPath,
+ filename: basename(resolvedPath),
+ });
+ return attachments.length;
+ };
+
+ const consume = (rawPath: string): string | null => {
+ const normalized = normalizeComposerPath(rawPath);
+ if (!normalized) return null;
+ const resolved = expandUserPath(normalized);
+ if (!shouldConsume(resolved)) return null;
+ return composerAttachmentToken(findOrAddAttachment(resolved));
+ };
+
+ working = working.replace(/(^|[\t ])@(?:"([^"]+)"|([^\s]+))/gm, (full, prefix, quoted, plain) => {
+ const replacement = consume(quoted ?? plain ?? "");
+ return replacement ? `${prefix}${replacement}` : full;
+ });
+
+ working = working.replace(
+ /(^|[\t ])((?:file:\/\/[^\s]+|(?:~\/|\.{1,2}\/|\/)[^\s"'`]+\.(?:png|jpe?g|gif|webp)))(?=$|[\t ])/gim,
+ (full, prefix, rawPath) => {
+ const replacement = consume(rawPath ?? "");
+ return replacement ? `${prefix}${replacement}` : full;
+ },
+ );
+
+ const tokenMatches = [...working.matchAll(/\[Image #(\d+)\]/g)];
+ const nextAttachments: ComposerAttachment[] = [];
+ for (const match of tokenMatches) {
+ const tokenIndex = Number.parseInt(match[1] ?? "", 10);
+ if (!Number.isFinite(tokenIndex) || tokenIndex < 1) {
+ continue;
+ }
+ const attachment = attachments[tokenIndex - 1];
+ if (attachment) {
+ nextAttachments.push(attachment);
+ }
+ }
+ attachments = nextAttachments;
+
+ let tokenOrdinal = 0;
+ working = working.replace(/\[Image #(\d+)\]\s*/g, () => {
+ tokenOrdinal += 1;
+ return composerAttachmentToken(tokenOrdinal);
+ });
+
+ const normalizedText = working
+ .replace(/[ \t]+\n/g, "\n")
+ .replace(/\n[ \t]+/g, "\n")
+ .replace(/[ \t]{2,}/g, " ");
+
+ return { normalizedText, attachments };
+}
+
+function expandComposerImageTokens(text: string, attachments: ComposerAttachment[]): string {
+ return text.replace(/\[Image #(\d+)\]\s*/g, (_full, rawIndex: string) => {
+ const index = Number.parseInt(rawIndex, 10);
+ if (!Number.isFinite(index) || index < 1) {
+ return "";
+ }
+ const attachment = attachments[index - 1];
+ return attachment ? `${formatComposerAttachmentPath(attachment.path)} ` : "";
+ });
+}
+
function isPermissionRequest(source: string | undefined, questionText: string): boolean {
return source === "permission" || PERMISSION_TOOL_RE.test(questionText);
}
@@ -71,6 +248,147 @@ function parsePermissionSummary(questionText: string): PermissionSummary {
};
}
+function compressRiskLabel(risk: string | undefined): string | undefined {
+ if (!risk) return undefined;
+ const normalized = risk.replace(/\s+/g, " ").trim();
+ return normalized
+ .replace(/^高\s*/u, "High ")
+ .replace(/^中\s*/u, "Medium ")
+ .replace(/^低\s*/u, "Low ")
+ .replace(/风险$/u, "risk");
+}
+
+function permissionToolKind(tool: string | undefined): "bash" | "filesystem" | "generic" {
+ const normalized = tool?.trim().toLowerCase() ?? "";
+ if (
+ normalized === "bash" ||
+ normalized === "shell" ||
+ normalized === "sh" ||
+ normalized === "powershell" ||
+ normalized === "command" ||
+ normalized === "exec" ||
+ normalized === "run" ||
+ normalized === "mcp_exec_command" ||
+ normalized === "create_terminal"
+ ) {
+ return "bash";
+ }
+ if (
+ normalized.includes("read") ||
+ normalized.includes("write") ||
+ normalized.includes("edit") ||
+ normalized.includes("search") ||
+ normalized.includes("grep") ||
+ normalized.includes("glob") ||
+ normalized.includes("fetch") ||
+ normalized.includes("file") ||
+ normalized.includes("memory")
+ ) {
+ return "filesystem";
+ }
+ return "generic";
+}
+
+function extractFilesystemTarget(summary: PermissionSummary): string | undefined {
+ const raw = summary.command ?? summary.description ?? "";
+ const quoted = /(["'`])([^"'`]+)\1/.exec(raw)?.[2]?.trim();
+ if (quoted) return quoted;
+ const pathish = /((?:\/|\.\/|\.\.\/)[^\s,)]+)/.exec(raw)?.[1]?.trim();
+ if (pathish) return pathish;
+ return undefined;
+}
+
+function renderPermissionBlock(
+ width: number,
+ summary: PermissionSummary,
+ progressLabel: string,
+): string[] {
+ const lines: string[] = [];
+ const risk = compressRiskLabel(summary.risk);
+ const kind = permissionToolKind(summary.tool);
+ const primaryDetail = summary.command ?? summary.description ?? summary.reason;
+
+ lines.push(padToWidth(palette.status.warning(progressLabel), width));
+
+ if (kind === "bash") {
+ lines.push(
+ padToWidth(palette.text.assistant(`${summary.tool ?? "command"} wants to run`), width),
+ );
+ if (summary.command) {
+ lines.push(
+ ...wrapPlainText(summary.command, width)
+ .slice(0, 2)
+ .map((line) => padToWidth(palette.text.tool(line), width)),
+ );
+ } else if (primaryDetail) {
+ lines.push(
+ ...wrapPlainText(primaryDetail, width)
+ .slice(0, 2)
+ .map((line) => padToWidth(palette.text.dim(line), width)),
+ );
+ }
+ } else if (kind === "filesystem") {
+ lines.push(
+ padToWidth(palette.text.assistant(`${summary.tool ?? "tool"} wants to access files`), width),
+ );
+ const target = extractFilesystemTarget(summary);
+ if (target) {
+ lines.push(padToWidth(palette.text.tool(target), width));
+ }
+ if (primaryDetail && primaryDetail !== target) {
+ lines.push(
+ ...wrapPlainText(primaryDetail, width)
+ .slice(0, 1)
+ .map((line) => padToWidth(palette.text.dim(line), width)),
+ );
+ }
+ } else {
+ if (summary.tool) {
+ lines.push(padToWidth(palette.text.assistant(`${summary.tool} requires permission`), width));
+ }
+ if (primaryDetail) {
+ lines.push(
+ ...wrapPlainText(primaryDetail, width)
+ .slice(0, 2)
+ .map((line) =>
+ padToWidth(summary.command ? palette.text.tool(line) : palette.text.dim(line), width),
+ ),
+ );
+ }
+ }
+
+ if (risk) {
+ lines.push(
+ padToWidth(
+ /high/i.test(risk) ? palette.status.error(risk) : palette.status.warning(risk),
+ width,
+ ),
+ );
+ }
+
+ return lines;
+}
+
+function normalizePermissionOptionLabel(label: string): string {
+ const trimmed = label.trim();
+ if (trimmed === "本次允许") return "Allow once";
+ if (trimmed === "总是允许") return "Always allow";
+ if (trimmed === "拒绝") return "Reject";
+ return trimmed;
+}
+
+function isAllowOption(label: string): boolean {
+ const normalized = label.trim();
+ return normalized.includes("允许") || /^allow\b/i.test(normalized);
+}
+
+function isRejectOption(label: string): boolean {
+ const normalized = label.trim();
+ return (
+ normalized.includes("拒绝") || /^reject\b/i.test(normalized) || /^deny\b/i.test(normalized)
+ );
+}
+
function wrapPlainText(text: string, width: number): string[] {
const maxWidth = Math.max(12, width - 1);
const source = text.replace(/\r/g, "").split("\n");
@@ -100,21 +418,42 @@ function wrapPlainText(text: string, width: number): string[] {
return lines.length > 0 ? lines : [text.slice(0, maxWidth)];
}
+function formatSessionTime(timestamp: number | undefined): string {
+ if (!timestamp) return "-";
+ return new Date(timestamp * 1000).toLocaleString();
+}
+
+function buildResumeSessionItems(sessions: SessionMeta[]): SelectItem[] {
+ return sessions.map((session) => ({
+ value: session.session_id,
+ label: session.title?.trim() || session.session_id,
+ description: `${session.session_id} · msgs ${session.message_count ?? 0} · ${formatSessionTime(session.last_message_at)}`,
+ }));
+}
+
export class AppScreen implements Component, Focusable {
private readonly editor: Editor;
private readonly unsubscribe: () => void;
+ private readonly composerAutocompleteProvider: CombinedAutocompleteProvider;
private _focused = false;
private activeQuestionId: string | null = null;
private activeQuestionIndex = 0;
private draftBeforeQuestion = "";
+ private draftAttachmentsBeforeQuestion: ComposerAttachment[] = [];
+ private composerAttachments: ComposerAttachment[] = [];
+ private syncingComposerInput = false;
private pendingQuestionAnswers = new Map<number, string>();
private questionList: SelectList | null = null;
- private showFullThinking = true;
- private showToolDetails = false;
- private showShortcutHelp = false;
+ private resumeSessionList: ResumeSessionListState | null = null;
+ private showTodos = true;
+ private showTeamPanel = false;
+ private selectedTeamMemberId: string | null = null;
private exitArmedUntil = 0;
private transientNotice: string | null = null;
private transientNoticeTimer: ReturnType<typeof setTimeout> | null = null;
+ private animationTimer: ReturnType<typeof setInterval> | null = null;
+ private animationPhase = 0;
+ private runningStartedAtMs: number | null = null;
constructor(
private readonly tui: TUI,
@@ -123,10 +462,14 @@ export class AppScreen implements Component, Focusable {
private readonly exit: () => void,
) {
this.editor = new Editor(tui, editorTheme, { paddingX: 1, autocompleteMaxVisible: 6 });
- this.editor.setAutocompleteProvider(
- new CombinedAutocompleteProvider(this.buildSlashCommands(), process.cwd()),
+ this.composerAutocompleteProvider = new CombinedAutocompleteProvider(
+ this.buildSlashCommands(),
+ process.cwd(),
+ resolveFdBinary(),
);
+ this.editor.setAutocompleteProvider(this.composerAutocompleteProvider);
this.editor.onChange = () => {
+ this.syncComposerAttachmentsFromEditor();
this.tui.requestRender();
};
this.editor.onSubmit = (value) => {
@@ -151,6 +494,10 @@ export class AppScreen implements Component, Focusable {
clearTimeout(this.transientNoticeTimer);
this.transientNoticeTimer = null;
}
+ if (this.animationTimer) {
+ clearInterval(this.animationTimer);
+ this.animationTimer = null;
+ }
this.unsubscribe();
}
@@ -159,8 +506,21 @@ export class AppScreen implements Component, Focusable {
}
handleInput(data: string): void {
+ const snapshot = this.state.getSnapshot();
+ const pendingQuestion = snapshot.pendingQuestion;
+ const activeQuestion =
+ pendingQuestion?.questions[this.activeQuestionIndex] ?? pendingQuestion?.questions[0];
+ const permissionRequest = activeQuestion
+ ? isPermissionRequest(pendingQuestion?.source, activeQuestion.question)
+ : false;
+
+ if (!pendingQuestion && snapshot.isProcessing && matchesKey(data, "escape")) {
+ this.state.cancel();
+ return;
+ }
+
const handled = handleAppScreenKeyInput(data, {
- getSnapshot: () => this.state.getSnapshot(),
+ getSnapshot: () => snapshot,
cancel: () => this.state.cancel(),
requestExit: () => {
const now = Date.now();
@@ -180,16 +540,32 @@ export class AppScreen implements Component, Focusable {
}, 1500);
this.tui.requestRender();
},
- toggleThinking: () => {
- this.showFullThinking = !this.showFullThinking;
+ toggleTodos: () => {
+ this.showTodos = !this.showTodos;
this.tui.requestRender();
},
- toggleToolDetails: () => {
- this.showToolDetails = !this.showToolDetails;
+ toggleTeamPanel: () => {
+ this.showTeamPanel = !this.showTeamPanel;
this.tui.requestRender();
},
- toggleShortcutHelp: () => {
- this.showShortcutHelp = !this.showShortcutHelp;
+ toggleTranscript: () => {
+ const snapshot = this.state.getSnapshot();
+ this.state.setTranscriptMode(
+ snapshot.transcriptMode === "detailed" ? "compact" : "detailed",
+ );
+ },
+ redraw: () => {
+ this.tui.invalidate();
+ this.tui.requestRender(true);
+ this.transientNotice = "Screen redrawn";
+ if (this.transientNoticeTimer) {
+ clearTimeout(this.transientNoticeTimer);
+ }
+ this.transientNoticeTimer = setTimeout(() => {
+ this.transientNotice = null;
+ this.transientNoticeTimer = null;
+ this.tui.requestRender();
+ }, 1200);
this.tui.requestRender();
},
});
@@ -197,13 +573,68 @@ export class AppScreen implements Component, Focusable {
return;
}
- const snapshot = this.state.getSnapshot();
+ if (permissionRequest && activeQuestion) {
+ const lower = data.toLowerCase();
+ if (lower === "y") {
+ const allow = activeQuestion.options.find((option) => isAllowOption(option.label));
+ if (allow) {
+ this.handleQuestionSelection(allow.label);
+ return;
+ }
+ }
+ if (lower === "n") {
+ const reject = activeQuestion.options.find((option) => isRejectOption(option.label));
+ if (reject) {
+ this.handleQuestionSelection(reject.label);
+ return;
+ }
+ }
+ }
+
+ if (!snapshot.pendingQuestion && this.resumeSessionList !== null) {
+ this.resumeSessionList.list.handleInput(data);
+ this.tui.requestRender();
+ return;
+ }
+
+ if (!snapshot.pendingQuestion && this.showTeamPanel) {
+ if (matchesKey(data, "up")) {
+ this.moveTeamPanelSelection(snapshot, -1);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "down")) {
+ this.moveTeamPanelSelection(snapshot, 1);
+ this.tui.requestRender();
+ return;
+ }
+ }
+
if (snapshot.pendingQuestion && this.questionList !== null) {
this.questionList.handleInput(data);
this.tui.requestRender();
return;
}
+ if (
+ !snapshot.pendingQuestion &&
+ this.editor.getText().length === 0 &&
+ this.composerAttachments.length > 0
+ ) {
+ if (matchesKey(data, "backspace")) {
+ this.composerAttachments = this.composerAttachments.slice(0, -1);
+ this.tui.requestRender();
+ return;
+ }
+ }
+
+ if (!snapshot.pendingQuestion && matchesKey(data, "backspace")) {
+ if (this.deleteComposerAttachmentTokenBackwards()) {
+ this.tui.requestRender();
+ return;
+ }
+ }
+
this.editor.handleInput(data);
}
@@ -211,23 +642,39 @@ export class AppScreen implements Component, Focusable {
const snapshot = this.state.getSnapshot();
this.editor.borderColor = snapshot.pendingQuestion
? palette.border.question
- : palette.border.active;
- const editorLines = this.applySlashCommandHint(this.editor.render(width), width);
- const questionLines = this.buildPendingQuestionLines(snapshot, width);
+ : palette.border.panel;
+ const editorLines = this.applyComposerTokenHighlight(
+ this.applySlashCommandHint(this.editor.render(width), width),
+ );
+ const composerPreviewLines: string[] = [];
+ const questionLines = [
+ ...this.buildResumeSessionListLines(width),
+ ...this.buildPendingQuestionLines(snapshot, width),
+ ];
return buildAppScreenLines(snapshot, {
width,
questionLines,
editorLines,
- showFullThinking: this.showFullThinking,
- showToolDetails: this.showToolDetails,
- showShortcutHelp: this.showShortcutHelp,
+ composerPreviewLines,
+ showFullThinking: snapshot.transcriptMode === "detailed",
+ showToolDetails: snapshot.transcriptMode === "detailed",
+ showShortcutHelp: false,
+ showTodos: this.showTodos,
+ showTeamPanel: this.showTeamPanel,
+ selectedTeamMemberId: this.selectedTeamMemberId,
transientNotice: this.transientNotice,
+ animationPhase: this.animationPhase,
+ runningElapsedMs:
+ snapshot.isProcessing && this.runningStartedAtMs !== null
+ ? Date.now() - this.runningStartedAtMs
+ : undefined,
});
}
private async handleSubmit(raw: string): Promise<void> {
const text = raw.trim();
- if (!text) return;
+ const content = this.composeOutgoingMessage(text);
+ if (!content) return;
const snapshot = this.state.getSnapshot();
if (snapshot.pendingQuestion) {
@@ -236,31 +683,47 @@ export class AppScreen implements Component, Focusable {
}
this.editor.addToHistory(text);
this.editor.setText("");
+ this.composerAttachments = [];
return;
}
if (text.startsWith("/")) {
+ if (/^\/(?:resume|continue)\s*$/.test(text)) {
+ this.editor.addToHistory(text);
+ this.editor.setText("");
+ this.composerAttachments = [];
+ await this.openResumeSessionList();
+ return;
+ }
await this.commands.execute(text, {
...this.state.getCommandContext(),
exitApp: this.exit,
});
this.editor.addToHistory(text);
this.editor.setText("");
+ this.composerAttachments = [];
return;
}
- if (snapshot.isProcessing) {
- this.state.addItem({
- kind: "error",
- id: `busy-${Date.now()}`,
- sessionId: snapshot.sessionId,
- content: "session is busy, run /cancel first",
- at: new Date().toISOString(),
- });
+ if (snapshot.isProcessing || snapshot.isPaused) {
+ const requestId = this.state.supplement(content);
+ if (!requestId) {
+ this.state.addItem({
+ kind: "error",
+ id: `offline-${Date.now()}`,
+ sessionId: snapshot.sessionId,
+ content: "offline: waiting for reconnect",
+ at: new Date().toISOString(),
+ });
+ return;
+ }
+ this.editor.addToHistory(text);
+ this.editor.setText("");
+ this.composerAttachments = [];
return;
}
- const requestId = this.state.sendMessage(text);
+ const requestId = this.state.sendMessage(content);
if (!requestId) {
this.state.addItem({
kind: "error",
@@ -274,6 +737,7 @@ export class AppScreen implements Component, Focusable {
this.editor.addToHistory(text);
this.editor.setText("");
+ this.composerAttachments = [];
}
private handleStateChange(): void {
@@ -284,7 +748,9 @@ export class AppScreen implements Component, Focusable {
this.activeQuestionIndex = 0;
this.pendingQuestionAnswers.clear();
this.draftBeforeQuestion = this.editor.getText();
+ this.draftAttachmentsBeforeQuestion = [...this.composerAttachments];
this.editor.setText("");
+ this.composerAttachments = [];
this.syncQuestionList(snapshot);
} else if (questionId && this.activeQuestionId) {
this.syncQuestionList(snapshot);
@@ -297,10 +763,204 @@ export class AppScreen implements Component, Focusable {
this.editor.setText(this.draftBeforeQuestion);
}
this.draftBeforeQuestion = "";
+ this.composerAttachments = [...this.draftAttachmentsBeforeQuestion];
+ this.draftAttachmentsBeforeQuestion = [];
+ }
+ this.syncTeamPanelSelection(snapshot);
+ this.syncAnimationLoop(snapshot);
+ this.tui.requestRender();
+ }
+
+ private syncTeamPanelSelection(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {
+ const memberIds = orderedMemberIds(snapshot.teamMemberEvents, snapshot.teamMessageEvents);
+ if (memberIds.length === 0) {
+ this.selectedTeamMemberId = null;
+ return;
+ }
+ if (!this.selectedTeamMemberId || !memberIds.includes(this.selectedTeamMemberId)) {
+ this.selectedTeamMemberId = memberIds[0] ?? null;
+ }
+ }
+
+ private moveTeamPanelSelection(
+ snapshot: ReturnType<CliPiAppState["getSnapshot"]>,
+ delta: -1 | 1,
+ ): void {
+ const memberIds = orderedMemberIds(snapshot.teamMemberEvents, snapshot.teamMessageEvents);
+ if (memberIds.length === 0) {
+ this.selectedTeamMemberId = null;
+ return;
+ }
+ const currentIndex = this.selectedTeamMemberId
+ ? memberIds.indexOf(this.selectedTeamMemberId)
+ : 0;
+ const baseIndex = currentIndex >= 0 ? currentIndex : 0;
+ const nextIndex = Math.max(0, Math.min(memberIds.length - 1, baseIndex + delta));
+ this.selectedTeamMemberId = memberIds[nextIndex] ?? memberIds[0] ?? null;
+ }
+
+ private async openResumeSessionList(): Promise<void> {
+ const snapshot = this.state.getSnapshot();
+ try {
+ const payload = await this.state.request<SessionListPayload>("session.list", {});
+ const sessions = payload.sessions ?? [];
+ const total = payload.total ?? sessions.length;
+ if (sessions.length === 0) {
+ this.resumeSessionList = null;
+ this.state.addItem(addInfo(snapshot.sessionId, "No sessions found", "r"));
+ return;
+ }
+
+ const items = buildResumeSessionItems(sessions);
+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 8), selectListTheme, {
+ minPrimaryColumnWidth: 24,
+ maxPrimaryColumnWidth: 42,
+ });
+ list.onSelect = (item) => {
+ void this.handleResumeSessionSelection(item.value);
+ };
+ list.onCancel = () => {
+ this.resumeSessionList = null;
+ this.tui.requestRender();
+ };
+ this.resumeSessionList = { list, sessions, total };
+ this.tui.requestRender();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.resumeSessionList = null;
+ this.state.addItem(addError(snapshot.sessionId, `resume failed: ${message}`));
+ }
+ }
+
+ private async handleResumeSessionSelection(sessionId: string): Promise<void> {
+ const nextSessionId = sessionId.trim();
+ if (!nextSessionId) {
+ return;
}
+ this.resumeSessionList = null;
+ this.state.updateSession(nextSessionId);
+ this.state.clearEntries();
+ await this.state.restoreHistory(nextSessionId);
this.tui.requestRender();
}
+ private buildResumeSessionListLines(width: number): string[] {
+ if (!this.resumeSessionList) {
+ return [];
+ }
+ return [
+ padToWidth(
+ palette.status.warning(`Resume session (${this.resumeSessionList.total} total)`),
+ width,
+ ),
+ ...this.resumeSessionList.list.render(width),
+ padToWidth(palette.text.dim("↑/↓ choose · Enter resume · Esc cancel"), width),
+ ];
+ }
+
+ private syncComposerAttachmentsFromEditor(): void {
+ if (this.syncingComposerInput) {
+ return;
+ }
+
+ const originalText = this.editor.getText();
+ const { normalizedText, attachments } = syncComposerImageTokens(
+ originalText,
+ this.composerAttachments,
+ (path) => this.isComposerImageFile(path),
+ );
+
+ this.composerAttachments = attachments;
+
+ if (normalizedText !== originalText) {
+ this.syncingComposerInput = true;
+ this.editor.setText(normalizedText);
+ this.syncingComposerInput = false;
+ }
+ }
+
+ private deleteComposerAttachmentTokenBackwards(): boolean {
+ const cursor = this.editor.getCursor();
+ const lines = this.editor.getLines();
+ const currentLine = lines[cursor.line] ?? "";
+ const tokenRange = findAttachmentTokenAtCursor(currentLine, cursor.col);
+ if (!tokenRange) {
+ return false;
+ }
+
+ const nextLine =
+ `${currentLine.slice(0, tokenRange.start)}${currentLine.slice(tokenRange.end)}`.replace(
+ / {2,}/g,
+ " ",
+ );
+ const nextLines = [...lines];
+ nextLines[cursor.line] = nextLine;
+ const nextText = nextLines.join("\n");
+ const nextCol = Math.min(tokenRange.start, nextLine.length);
+
+ this.syncingComposerInput = true;
+ this.editor.setText(nextText);
+ const editorState = this.editor as unknown as {
+ state?: { cursorLine: number; cursorCol: number };
+ };
+ if (editorState.state) {
+ editorState.state.cursorLine = cursor.line;
+ editorState.state.cursorCol = nextCol;
+ }
+ this.syncingComposerInput = false;
+ this.syncComposerAttachmentsFromEditor();
+ return true;
+ }
+
+ private composeOutgoingMessage(text: string): string {
+ return expandComposerImageTokens(text, this.composerAttachments)
+ .replace(/[ \t]{2,}/g, " ")
+ .replace(/[ \t]+\n/g, "\n")
+ .trim();
+ }
+
+ private isComposerImageFile(path: string): boolean {
+ if (!looksLikeImagePath(path)) {
+ return false;
+ }
+
+ try {
+ const stats = statSync(path);
+ if (!stats.isFile()) {
+ return false;
+ }
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ private syncAnimationLoop(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {
+ const hasRunningTools = snapshot.toolExecutions.some(
+ (execution) => execution.tool.status === "running",
+ );
+ const shouldAnimate = snapshot.isProcessing || hasRunningTools;
+ if (!shouldAnimate) {
+ if (this.animationTimer) {
+ clearInterval(this.animationTimer);
+ this.animationTimer = null;
+ }
+ this.animationPhase = 0;
+ this.runningStartedAtMs = null;
+ return;
+ }
+ if (snapshot.isProcessing && this.runningStartedAtMs === null) {
+ this.runningStartedAtMs = Date.now();
+ }
+ if (this.animationTimer) {
+ return;
+ }
+ this.animationTimer = setInterval(() => {
+ this.animationPhase = (this.animationPhase + 1) % 12;
+ this.tui.requestRender();
+ }, 220);
+ }
+
private applySlashCommandHint(editorLines: string[], width: number): string[] {
const hint = this.getInlineSlashCommandHint();
if (!hint || editorLines.length < 3) {
@@ -324,6 +984,12 @@ export class AppScreen implements Component, Focusable {
return nextLines;
}
+ private applyComposerTokenHighlight(editorLines: string[]): string[] {
+ return editorLines.map((line) =>
+ line.replace(COMPOSER_ATTACHMENT_TOKEN_RE, (token) => palette.text.info(token)),
+ );
+ }
+
private getInlineSlashCommandHint(): string | null {
const text = this.editor.getText();
if (!text.startsWith("/") || text.includes("\n")) {
@@ -390,27 +1056,8 @@ export class AppScreen implements Component, Focusable {
if (permissionRequest) {
const summary = parsePermissionSummary(question.question);
- lines.push(
- padToWidth(
- palette.status.warning(
- `Permission${progress ? ` ${this.activeQuestionIndex + 1}/${total}` : ""}`,
- ),
- width,
- ),
- );
- if (summary.tool) {
- lines.push(padToWidth(palette.text.assistant(`${summary.tool} wants to run`), width));
- }
- const primaryDetail = summary.command ?? summary.description ?? summary.reason;
- if (primaryDetail) {
- lines.push(
- ...wrapPlainText(primaryDetail, width)
- .slice(0, 2)
- .map((line) =>
- padToWidth(summary.command ? palette.text.tool(line) : palette.text.dim(line), width),
- ),
- );
- }
+ const title = progress ? `Permission ${this.activeQuestionIndex + 1}/${total}` : "Permission";
+ lines.push(...renderPermissionBlock(width, summary, title));
} else {
lines.push(
...wrapPlainText(
@@ -421,21 +1068,18 @@ export class AppScreen implements Component, Focusable {
}
if (this.questionList !== null) {
- lines.push(" ".repeat(width));
lines.push(...this.questionList.render(width));
lines.push(
padToWidth(
palette.text.dim(
permissionRequest
- ? "Use ↑/↓ to review options, Enter to approve, Esc to reject"
- : "Use ↑/↓ to choose, Enter to confirm, Esc to reject",
+ ? "↑/↓ review · Enter confirm · Esc reject"
+ : "↑/↓ choose · Enter confirm · Esc reject",
),
width,
),
);
}
-
- lines.push(" ".repeat(width));
return lines;
}
@@ -454,10 +1098,18 @@ export class AppScreen implements Component, Focusable {
const items: SelectItem[] = question.options.map((option) => ({
value: option.label,
- label: option.label,
+ label:
+ pendingQuestion.source === "permission"
+ ? normalizePermissionOptionLabel(option.label)
+ : option.label,
description: option.description,
}));
- const list = new SelectList(items, Math.min(Math.max(items.length, 1), 6), selectListTheme);
+ const maxVisible = pendingQuestion.source === "permission" ? 4 : 6;
+ const list = new SelectList(
+ items,
+ Math.min(Math.max(items.length, 1), maxVisible),
+ selectListTheme,
+ );
list.onSelect = (item) => {
this.handleQuestionSelection(item.value);
};
diff --git a/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts b/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts
index a6c94762a8..b18d9c403e 100644
--- a/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts
+++ b/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts
@@ -1,174 +1,12 @@
-import { truncateToWidth, type Component } from "@mariozechner/pi-tui";
-import type { HistoryItem } from "../../../core/types.js";
-import { chalk, palette } from "../../theme.js";
-import {
- prefixedLines,
- renderMarkdownLines,
- renderStyledMarkdownLines,
- renderWrappedText,
- summarize,
-} from "../../rendering/text.js";
-import { summarizeToolResultByKind } from "../tools/index.js";
-
-export class UserMessageComponent implements Component {
- constructor(private readonly entry: Extract<HistoryItem, { kind: "user" }>) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- const lines = renderStyledMarkdownLines(
- Math.max(1, width - 2),
- this.entry.content,
- {
- bgColor: palette.surface.user,
- color: (value: string) => value,
- },
- 1,
- 1,
- );
- return prefixedLines(lines, width, "> ", palette.text.user, "│ ");
- }
-}
-
-export class AssistantMessageComponent implements Component {
- constructor(private readonly entry: Extract<HistoryItem, { kind: "assistant" }>) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- const body = this.entry.content.trim();
- if (!body) {
- return [];
- }
- const lines = renderMarkdownLines(width, body, 0, 0);
- if (this.entry.streaming && lines.length > 0) {
- const lastIndex = lines.length - 1;
- lines[lastIndex] = truncateToWidth(
- lines[lastIndex] + palette.status.warning(" …"),
- Math.max(1, width),
- );
- }
- return lines;
- }
-}
-
-export class ThinkingMessageComponent implements Component {
- constructor(
- private readonly entry: Extract<HistoryItem, { kind: "thinking" }>,
- private readonly expanded: boolean,
- ) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- if (!this.expanded) {
- return renderWrappedText(width, "thinking", (value) =>
- chalk.italic(palette.text.thinking(value)),
- );
- }
- const lines = renderWrappedText(width, "thinking", (value) =>
- chalk.italic(palette.text.thinking(value)),
- );
- const wrapped = renderStyledMarkdownLines(
- Math.max(1, width - 2),
- this.entry.content,
- {
- color: palette.text.dim,
- italic: true,
- },
- 0,
- 0,
- );
- return [...lines, ...prefixedLines(wrapped, width, "│ ", palette.text.dim, "│ ")];
- }
-}
-
-export class SystemMessageComponent implements Component {
- constructor(private readonly entry: Extract<HistoryItem, { kind: "system" }>) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- return renderWrappedText(width, `· ${this.entry.content}`, palette.text.system);
- }
-}
-
-export class ErrorMessageComponent implements Component {
- constructor(private readonly entry: Extract<HistoryItem, { kind: "error" }>) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- return prefixedLines(
- renderWrappedText(Math.max(1, width - 2), this.entry.content, palette.status.error),
- width,
- "! ",
- palette.status.error,
- " ",
- );
- }
-}
-
-export class InfoMessageComponent implements Component {
- constructor(private readonly entry: Extract<HistoryItem, { kind: "info" }>) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- const meta = this.entry.meta;
- const lines: string[] = [];
- const innerWidth = Math.max(1, width);
- const title = meta?.title ?? this.entry.content;
- lines.push(...renderWrappedText(innerWidth, `· ${title}`, palette.text.info));
- for (const item of meta?.items ?? []) {
- const value = item.value ? `: ${item.value}` : "";
- lines.push(
- ...renderWrappedText(innerWidth, ` ${item.label}${value}`, palette.text.assistant),
- );
- if (item.description) {
- lines.push(...renderWrappedText(innerWidth, ` ${item.description}`, palette.text.dim));
- }
- }
- return lines;
- }
-}
-
-export class CompactMessageComponent implements Component {
- constructor(private readonly entry: HistoryItem) {}
-
- invalidate(): void {}
-
- render(width: number): string[] {
- if (this.entry.kind === "tool_group") {
- const lastTool = this.entry.tools[this.entry.tools.length - 1];
- const summary = lastTool
- ? `${lastTool.name}${lastTool.result ? ` - ${lastTool.summary ?? summarizeToolResultByKind(lastTool.name, lastTool.result) ?? summarize(lastTool.result, 72)}` : ""}`
- : "tool activity";
- return renderWrappedText(width, `[tool] ${summary}`, palette.text.dim);
- }
-
- const content =
- this.entry.kind === "assistant" || this.entry.kind === "thinking"
- ? summarize(this.entry.content, 120)
- : this.entry.content;
- const prefix =
- this.entry.kind === "assistant" || this.entry.kind === "thinking"
- ? ""
- : this.entry.kind === "user"
- ? "> "
- : this.entry.kind === "error"
- ? "! "
- : "· ";
- const color =
- this.entry.kind === "error"
- ? palette.status.error
- : this.entry.kind === "assistant"
- ? palette.text.assistant
- : this.entry.kind === "user"
- ? palette.text.user
- : this.entry.kind === "thinking"
- ? palette.text.thinking
- : palette.text.dim;
- return renderWrappedText(width, `${prefix}${content}`, color);
- }
-}
+export {
+ AssistantMessageComponent,
+ CompactAssistantMessageComponent,
+ ThinkingMessageComponent,
+ UserMessageComponent,
+} from "./content-components.js";
+export {
+ CompactMessageComponent,
+ ErrorMessageComponent,
+ InfoMessageComponent,
+ SystemMessageComponent,
+} from "./meta-components.js";
diff --git a/jiuwenclaw/cli/src/ui/components/messages/content-components.ts b/jiuwenclaw/cli/src/ui/components/messages/content-components.ts
new file mode 100644
index 0000000000..0ed1e2aa01
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/content-components.ts
@@ -0,0 +1,145 @@
+import { truncateToWidth, type Component } from "@mariozechner/pi-tui";
+import type { HistoryItem } from "../../../core/types.js";
+import { chalk, palette } from "../../theme.js";
+import {
+ padToWidth,
+ prefixedLines,
+ renderStyledMarkdownLines,
+ renderWrappedText,
+} from "../../rendering/text.js";
+import { renderMediaItems } from "./shared.js";
+
+function renderAssistantLines(
+ entry: Extract<HistoryItem, { kind: "assistant" }>,
+ width: number,
+): string[] {
+ const body = entry.content.trim();
+ if (!body && (!entry.mediaItems || entry.mediaItems.length === 0)) {
+ return [];
+ }
+ const lines = body
+ ? renderStyledMarkdownLines(
+ width,
+ body,
+ {
+ color: palette.text.assistant,
+ },
+ 0,
+ 0,
+ )
+ : [];
+ if (entry.streaming && lines.length > 0) {
+ const lastIndex = lines.length - 1;
+ lines[lastIndex] = truncateToWidth(lines[lastIndex], Math.max(1, width));
+ }
+ if (entry.mediaItems?.length) {
+ lines.push(...renderMediaItems(width, entry.mediaItems));
+ }
+ return lines;
+}
+
+function renderThinkingLabel(active: boolean, animationPhase: number, width: number): string[] {
+ const label = "thinking";
+ if (!active) {
+ return [padToWidth(chalk.italic(palette.text.dim(label)), width)];
+ }
+
+ const focus = animationPhase % (label.length + 2) - 1;
+ const animated = label
+ .split("")
+ .map((char, index) => {
+ const distance = Math.abs(index - focus);
+ if (distance === 0) return palette.text.thinking(char);
+ if (distance === 1) return palette.text.dim(char);
+ return palette.text.subtle(char);
+ })
+ .join("");
+
+ return [padToWidth(chalk.italic(animated), width)];
+}
+
+export class UserMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "user" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ const lines = renderStyledMarkdownLines(
+ Math.max(1, width - 2),
+ this.entry.content,
+ {
+ color: palette.text.dim,
+ },
+ 0,
+ 0,
+ );
+ return prefixedLines(lines, width, "> ", palette.text.user, " ");
+ }
+}
+
+export class AssistantMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "assistant" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ return renderAssistantLines(this.entry, width);
+ }
+}
+
+export class CompactAssistantMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "assistant" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ return renderAssistantLines(this.entry, width);
+ }
+}
+
+export class ThinkingMessageComponent implements Component {
+ constructor(
+ private readonly entry: Extract<HistoryItem, { kind: "thinking" }>,
+ private readonly expanded: boolean,
+ private readonly active: boolean,
+ private readonly animationPhase: number,
+ ) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ if (!this.expanded) {
+ return renderThinkingLabel(this.active, this.animationPhase, width);
+ }
+ const lines = renderThinkingLabel(this.active, this.animationPhase, width);
+ const wrapped = renderStyledMarkdownLines(
+ Math.max(1, width - 2),
+ this.entry.content,
+ {
+ color: palette.text.subtle,
+ italic: true,
+ },
+ 0,
+ 0,
+ );
+ const previewLimit = 4;
+ const preview = wrapped.slice(-previewLimit);
+ const rendered = [...lines, ...prefixedLines(preview, width, "│ ", palette.text.subtle, "│ ")];
+ if (wrapped.length > preview.length) {
+ rendered.push(
+ ...prefixedLines(
+ renderWrappedText(
+ Math.max(1, width - 2),
+ `+ ${wrapped.length - preview.length} earlier lines`,
+ palette.text.dim,
+ ),
+ width,
+ "│ ",
+ palette.text.subtle,
+ "│ ",
+ ),
+ );
+ }
+ return rendered;
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts b/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts
index d0a609e74d..f417d7ad06 100644
--- a/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts
+++ b/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts
@@ -1,49 +1,15 @@
import type { HistoryItem } from "../../../core/types.js";
-import {
- AssistantMessageComponent,
- CompactMessageComponent,
- ErrorMessageComponent,
- InfoMessageComponent,
- SystemMessageComponent,
- ThinkingMessageComponent,
- UserMessageComponent,
-} from "./basic-message-components.js";
-import { ToolGroupMessageComponent } from "../tools/index.js";
-
-export interface MessageRenderOptions {
- compact: boolean;
- collapsed: boolean;
- thinkingExpanded: boolean;
- toolDetailsExpanded: boolean;
-}
+import { renderCompactEntry } from "./render-compact-entry.js";
+import { renderDetailedEntry } from "./render-detailed-entry.js";
+import type { MessageRenderOptions, RenderedHistoryEntry } from "./types.js";
export function renderHistoryEntry(
entry: HistoryItem,
width: number,
options: MessageRenderOptions,
-): string[] {
+): RenderedHistoryEntry {
if (options.compact) {
- return new CompactMessageComponent(entry).render(width);
- }
-
- switch (entry.kind) {
- case "user":
- return new UserMessageComponent(entry).render(width);
- case "assistant":
- return new AssistantMessageComponent(entry).render(width);
- case "thinking":
- return new ThinkingMessageComponent(entry, options.thinkingExpanded).render(width);
- case "tool_group":
- return new ToolGroupMessageComponent(
- entry,
- options.collapsed,
- options.toolDetailsExpanded,
- ).render(width);
- case "system":
- return new SystemMessageComponent(entry).render(width);
- case "error":
- return new ErrorMessageComponent(entry).render(width);
- case "info":
- return new InfoMessageComponent(entry).render(width);
+ return renderCompactEntry(entry, width, options);
}
+ return renderDetailedEntry(entry, width, options);
}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/index.ts b/jiuwenclaw/cli/src/ui/components/messages/index.ts
index b14eeb73bb..75c1990045 100644
--- a/jiuwenclaw/cli/src/ui/components/messages/index.ts
+++ b/jiuwenclaw/cli/src/ui/components/messages/index.ts
@@ -8,4 +8,4 @@ export {
UserMessageComponent,
} from "./basic-message-components.js";
export { renderHistoryEntry } from "./history-entry.js";
-export type { MessageRenderOptions } from "./history-entry.js";
+export type { MessageRenderOptions } from "./types.js";
diff --git a/jiuwenclaw/cli/src/ui/components/messages/meta-components.ts b/jiuwenclaw/cli/src/ui/components/messages/meta-components.ts
new file mode 100644
index 0000000000..3d46ae2220
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/meta-components.ts
@@ -0,0 +1,108 @@
+import type { Component } from "@mariozechner/pi-tui";
+import type { HistoryItem } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { prefixedLines, renderWrappedText, summarize } from "../../rendering/text.js";
+import { renderClaudeResponseLines, renderMediaItems } from "./shared.js";
+
+export class SystemMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "system" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ return renderWrappedText(width, `· ${this.entry.content}`, palette.text.system);
+ }
+}
+
+export class ErrorMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "error" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ return prefixedLines(
+ renderWrappedText(Math.max(1, width - 2), this.entry.content, palette.status.error),
+ width,
+ "! ",
+ palette.status.error,
+ " ",
+ );
+ }
+}
+
+export class InfoMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "info" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ const meta = this.entry.meta;
+ const lines: string[] = [];
+ const innerWidth = Math.max(1, width);
+ const title = meta?.title ?? this.entry.content;
+ lines.push(...renderWrappedText(innerWidth, `· ${title}`, palette.text.info));
+ if (this.entry.mediaItems?.length) {
+ lines.push(...renderMediaItems(width, this.entry.mediaItems));
+ }
+ for (const item of meta?.items ?? []) {
+ const value = item.value ? `: ${item.value}` : "";
+ lines.push(
+ ...renderClaudeResponseLines(
+ width,
+ renderWrappedText(
+ Math.max(1, width - 4),
+ `${item.label}${value}`,
+ palette.text.assistant,
+ ),
+ palette.text.assistant,
+ ),
+ );
+ if (item.description) {
+ lines.push(
+ ...renderClaudeResponseLines(
+ width,
+ renderWrappedText(Math.max(1, width - 4), item.description, palette.text.dim),
+ palette.text.dim,
+ ),
+ );
+ }
+ }
+ return lines;
+ }
+}
+
+export class CompactMessageComponent implements Component {
+ constructor(
+ private readonly entry: Exclude<HistoryItem, { kind: "tool_group" | "collapsed_tool_group" }>,
+ ) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ const content =
+ this.entry.kind === "assistant" || this.entry.kind === "thinking"
+ ? summarize(this.entry.content, 120)
+ : this.entry.content;
+ const prefix =
+ this.entry.kind === "assistant"
+ ? "• "
+ : this.entry.kind === "thinking"
+ ? "· "
+ : this.entry.kind === "user"
+ ? "> "
+ : this.entry.kind === "error"
+ ? "! "
+ : "· ";
+ const color =
+ this.entry.kind === "error"
+ ? palette.status.error
+ : this.entry.kind === "assistant"
+ ? palette.text.assistant
+ : this.entry.kind === "user"
+ ? palette.text.user
+ : this.entry.kind === "thinking"
+ ? palette.text.thinking
+ : palette.text.dim;
+ return renderWrappedText(width, `${prefix}${content}`, color);
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/presentation-rules.ts b/jiuwenclaw/cli/src/ui/components/messages/presentation-rules.ts
new file mode 100644
index 0000000000..11a245639e
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/presentation-rules.ts
@@ -0,0 +1,51 @@
+import type { HistoryItem } from "../../../core/types.js";
+
+const COMPACT_EXPANDED_TOOL_NAMES = new Set([
+ "write",
+ "write_file",
+ "write_text_file",
+ "write_memory",
+ "edit",
+ "edit_file",
+ "edit_memory",
+ "search_replace",
+]);
+
+export function shouldExpandCompactToolGroup(
+ entry: Extract<HistoryItem, { kind: "tool_group" }>,
+): boolean {
+ return entry.tools.some((tool) =>
+ COMPACT_EXPANDED_TOOL_NAMES.has(tool.name.trim().toLowerCase()),
+ );
+}
+
+export function shouldGapAfterEntry(entry: HistoryItem, compact: boolean): boolean {
+ switch (entry.kind) {
+ case "user":
+ case "assistant":
+ case "error":
+ return true;
+ case "tool_group":
+ case "collapsed_tool_group":
+ return true;
+ case "thinking":
+ return !compact;
+ case "system":
+ case "info":
+ return false;
+ }
+}
+
+export function shouldEmphasizeAssistantTransition(
+ entry: HistoryItem,
+ nextEntry: HistoryItem | undefined,
+ compact: boolean,
+): boolean {
+ if (!nextEntry || nextEntry.kind !== "assistant") {
+ return false;
+ }
+ if (entry.kind === "thinking") {
+ return !compact;
+ }
+ return entry.kind === "tool_group" || entry.kind === "collapsed_tool_group";
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts b/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts
new file mode 100644
index 0000000000..cfa664b45b
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts
@@ -0,0 +1,53 @@
+import type { HistoryItem } from "../../../core/types.js";
+import {
+ CompactAssistantMessageComponent,
+ CompactMessageComponent,
+ UserMessageComponent,
+} from "./basic-message-components.js";
+import { CollapsedToolGroupMessageComponent, ToolGroupMessageComponent } from "../tools/index.js";
+import type { MessageRenderOptions, RenderedHistoryEntry } from "./types.js";
+import { shouldExpandCompactToolGroup, shouldGapAfterEntry } from "./presentation-rules.js";
+
+export function renderCompactEntry(
+ entry: HistoryItem,
+ width: number,
+ options: MessageRenderOptions,
+): RenderedHistoryEntry {
+ switch (entry.kind) {
+ case "user":
+ return {
+ lines: new UserMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, true),
+ };
+ case "assistant":
+ return {
+ lines: new CompactAssistantMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, true),
+ };
+ case "tool_group":
+ return {
+ lines: new ToolGroupMessageComponent(
+ entry,
+ false,
+ shouldExpandCompactToolGroup(entry),
+ options.animationPhase,
+ ).render(width),
+ gapAfter: shouldGapAfterEntry(entry, true),
+ };
+ case "collapsed_tool_group":
+ return {
+ lines: new CollapsedToolGroupMessageComponent(
+ entry,
+ true,
+ false,
+ options.animationPhase,
+ ).render(width),
+ gapAfter: shouldGapAfterEntry(entry, true),
+ };
+ default:
+ return {
+ lines: new CompactMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, true),
+ };
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/render-detailed-entry.ts b/jiuwenclaw/cli/src/ui/components/messages/render-detailed-entry.ts
new file mode 100644
index 0000000000..069fd6a9c4
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/render-detailed-entry.ts
@@ -0,0 +1,76 @@
+import type { HistoryItem } from "../../../core/types.js";
+import {
+ AssistantMessageComponent,
+ ErrorMessageComponent,
+ InfoMessageComponent,
+ SystemMessageComponent,
+ ThinkingMessageComponent,
+ UserMessageComponent,
+} from "./basic-message-components.js";
+import { CollapsedToolGroupMessageComponent, ToolGroupMessageComponent } from "../tools/index.js";
+import type { MessageRenderOptions, RenderedHistoryEntry } from "./types.js";
+import { shouldGapAfterEntry } from "./presentation-rules.js";
+
+export function renderDetailedEntry(
+ entry: HistoryItem,
+ width: number,
+ options: MessageRenderOptions,
+): RenderedHistoryEntry {
+ switch (entry.kind) {
+ case "user":
+ return {
+ lines: new UserMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "assistant":
+ return {
+ lines: new AssistantMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "thinking":
+ return {
+ lines: new ThinkingMessageComponent(
+ entry,
+ options.thinkingExpanded,
+ options.activeThinkingId === entry.id,
+ options.animationPhase,
+ ).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "tool_group":
+ return {
+ lines: new ToolGroupMessageComponent(
+ entry,
+ options.collapsed,
+ options.toolDetailsExpanded,
+ options.animationPhase,
+ ).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "collapsed_tool_group":
+ return {
+ lines: new CollapsedToolGroupMessageComponent(
+ entry,
+ options.collapsed,
+ options.toolDetailsExpanded,
+ options.animationPhase,
+ ).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "system":
+ return {
+ lines: new SystemMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "error":
+ return {
+ lines: new ErrorMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ case "info":
+ return {
+ lines: new InfoMessageComponent(entry).render(width),
+ gapAfter: shouldGapAfterEntry(entry, false),
+ };
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/shared.ts b/jiuwenclaw/cli/src/ui/components/messages/shared.ts
new file mode 100644
index 0000000000..18346cb251
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/shared.ts
@@ -0,0 +1,46 @@
+import { Image as TuiImage } from "@mariozechner/pi-tui";
+import type { MediaItem } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { prefixedLines, renderWrappedText, summarize } from "../../rendering/text.js";
+
+export function renderClaudeResponseLines(
+ width: number,
+ lines: string[],
+ colorFn: (value: string) => string,
+): string[] {
+ return prefixedLines(lines, width, " ⎿ ", palette.text.subtle, " ").map((line, index) =>
+ index === 0 ? line : colorFn(line),
+ );
+}
+
+export function renderMediaItems(width: number, items: MediaItem[]): string[] {
+ const lines: string[] = [];
+ for (const item of items) {
+ const kind =
+ item.type === "image"
+ ? "Image"
+ : item.type === "audio"
+ ? "Audio"
+ : item.type === "video"
+ ? "Video"
+ : "File";
+ const label = `${kind}: ${item.filename}${item.url ? ` (${summarize(item.url, 72)})` : ""}`;
+ lines.push(
+ ...renderClaudeResponseLines(
+ width,
+ renderWrappedText(Math.max(1, width - 4), label, palette.text.dim),
+ palette.text.dim,
+ ),
+ );
+ if (item.type === "image" && item.base64Data) {
+ const image = new TuiImage(
+ item.base64Data,
+ item.mimeType,
+ { fallbackColor: palette.text.dim },
+ { maxWidthCells: Math.max(16, Math.min(72, width - 4)), filename: item.filename },
+ );
+ lines.push(...image.render(width));
+ }
+ }
+ return lines;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/types.ts b/jiuwenclaw/cli/src/ui/components/messages/types.ts
new file mode 100644
index 0000000000..e22f4d2e28
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/types.ts
@@ -0,0 +1,13 @@
+export interface MessageRenderOptions {
+ compact: boolean;
+ collapsed: boolean;
+ thinkingExpanded: boolean;
+ activeThinkingId?: string;
+ toolDetailsExpanded: boolean;
+ animationPhase: number;
+}
+
+export interface RenderedHistoryEntry {
+ lines: string[];
+ gapAfter: boolean;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/team-panel.ts b/jiuwenclaw/cli/src/ui/components/team-panel.ts
new file mode 100644
index 0000000000..0bcd44e12d
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/team-panel.ts
@@ -0,0 +1,203 @@
+import type { TeamMemberEvent, TeamMessageEvent, TeamTaskEvent } from "../../core/types.js";
+import { padToWidth } from "../rendering/text.js";
+import { palette } from "../theme.js";
+import {
+ isLeaderMember,
+ isWorkingStatusLabel,
+ latestMemberSummaries,
+ messageEventLabel,
+ messagePreviewLabel,
+ memberStatusPhrase,
+ memberStatusTone,
+ taskEventLabel,
+ truncate,
+ type TeamMemberSummary,
+} from "./team-shared.js";
+
+function colorMemberLine(line: string, statusLabel: string): string {
+ switch (memberStatusTone(statusLabel)) {
+ case "active":
+ return palette.text.tool(line);
+ case "warning":
+ return palette.status.warning(line);
+ case "error":
+ return palette.status.error(line);
+ case "subtle":
+ return palette.text.subtle(line);
+ case "idle":
+ default:
+ return palette.text.dim(line);
+ }
+}
+
+function renderMemberTree(
+ members: TeamMemberSummary[],
+ taskEvents: TeamTaskEvent[],
+ messageEvents: TeamMessageEvent[],
+ width: number,
+ selectedMemberId: string | null,
+ maxVisibleTeammates = 6,
+): string[] {
+ const lines: string[] = [];
+ const leader = members.find((member) => isLeaderMember(member.memberId));
+ const teammates = members.filter((member) => !isLeaderMember(member.memberId));
+ const latestTask = taskEvents.at(-1);
+ const latestBroadcast = [...messageEvents].reverse().find((event) => !event.toMember);
+ const selectedTeammateIndex = selectedMemberId
+ ? teammates.findIndex((member) => member.memberId === selectedMemberId)
+ : -1;
+ const teammateOffset =
+ teammates.length <= maxVisibleTeammates || selectedTeammateIndex < 0
+ ? 0
+ : Math.max(
+ 0,
+ Math.min(
+ selectedTeammateIndex - Math.floor(maxVisibleTeammates / 2),
+ teammates.length - maxVisibleTeammates,
+ ),
+ );
+ const visibleTeammates =
+ teammates.length <= maxVisibleTeammates
+ ? teammates
+ : teammates.slice(teammateOffset, teammateOffset + maxVisibleTeammates);
+
+ if (leader) {
+ const leadPrimary = `team-lead · ${memberStatusPhrase(leader)}`;
+ lines.push(
+ padToWidth(
+ leader.memberId === selectedMemberId
+ ? palette.text.assistant(truncate(`› ${leadPrimary}`, width - 1))
+ : colorMemberLine(truncate(leadPrimary, width - 1), leader.statusLabel),
+ width,
+ ),
+ );
+ if (leader.preview) {
+ lines.push(
+ padToWidth(
+ palette.text.subtle(
+ `⎿ ${truncate(messagePreviewLabel(leader.preview.replace(/\s+/g, " "), leader.previewKind), Math.max(12, width - 4))}`,
+ ),
+ width,
+ ),
+ );
+ }
+ if (latestTask) {
+ lines.push(
+ padToWidth(
+ palette.text.subtle(`⎿ ${truncate(taskEventLabel(latestTask), Math.max(12, width - 4))}`),
+ width,
+ ),
+ );
+ } else if (latestBroadcast && latestBroadcast.content.trim()) {
+ lines.push(
+ padToWidth(
+ palette.text.subtle(
+ `⎿ ${truncate(latestBroadcast.content.replace(/\s+/g, " ").trim(), Math.max(12, width - 4))}`,
+ ),
+ width,
+ ),
+ );
+ }
+ if (teammates.length > 0) {
+ lines.push(" ".repeat(width));
+ }
+ }
+
+ if (teammateOffset > 0) {
+ lines.push(padToWidth(palette.text.subtle(`… ${teammateOffset} earlier teammates`), width));
+ }
+
+ for (const [index, member] of visibleTeammates.entries()) {
+ const isLast = teammateOffset + index === teammates.length - 1;
+ const branch = isLast ? "└─" : "├─";
+ const primary = `${branch} @${member.memberId} · ${memberStatusPhrase(member)}`;
+ lines.push(
+ padToWidth(
+ member.memberId === selectedMemberId
+ ? palette.text.assistant(truncate(`› ${primary}`, width - 1))
+ : colorMemberLine(truncate(primary, width - 1), member.statusLabel),
+ width,
+ ),
+ );
+ if (member.preview) {
+ const childPrefix = isLast ? " " : "│ ";
+ lines.push(
+ padToWidth(
+ palette.text.subtle(
+ `${childPrefix}⎿ ${truncate(messagePreviewLabel(member.preview.replace(/\s+/g, " "), member.previewKind), Math.max(12, width - 6))}`,
+ ),
+ width,
+ ),
+ );
+ }
+ }
+
+ const remainingTeammates = teammates.length - teammateOffset - visibleTeammates.length;
+ if (remainingTeammates > 0) {
+ lines.push(padToWidth(palette.text.subtle(`… ${remainingTeammates} more teammates`), width));
+ }
+ return lines;
+}
+
+export function renderTeamPanel(
+ memberEvents: TeamMemberEvent[],
+ taskEvents: TeamTaskEvent[],
+ messageEvents: TeamMessageEvent[],
+ width: number,
+ selectedMemberId: string | null,
+): string[] {
+ const members = latestMemberSummaries(memberEvents, messageEvents);
+ const lines: string[] = [];
+ const leader = members.find((member) => isLeaderMember(member.memberId));
+ const teammates = members.filter((member) => !isLeaderMember(member.memberId));
+ const workingCount = teammates.filter((member) =>
+ isWorkingStatusLabel(member.statusLabel),
+ ).length;
+ const latestMessage = messageEvents.at(-1);
+
+ lines.push(
+ padToWidth(
+ palette.text.secondary(
+ `Team · ${teammates.length} teammate${teammates.length === 1 ? "" : "s"}${workingCount > 0 ? ` · ${workingCount} working` : leader ? ` · ${memberStatusPhrase(leader)}` : ""}`,
+ ),
+ width,
+ ),
+ );
+
+ if (members.length > 0) {
+ lines.push(...renderMemberTree(members, taskEvents, messageEvents, width, selectedMemberId));
+ } else if (latestMessage) {
+ lines.push(
+ padToWidth(
+ palette.text.dim(
+ `⎿ ${truncate(messageEventLabel(latestMessage), Math.max(12, width - 2))}`,
+ ),
+ width,
+ ),
+ );
+ }
+
+ lines.push(padToWidth(palette.text.subtle("↑/↓ navigate"), width));
+ lines.push(" ".repeat(width));
+ return lines;
+}
+
+export function renderMiniTeamTree(
+ memberEvents: TeamMemberEvent[],
+ taskEvents: TeamTaskEvent[],
+ messageEvents: TeamMessageEvent[],
+ width: number,
+): string[] {
+ const members = latestMemberSummaries(memberEvents, messageEvents);
+ if (members.length === 0) {
+ return [];
+ }
+ return renderMemberTree(
+ members,
+ taskEvents,
+ messageEvents,
+ width,
+ null,
+ 2,
+ ).slice(0, 4);
+}
diff --git a/jiuwenclaw/cli/src/ui/components/team-shared.ts b/jiuwenclaw/cli/src/ui/components/team-shared.ts
new file mode 100644
index 0000000000..a6127b52a6
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/team-shared.ts
@@ -0,0 +1,169 @@
+import type { TeamMemberEvent, TeamMessageEvent, TeamTaskEvent } from "../../core/types.js";
+
+export type TeamMemberSummary = {
+ memberId: string;
+ statusLabel: string;
+ timestamp: number;
+ preview?: string;
+ previewKind?: "broadcast" | "p2p";
+};
+
+export function truncate(value: string, maxLength: number): string {
+ if (value.length <= maxLength) {
+ return value;
+ }
+ return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
+}
+
+export function formatElapsed(timestamp: number): string {
+ const diff = Math.max(0, Date.now() - timestamp);
+ const seconds = Math.floor(diff / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+ const hours = Math.floor(minutes / 60);
+ return `${hours}h`;
+}
+
+function normalizeStatusValue(value: string | undefined): string {
+ return value?.trim().toLowerCase() ?? "";
+}
+
+export function memberStatusLabel(event: TeamMemberEvent): string {
+ const type = normalizeStatusValue(event.type);
+ const oldStatus = normalizeStatusValue(event.oldStatus);
+ const nextStatus = normalizeStatusValue(event.newStatus);
+ const current = nextStatus || oldStatus;
+
+ if (type.endsWith(".spawned")) return "spawned";
+ if (type.endsWith(".restarted")) return "restarted";
+ if (type.endsWith(".shutdown")) return "shutdown";
+ if (type.endsWith(".execution_changed")) {
+ if (current.includes("exec") || current.includes("run")) return "working";
+ if (current.includes("idle")) return "idle";
+ }
+ if (type.endsWith(".status_changed")) {
+ if (current.includes("busy")) return "busy";
+ if (current.includes("wait")) return "waiting";
+ if (current.includes("block")) return "blocked";
+ if (current.includes("idle")) return "idle";
+ if (current.includes("active")) return "active";
+ }
+ if (current.includes("think")) return "thinking";
+ if (current.includes("exec")) return "working";
+ if (current.includes("run")) return "running";
+ if (current.includes("busy")) return "busy";
+ if (current.includes("idle")) return "idle";
+ if (current.includes("wait")) return "waiting";
+ if (current.includes("block")) return "blocked";
+ if (current.includes("error") || current.includes("fail")) return "error";
+ return current || "idle";
+}
+
+export function isWorkingStatusLabel(statusLabel: string): boolean {
+ const normalized = normalizeStatusValue(statusLabel);
+ return (
+ normalized === "working" ||
+ normalized === "running" ||
+ normalized === "busy" ||
+ normalized === "active" ||
+ normalized === "thinking"
+ );
+}
+
+export type TeamStatusTone = "active" | "idle" | "warning" | "error" | "subtle";
+
+export function memberStatusTone(statusLabel: string): TeamStatusTone {
+ const normalized = normalizeStatusValue(statusLabel);
+ if (normalized === "shutdown" || normalized === "error") return "error";
+ if (normalized === "waiting" || normalized === "blocked") return "warning";
+ if (normalized === "idle" || normalized === "spawned" || normalized === "restarted")
+ return "subtle";
+ if (isWorkingStatusLabel(normalized)) return "active";
+ return "idle";
+}
+
+export function isLeaderMember(memberId: string): boolean {
+ return /(^|[_-])leader($|[_-])/i.test(memberId) || /teamleader/i.test(memberId);
+}
+
+export function memberStatusPhrase(summary: TeamMemberSummary): string {
+ if (isWorkingStatusLabel(summary.statusLabel)) {
+ return summary.statusLabel;
+ }
+ if (summary.statusLabel === "idle") {
+ return `idle for ${formatElapsed(summary.timestamp)}`;
+ }
+ if (summary.statusLabel === "waiting" || summary.statusLabel === "blocked") {
+ return `${summary.statusLabel} for ${formatElapsed(summary.timestamp)}`;
+ }
+ if (summary.statusLabel === "spawned" || summary.statusLabel === "restarted") {
+ return `${summary.statusLabel} ${formatElapsed(summary.timestamp)} ago`;
+ }
+ return summary.statusLabel;
+}
+
+export function latestMemberSummaries(
+ memberEvents: TeamMemberEvent[],
+ messageEvents: TeamMessageEvent[],
+): TeamMemberSummary[] {
+ const latestMembers = new Map<string, TeamMemberEvent>();
+ for (const event of memberEvents) {
+ const previous = latestMembers.get(event.memberId);
+ if (!previous || event.timestamp >= previous.timestamp) {
+ latestMembers.set(event.memberId, event);
+ }
+ }
+ const latestMessages = new Map<string, TeamMessageEvent>();
+ for (const event of messageEvents) {
+ const previous = latestMessages.get(event.fromMember);
+ if (!previous || event.timestamp >= previous.timestamp) {
+ latestMessages.set(event.fromMember, event);
+ }
+ }
+ return [...latestMembers.values()]
+ .map((event) => ({
+ memberId: event.memberId,
+ statusLabel: memberStatusLabel(event),
+ timestamp: event.timestamp,
+ preview: latestMessages.get(event.memberId)?.content.trim() || undefined,
+ previewKind: latestMessages.get(event.memberId)
+ ? ((latestMessages.get(event.memberId)?.toMember ? "p2p" : "broadcast") as
+ | "broadcast"
+ | "p2p")
+ : undefined,
+ }))
+ .sort((a, b) => {
+ const aLeader = isLeaderMember(a.memberId) ? 0 : 1;
+ const bLeader = isLeaderMember(b.memberId) ? 0 : 1;
+ if (aLeader !== bLeader) return aLeader - bLeader;
+ return b.timestamp - a.timestamp;
+ });
+}
+
+export function orderedMemberIds(
+ memberEvents: TeamMemberEvent[],
+ messageEvents: TeamMessageEvent[],
+): string[] {
+ return latestMemberSummaries(memberEvents, messageEvents).map((member) => member.memberId);
+}
+
+export function taskEventLabel(event: TeamTaskEvent): string {
+ const action = event.type.replace(/^team\.task\./, "").replaceAll("_", " ");
+ return `${action} ${event.taskId}${event.status ? ` · ${event.status}` : ""}`.trim();
+}
+
+export function messageEventLabel(event: TeamMessageEvent): string {
+ const route = event.toMember
+ ? `p2p ${event.fromMember} → ${event.toMember}`
+ : `broadcast ${event.fromMember} → team`;
+ return `${route} · ${event.content.replace(/\s+/g, " ").trim()}`;
+}
+
+export function messagePreviewLabel(
+ content: string,
+ kind: "broadcast" | "p2p" | undefined,
+): string {
+ const prefix = kind === "broadcast" ? "broadcast" : kind === "p2p" ? "p2p" : null;
+ return prefix ? `${prefix} · ${content}` : content;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/team-status-pill.ts b/jiuwenclaw/cli/src/ui/components/team-status-pill.ts
new file mode 100644
index 0000000000..7c2916bd1f
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/team-status-pill.ts
@@ -0,0 +1,39 @@
+import type { TeamMemberEvent, TeamMessageEvent, TeamTaskEvent } from "../../core/types.js";
+import { padToWidth } from "../rendering/text.js";
+import { palette } from "../theme.js";
+import {
+ isWorkingStatusLabel,
+ latestMemberSummaries,
+ memberStatusPhrase,
+ taskEventLabel,
+ truncate,
+} from "./team-shared.js";
+
+export function renderTeamStatusPill(
+ memberEvents: TeamMemberEvent[],
+ taskEvents: TeamTaskEvent[],
+ messageEvents: TeamMessageEvent[],
+ width: number,
+): string[] {
+ const members = latestMemberSummaries(memberEvents, messageEvents);
+ if (members.length === 0 && taskEvents.length === 0 && messageEvents.length === 0) {
+ return [];
+ }
+
+ const workingCount = members.filter((member) => isWorkingStatusLabel(member.statusLabel)).length;
+ const parts: string[] = [];
+ if (members.length > 0) {
+ parts.push(`${members.length} teammate${members.length === 1 ? "" : "s"}`);
+ }
+ if (workingCount > 0) {
+ parts.push(`${workingCount} working`);
+ } else if (members[0]) {
+ parts.push(memberStatusPhrase(members[0]));
+ }
+ const latestTask = taskEvents.at(-1);
+ if (latestTask) {
+ parts.push(truncate(taskEventLabel(latestTask), 32));
+ }
+ const content = parts.length > 0 ? parts.join(" · ") : "team active";
+ return [padToWidth(palette.text.dim(`• ${content} · ctrl+g to view`), width)];
+}
diff --git a/jiuwenclaw/cli/src/ui/components/todo-list.ts b/jiuwenclaw/cli/src/ui/components/todo-list.ts
index 88a17b5763..21e61e268c 100644
--- a/jiuwenclaw/cli/src/ui/components/todo-list.ts
+++ b/jiuwenclaw/cli/src/ui/components/todo-list.ts
@@ -3,9 +3,31 @@ import type { TodoItem } from "../../core/types.js";
import { padToWidth } from "../rendering/text.js";
import { palette, selectListTheme } from "../theme.js";
+function normalizeTodoText(text: string): string {
+ const trimmed = text.trim();
+ if (!trimmed) {
+ return trimmed;
+ }
+ return trimmed
+ .replace(/^Executing\s+/i, "")
+ .replace(/^Running\s+/i, "")
+ .replace(/^Calling\s+/i, "")
+ .replace(/^Using\s+/i, "")
+ .replace(/^Working on\s+/i, "")
+ .replace(/^Processing\s+/i, "")
+ .replace(/^Reading\s+/i, "")
+ .replace(/^Searching\s+/i, "")
+ .replace(/^Fetching\s+/i, "")
+ .replace(/^Writing\s+/i, "")
+ .replace(/^Editing\s+/i, "")
+ .replace(/^正在调用\s+/u, "")
+ .replace(/^正在/u, "")
+ .replace(/(?:\.\.\.|…)\s*$/u, "");
+}
+
function todoLabel(todo: TodoItem): string {
const prefix = todo.status === "in_progress" ? "●" : todo.status === "completed" ? "✓" : "○";
- return `${prefix} ${todo.activeForm || todo.content}`;
+ return `${prefix} ${normalizeTodoText(todo.activeForm || todo.content)}`;
}
export function renderTodoList(todos: TodoItem[], width: number): string[] {
diff --git a/jiuwenclaw/cli/src/ui/components/tools/collapsed-tool-group-message.ts b/jiuwenclaw/cli/src/ui/components/tools/collapsed-tool-group-message.ts
new file mode 100644
index 0000000000..ddf2514167
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/collapsed-tool-group-message.ts
@@ -0,0 +1,34 @@
+import type { Component } from "@mariozechner/pi-tui";
+import type { HistoryItem } from "../../../core/types.js";
+import { renderCollapsedCompactSummaryLines } from "./compact-tool-renderers.js";
+import { ToolGroupMessageComponent } from "./tool-group-message.js";
+
+export class CollapsedToolGroupMessageComponent implements Component {
+ constructor(
+ private readonly entry: Extract<HistoryItem, { kind: "collapsed_tool_group" }>,
+ private readonly collapsed: boolean,
+ private readonly showDetails: boolean,
+ private readonly animationPhase: number,
+ ) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ if (!this.showDetails) {
+ return renderCollapsedCompactSummaryLines(this.entry, width, this.animationPhase);
+ }
+ return new ToolGroupMessageComponent(
+ {
+ kind: "tool_group",
+ id: this.entry.id,
+ sessionId: this.entry.sessionId,
+ requestId: this.entry.requestId,
+ tools: this.collapsed ? this.entry.tools.slice(-1) : this.entry.tools,
+ at: this.entry.at,
+ },
+ false,
+ true,
+ this.animationPhase,
+ ).render(width);
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/command-tool-renderers.ts b/jiuwenclaw/cli/src/ui/components/tools/command-tool-renderers.ts
new file mode 100644
index 0000000000..7a3811bc71
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/command-tool-renderers.ts
@@ -0,0 +1,166 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { summarize } from "../../rendering/text.js";
+import type { DetailedToolRenderOptions } from "./tool-render-types.js";
+import {
+ getNumericArg,
+ getStringArg,
+ nonEmptyLines,
+ parseFetchResult,
+ parseToolResultPayload,
+ renderPreviewLines,
+ renderStructuredBranch,
+ renderToolBranch,
+ renderToolTail,
+ renderToolTitle,
+ shouldRenderStructuredPayloadByDefault,
+ summarizePath,
+ summarizeToolResultByKind,
+ toolStateColor,
+} from "./tool-render-shared.js";
+
+export function renderRunTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const payload = parseToolResultPayload(tool);
+ const command =
+ getStringArg(args, "command", "cmd", "script", "input") ??
+ getStringArg(payload ?? {}, "command", "cmd") ??
+ tool.description ??
+ tool.name;
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `Run ${summarize(command, 120)}`,
+ options.animationPhase,
+ );
+
+ const cwd = getStringArg(args, "cwd", "path", "workdir");
+ if (cwd) {
+ lines.push(...renderToolBranch(width, `cwd: ${summarizePath(cwd) ?? cwd}`, palette.text.dim));
+ }
+
+ if (tool.result) {
+ const exitCode =
+ getNumericArg(payload ?? {}, "exit_code", "exitCode", "code") ??
+ getNumericArg(args, "exit_code", "exitCode", "code");
+ const stdoutLines =
+ nonEmptyLines(payload?.stdout) ||
+ nonEmptyLines(payload?.output) ||
+ nonEmptyLines(payload?.content) ||
+ nonEmptyLines(payload?.result);
+ const stderrLines = nonEmptyLines(payload?.stderr);
+
+ const summaryParts: string[] = [];
+ if (exitCode !== undefined) {
+ summaryParts.push(`exit ${exitCode}`);
+ }
+ if (stdoutLines.length > 0) {
+ summaryParts.push(`${stdoutLines.length} line${stdoutLines.length === 1 ? "" : "s"}`);
+ } else if (stderrLines.length > 0) {
+ summaryParts.push(`${stderrLines.length} stderr line${stderrLines.length === 1 ? "" : "s"}`);
+ }
+
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ?? (summaryParts.join(" | ") || summarize(tool.result, 120)),
+ toolStateColor(tool),
+ ),
+ );
+
+ if (stdoutLines.length > 0 || stderrLines.length > 0) {
+ if (tool.isError || tool.status === "timeout") {
+ lines.push(
+ ...renderPreviewLines(
+ width,
+ stderrLines.length > 0 ? stderrLines : stdoutLines,
+ palette.status.warning,
+ 4,
+ 2,
+ false,
+ "lines",
+ ),
+ );
+ }
+ } else if (
+ payload &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderStructuredBranch(
+ width,
+ payload,
+ options.showDetails,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ } else if (
+ !payload &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderPreviewLines(
+ width,
+ nonEmptyLines(tool.result),
+ tool.isError ? palette.status.error : palette.text.assistant,
+ 8,
+ 4,
+ options.showDetails,
+ "lines",
+ ),
+ );
+ }
+ }
+
+ return lines;
+}
+
+export function renderFetchTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const fetchResult = parseFetchResult(tool);
+ const url = getStringArg(args, "url") ?? fetchResult.url ?? tool.description ?? tool.name;
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `Fetch ${summarize(url, 120)}`,
+ options.animationPhase,
+ );
+
+ const metaParts = [
+ fetchResult.status ? `status ${fetchResult.status}` : undefined,
+ fetchResult.title,
+ ].filter((part): part is string => Boolean(part && part.trim()));
+ if (metaParts.length > 0) {
+ lines.push(...renderToolBranch(width, metaParts.join(" | "), palette.text.dim));
+ }
+
+ if (tool.result) {
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120),
+ toolStateColor(tool),
+ ),
+ );
+ }
+
+ return lines;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/compact-tool-renderers.ts b/jiuwenclaw/cli/src/ui/components/tools/compact-tool-renderers.ts
new file mode 100644
index 0000000000..2c8d647b17
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/compact-tool-renderers.ts
@@ -0,0 +1,184 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { summarize } from "../../rendering/text.js";
+import {
+ getStringArg,
+ getToolFilePath,
+ isEditTool,
+ isFetchTool,
+ isGlobTool,
+ isListTool,
+ isMcpTool,
+ isReadTool,
+ isRunTool,
+ isSearchTool,
+ isToolRunning,
+ isWriteTool,
+ renderToolBranch,
+ renderToolTitle,
+ summarizeToolArguments,
+ toolDisplayName,
+ TOOL_EXPAND_HINT,
+} from "./tool-render-shared.js";
+
+function summarizeCompactHint(hint: string, maxWidth = 72): string {
+ const normalized =
+ hint
+ .split("\n")
+ .map((line) => line.trim())
+ .find((line) => line.length > 0) ?? hint.trim();
+ return summarize(normalized, maxWidth);
+}
+
+function compactActionLabel(label: string): string {
+ return label;
+}
+
+export function compactToolTitle(tool: ToolCallDisplay): string {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args);
+ const query = getStringArg(args, "pattern", "query", "q", "prompt", "glob");
+ const url = getStringArg(args, "url");
+ const running = isToolRunning(tool);
+ const hasError = tool.isError || tool.status === "error";
+ const hasTimeout = tool.status === "timeout";
+
+ if (hasError) {
+ return `Failed ${toolDisplayName(tool).toLowerCase()} (${TOOL_EXPAND_HINT})`;
+ }
+ if (hasTimeout) {
+ return `Timed out ${toolDisplayName(tool).toLowerCase()} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isListTool(tool.name)) {
+ return `${compactActionLabel(running ? "Listing directories" : "Listed directories")} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isReadTool(tool.name)) {
+ return `${compactActionLabel(`${running ? "Reading" : "Read"} ${path ?? "file"}`)} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isSearchTool(tool.name) || isGlobTool(tool.name)) {
+ const target = query ? summarize(query, 48) : toolDisplayName(tool).toLowerCase();
+ return `${compactActionLabel(`${running ? "Searching" : "Searched"} ${target}`)} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isWriteTool(tool.name)) {
+ return `${compactActionLabel(`${running ? "Writing" : "Wrote"} ${path ?? "file"}`)} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isEditTool(tool.name)) {
+ return `${compactActionLabel(`${running ? "Editing" : "Edited"} ${path ?? "file"}`)} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isFetchTool(tool.name)) {
+ return `${compactActionLabel(`${running ? "Fetching" : "Fetched"} ${url ? summarize(url, 48) : "page"}`)} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isRunTool(tool.name)) {
+ return `${compactActionLabel(`${running ? "Running" : "Ran"} command`)} (${TOOL_EXPAND_HINT})`;
+ }
+ if (isMcpTool(tool.name)) {
+ return `${compactActionLabel(
+ `${running ? "Querying" : "Queried"} ${toolDisplayName(tool)
+ .replace(/^Query\s+/i, "")
+ .toLowerCase()}`,
+ )} (${TOOL_EXPAND_HINT})`;
+ }
+ return `${compactActionLabel(running ? "Working" : toolDisplayName(tool))} (${TOOL_EXPAND_HINT})`;
+}
+
+export function compactToolHint(tool: ToolCallDisplay): string | undefined {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+
+ if (isRunTool(tool.name)) {
+ const command = getStringArg(args, "command", "cmd", "script", "input");
+ return command ? `$ ${summarize(command, 120)}` : tool.summary;
+ }
+ if (isWriteTool(tool.name) || isEditTool(tool.name)) {
+ return getToolFilePath(args) ?? summarizeToolArguments(tool.name, args) ?? tool.summary;
+ }
+ if (isListTool(tool.name) || isReadTool(tool.name)) {
+ return getToolFilePath(args) ?? tool.summary;
+ }
+ if (isFetchTool(tool.name)) {
+ return getStringArg(args, "url") ?? tool.summary;
+ }
+ if (isSearchTool(tool.name) || isGlobTool(tool.name)) {
+ return summarizeToolArguments(tool.name, args) ?? tool.summary;
+ }
+ if (isMcpTool(tool.name)) {
+ return summarizeToolArguments(tool.name, args) ?? tool.summary;
+ }
+ return summarizeToolArguments(tool.name, args) ?? tool.summary;
+}
+
+export function renderCompactToolLines(
+ tool: ToolCallDisplay,
+ width: number,
+ animationPhase: number,
+): string[] {
+ const title = compactToolTitle(tool);
+ const lines = renderToolTitle(width, tool, title, animationPhase);
+ const hint = compactToolHint(tool);
+ if (hint) {
+ lines.push(...renderToolBranch(width, summarizeCompactHint(hint, 80), palette.text.dim));
+ }
+ return lines;
+}
+
+export function renderCollapsedCompactSummaryLines(
+ entry: {
+ id: string;
+ counts: { read: number; search: number; list: number; fetch: number };
+ tools: ToolCallDisplay[];
+ latestHint?: string;
+ },
+ width: number,
+ animationPhase: number,
+): string[] {
+ const readCount = entry.counts.read;
+ const searchCount = entry.counts.search;
+ const listCount = entry.counts.list;
+ const fetchCount = entry.counts.fetch;
+ const running = entry.tools.some((tool) => isToolRunning(tool));
+ const hasError = entry.tools.some((tool) => tool.isError || tool.status === "error");
+ const hasTimeout = entry.tools.some((tool) => tool.status === "timeout");
+ const lastTool = entry.tools[entry.tools.length - 1];
+
+ const actionLabel =
+ listCount > 0
+ ? `${running ? "Listing" : "Listed"} ${listCount} director${listCount === 1 ? "y" : "ies"}`
+ : readCount > 0
+ ? `${running ? "Reading" : "Read"} ${readCount} file${readCount === 1 ? "" : "s"}`
+ : searchCount > 0
+ ? `${running ? "Searching" : "Searched"} ${searchCount} match set${searchCount === 1 ? "" : "s"}`
+ : fetchCount > 0
+ ? `${running ? "Fetching" : "Fetched"} ${fetchCount} page${fetchCount === 1 ? "" : "s"}`
+ : `${running ? "Working" : "Completed"} ${entry.tools.length} tool${entry.tools.length === 1 ? "" : "s"}`;
+
+ const statusLabel = hasError
+ ? `Failed ${entry.tools.length} tool${entry.tools.length === 1 ? "" : "s"}`
+ : hasTimeout
+ ? `Timed out after ${entry.tools.length} tool${entry.tools.length === 1 ? "" : "s"}`
+ : compactActionLabel(actionLabel);
+
+ const pseudoTool: ToolCallDisplay = {
+ callId: entry.id,
+ name: "collapsed",
+ status: hasError ? "error" : hasTimeout ? "timeout" : running ? "running" : "completed",
+ isError: hasError,
+ };
+ const lines = renderToolTitle(
+ width,
+ pseudoTool,
+ `${statusLabel} (${TOOL_EXPAND_HINT})`,
+ animationPhase,
+ );
+
+ const hint = entry.latestHint ?? lastTool?.summary;
+ if (hint) {
+ lines.push(...renderToolBranch(width, summarizeCompactHint(hint, 72), palette.text.dim));
+ }
+
+ return lines;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/detailed-tool-renderers.ts b/jiuwenclaw/cli/src/ui/components/tools/detailed-tool-renderers.ts
new file mode 100644
index 0000000000..4233627b2c
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/detailed-tool-renderers.ts
@@ -0,0 +1,65 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { renderFetchTool, renderRunTool } from "./command-tool-renderers.js";
+import {
+ renderEditTool,
+ renderListTool,
+ renderReadTool,
+ renderSessionTool,
+ renderWriteTool,
+} from "./file-tool-renderers.js";
+import {
+ isEditTool,
+ isFetchTool,
+ isGlobTool,
+ isListTool,
+ isMcpTool,
+ isReadTool,
+ isRunTool,
+ isSearchTool,
+ isWriteTool,
+} from "./tool-render-shared.js";
+import type { DetailedToolRenderOptions } from "./tool-render-types.js";
+import {
+ renderGenericTool,
+ renderGlobTool,
+ renderMcpTool,
+ renderSearchTool,
+} from "./search-tool-renderers.js";
+
+export function renderDetailedToolLines(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ if (tool.name === "session") {
+ return renderSessionTool(tool, width, options);
+ }
+ if (isReadTool(tool.name)) {
+ return renderReadTool(tool, width, options);
+ }
+ if (isListTool(tool.name)) {
+ return renderListTool(tool, width, options);
+ }
+ if (isWriteTool(tool.name)) {
+ return renderWriteTool(tool, width, options);
+ }
+ if (isEditTool(tool.name)) {
+ return renderEditTool(tool, width, options);
+ }
+ if (isRunTool(tool.name)) {
+ return renderRunTool(tool, width, options);
+ }
+ if (isFetchTool(tool.name)) {
+ return renderFetchTool(tool, width, options);
+ }
+ if (isGlobTool(tool.name)) {
+ return renderGlobTool(tool, width, options);
+ }
+ if (isSearchTool(tool.name)) {
+ return renderSearchTool(tool, width, options);
+ }
+ if (isMcpTool(tool.name)) {
+ return renderMcpTool(tool, width, options);
+ }
+ return renderGenericTool(tool, width, options);
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/file-tool-renderers.ts b/jiuwenclaw/cli/src/ui/components/tools/file-tool-renderers.ts
new file mode 100644
index 0000000000..64dc26ee3a
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/file-tool-renderers.ts
@@ -0,0 +1,325 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { summarize } from "../../rendering/text.js";
+import type { DetailedToolRenderOptions } from "./tool-render-types.js";
+import {
+ TOOL_EXPAND_HINT,
+ countLogicalLines,
+ extractTrailingBracketNotices,
+ getNumericArg,
+ getStringArg,
+ getStringList,
+ getToolFilePath,
+ isCodeLikePath,
+ isPlainObject,
+ parseToolResultPayload,
+ renderAddedLines,
+ renderSimpleDiff,
+ renderToolBranch,
+ renderToolTail,
+ renderToolTitle,
+ summarizeToolResultByKind,
+ toolStateColor,
+} from "./tool-render-shared.js";
+
+export function renderSessionTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const description =
+ typeof args.description === "string" && args.description
+ ? args.description
+ : (tool.description ?? "session task");
+ const index = typeof args.index === "number" ? args.index : undefined;
+ const total = typeof args.total === "number" ? args.total : undefined;
+ const label =
+ index !== undefined && total !== undefined
+ ? `Run session ${index}/${total} · ${description}`
+ : `Run session · ${description}`;
+ const lines = renderToolTitle(width, tool, label, options.animationPhase);
+
+ if (tool.result) {
+ const previewLines = tool.result.split("\n").filter(Boolean);
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120),
+ toolStateColor(tool),
+ ),
+ );
+ if (options.showDetails) {
+ for (const line of previewLines.slice(0, 6)) {
+ lines.push(...renderToolBranch(width, line, palette.text.assistant));
+ }
+ if (previewLines.length > 6) {
+ lines.push(
+ ...renderToolBranch(width, `+ ${previewLines.length - 6} more lines`, palette.text.dim),
+ );
+ }
+ } else if (previewLines.length > 0) {
+ lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
+ }
+ }
+
+ return lines;
+}
+
+export function renderReadTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const payload = parseToolResultPayload(tool);
+ const path = getToolFilePath(args) ?? getStringArg(payload ?? {}, "path", "file_path", "file");
+ const offset = typeof args.offset === "number" ? args.offset : undefined;
+ const limit = typeof args.limit === "number" ? args.limit : undefined;
+ const rangeSuffix =
+ offset !== undefined || limit !== undefined
+ ? `:${offset ?? 1}${limit !== undefined ? `-${(offset ?? 1) + limit - 1}` : ""}`
+ : "";
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `Read ${path ?? tool.description ?? tool.name}${rangeSuffix}`,
+ options.animationPhase,
+ );
+
+ if (tool.result) {
+ const content = getStringArg(payload ?? {}, "content", "result", "data") ?? tool.result;
+ const { notices } = extractTrailingBracketNotices(content);
+ const totalLines =
+ getNumericArg(payload ?? {}, "totalLines", "total_lines") ?? countLogicalLines(content);
+ const startLine = getNumericArg(payload ?? {}, "start_line", "startLine");
+ const endLine = getNumericArg(payload ?? {}, "end_line", "endLine");
+ const truncated = typeof payload?.truncated === "boolean" ? payload.truncated : undefined;
+ if (path) {
+ const lineRange =
+ startLine !== undefined && endLine !== undefined ? ` · ${startLine}-${endLine}` : "";
+ const meta = `${totalLines} lines${lineRange}${isCodeLikePath(path) ? " · code" : ""}`;
+ lines.push(...renderToolTail(width, meta, palette.text.dim));
+ }
+ if (truncated) {
+ lines.push(...renderToolBranch(width, "result truncated", palette.status.warning));
+ }
+ for (const notice of notices) {
+ lines.push(...renderToolBranch(width, notice, palette.status.warning));
+ }
+ }
+
+ return lines;
+}
+
+export function renderListTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args) ?? ".";
+ const limit = typeof args.limit === "number" ? args.limit : undefined;
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `List ${path}${limit !== undefined ? ` (limit ${limit})` : ""}`,
+ options.animationPhase,
+ );
+
+ if (tool.result) {
+ const payload = parseToolResultPayload(tool);
+ const files = getStringList(payload ?? {}, "files");
+ const dirs = getStringList(payload ?? {}, "dirs").map((dir) => `${dir}/`);
+ const payloadEntries = [...files, ...dirs];
+ const { mainLines, notices } = extractTrailingBracketNotices(tool.result);
+ const visibleEntries = payloadEntries.length > 0 ? payloadEntries : mainLines;
+ const shown = visibleEntries.slice(0, options.showDetails ? 12 : 6);
+ lines.push(
+ ...renderToolTail(
+ width,
+ `${visibleEntries.length} entr${visibleEntries.length === 1 ? "y" : "ies"}`,
+ palette.text.dim,
+ ),
+ );
+ if (visibleEntries.length > shown.length) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `+ ${visibleEntries.length - shown.length} more entries`,
+ palette.text.dim,
+ ),
+ );
+ }
+ for (const notice of notices) {
+ lines.push(...renderToolBranch(width, notice, palette.status.warning));
+ }
+ }
+
+ return lines;
+}
+
+export function renderWriteTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args);
+ const content = typeof args.content === "string" ? args.content : "";
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `Write ${path ?? tool.description ?? tool.name}`,
+ options.animationPhase,
+ );
+
+ if (content) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `${countLogicalLines(content)} lines · ${content.length} chars`,
+ palette.text.dim,
+ ),
+ );
+ const diffLines = renderAddedLines(Math.max(1, width - 2), content);
+ const shown = options.showDetails ? diffLines : diffLines.slice(0, 6);
+ lines.push(...shown.flatMap((line) => renderToolBranch(width, line, (value) => value)));
+ if (!options.showDetails && diffLines.length > shown.length) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `+ ${diffLines.length - shown.length} more diff lines`,
+ palette.text.dim,
+ ),
+ );
+ lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
+ }
+ }
+
+ if (tool.result) {
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120),
+ toolStateColor(tool),
+ ),
+ );
+ }
+
+ return lines;
+}
+
+export function renderEditTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args);
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `Edit ${path ?? tool.description ?? tool.name}`,
+ options.animationPhase,
+ );
+
+ const oldString =
+ typeof args.old_string === "string"
+ ? args.old_string
+ : typeof args.oldText === "string"
+ ? args.oldText
+ : undefined;
+ const newString =
+ typeof args.new_string === "string"
+ ? args.new_string
+ : typeof args.newText === "string"
+ ? args.newText
+ : undefined;
+
+ if (oldString !== undefined && newString !== undefined) {
+ const diffLines = renderSimpleDiff(Math.max(1, width - 2), oldString, newString);
+ const shown = options.showDetails ? diffLines : diffLines.slice(0, 6);
+ lines.push(...shown.flatMap((line) => renderToolBranch(width, line, (value) => value)));
+ if (!options.showDetails && diffLines.length > shown.length) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `+ ${diffLines.length - shown.length} more diff lines`,
+ palette.text.dim,
+ ),
+ );
+ lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
+ }
+ } else if (Array.isArray(args.edits)) {
+ lines.push(...renderToolTail(width, `${args.edits.length} edit block(s)`, palette.text.dim));
+ const shownEdits = args.edits.slice(0, options.showDetails ? 3 : 1);
+ for (const edit of shownEdits) {
+ if (!isPlainObject(edit)) continue;
+ const before =
+ typeof edit.oldText === "string"
+ ? edit.oldText
+ : typeof edit.old_string === "string"
+ ? edit.old_string
+ : "";
+ const after =
+ typeof edit.newText === "string"
+ ? edit.newText
+ : typeof edit.new_string === "string"
+ ? edit.new_string
+ : "";
+ if (!before && !after) continue;
+ const diffLines = renderSimpleDiff(Math.max(1, width - 2), before, after);
+ lines.push(
+ ...diffLines
+ .slice(0, options.showDetails ? 6 : 2)
+ .flatMap((line) => renderToolBranch(width, line, (value) => value)),
+ );
+ }
+ if (args.edits.length > shownEdits.length) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `+ ${args.edits.length - shownEdits.length} more edit blocks`,
+ palette.text.dim,
+ ),
+ );
+ }
+ if (!options.showDetails && args.edits.length > 0) {
+ lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
+ }
+ }
+
+ if (tool.result) {
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120),
+ toolStateColor(tool),
+ ),
+ );
+ }
+
+ return lines;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/index.ts b/jiuwenclaw/cli/src/ui/components/tools/index.ts
index 1f8fd3f19f..f92941f76d 100644
--- a/jiuwenclaw/cli/src/ui/components/tools/index.ts
+++ b/jiuwenclaw/cli/src/ui/components/tools/index.ts
@@ -1 +1,9 @@
-export { ToolGroupMessageComponent, summarizeToolResultByKind } from "./tool-group-message.js";
+export { ToolGroupMessageComponent } from "./tool-group-message.js";
+export { CollapsedToolGroupMessageComponent } from "./collapsed-tool-group-message.js";
+export {
+ isToolRunning,
+ renderToolBranch,
+ renderToolTitle,
+ summarizeToolResultByKind,
+ TOOL_EXPAND_HINT,
+} from "./tool-render-shared.js";
diff --git a/jiuwenclaw/cli/src/ui/components/tools/search-tool-renderers.ts b/jiuwenclaw/cli/src/ui/components/tools/search-tool-renderers.ts
new file mode 100644
index 0000000000..0742ee785f
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/search-tool-renderers.ts
@@ -0,0 +1,322 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { summarize } from "../../rendering/text.js";
+import type { DetailedToolRenderOptions } from "./tool-render-types.js";
+import {
+ getNumericArg,
+ getStringArg,
+ getStringList,
+ getStringListFromValue,
+ isPlainObject,
+ nonEmptyLines,
+ parseToolResultPayload,
+ parseToolResultValue,
+ renderPreviewLines,
+ renderStructuredBranch,
+ renderToolBranch,
+ renderToolTail,
+ renderToolTitle,
+ shouldRenderStructuredPayloadByDefault,
+ summarizePath,
+ summarizeToolArguments,
+ summarizeToolResultByKind,
+ toolDisplayName,
+ toolStateColor,
+} from "./tool-render-shared.js";
+
+export function renderGlobTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const payload = parseToolResultPayload(tool);
+ const parsedValue = parseToolResultValue(tool);
+ const pattern =
+ getStringArg(args, "glob", "pattern", "path", "file_path") ??
+ getStringArg(payload ?? {}, "glob", "pattern") ??
+ tool.description ??
+ tool.name;
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `Glob ${summarize(pattern, 120)}`,
+ options.animationPhase,
+ );
+ const root = getStringArg(args, "root", "cwd", "dir_path");
+ if (root) {
+ lines.push(
+ ...renderToolBranch(width, `root: ${summarizePath(root) ?? root}`, palette.text.dim),
+ );
+ }
+
+ if (tool.result) {
+ const payloadMatchLines = getStringList(payload ?? {}, "matching_files", "files");
+ const valueMatchLines = getStringListFromValue(parsedValue);
+ const matchLines = payloadMatchLines.length > 0 ? payloadMatchLines : valueMatchLines;
+ const count = getNumericArg(payload ?? {}, "count") ?? matchLines.length;
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ?? `${count} file${count === 1 ? "" : "s"}`,
+ toolStateColor(tool),
+ ),
+ );
+ if (
+ !matchLines.length &&
+ payload &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderStructuredBranch(width, payload, options.showDetails, palette.text.assistant),
+ );
+ } else if (
+ !matchLines.length &&
+ parsedValue !== undefined &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderStructuredBranch(width, parsedValue, options.showDetails, palette.text.assistant),
+ );
+ }
+ }
+
+ return lines;
+}
+
+export function renderSearchTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const payload = parseToolResultPayload(tool);
+ const parsedValue = parseToolResultValue(tool);
+ const query =
+ getStringArg(args, "pattern", "query", "q", "prompt", "glob") ??
+ getStringArg(payload ?? {}, "pattern", "query", "q") ??
+ tool.description ??
+ tool.name;
+ const root =
+ getStringArg(args, "path", "cwd", "root", "dir_path") ??
+ getStringArg(payload ?? {}, "path", "cwd", "root");
+ const title = root
+ ? `Search ${summarize(query, 96)} in ${summarizePath(root) ?? root}`
+ : `Search ${summarize(query, 120)}`;
+ const lines = renderToolTitle(width, tool, title, options.animationPhase);
+
+ if (tool.result) {
+ const payloadResultLines = getStringList(
+ payload ?? {},
+ "matches",
+ "results",
+ "items",
+ "hits",
+ "files",
+ );
+ const valueResultLines = getStringListFromValue(parsedValue);
+ const resultLines = payloadResultLines.length > 0 ? payloadResultLines : valueResultLines;
+ const fallbackLines = nonEmptyLines(tool.result);
+ const visibleLines = resultLines.length > 0 ? resultLines : fallbackLines;
+ const count =
+ getNumericArg(payload ?? {}, "count", "match_count", "matches_count", "total") ??
+ visibleLines.length;
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ?? `${count} match${count === 1 ? "" : "es"}`,
+ toolStateColor(tool),
+ ),
+ );
+ if (visibleLines.length > 0 && count > visibleLines.length) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `+ ${count - visibleLines.length} more matches`,
+ palette.text.dim,
+ ),
+ );
+ } else if (
+ payload &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderStructuredBranch(
+ width,
+ payload,
+ options.showDetails,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ } else if (
+ parsedValue !== undefined &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderStructuredBranch(
+ width,
+ parsedValue,
+ options.showDetails,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ }
+ }
+
+ return lines;
+}
+
+export function renderMcpTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const title = toolDisplayName(tool);
+ const detail =
+ getStringArg(args, "query", "q", "prompt", "url", "path", "file_path", "file") ??
+ tool.description ??
+ summarizeToolArguments(tool.name, args);
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `${title}${detail ? ` · ${summarize(detail, 120)}` : ""}`,
+ options.animationPhase,
+ );
+
+ if (isPlainObject(tool.arguments)) {
+ const argsSummary = summarizeToolArguments(tool.name, tool.arguments);
+ if (argsSummary) {
+ lines.push(...renderToolTail(width, argsSummary, palette.text.dim));
+ }
+ }
+
+ if (tool.result) {
+ const payload = parseToolResultPayload(tool);
+ const parsedValue = parseToolResultValue(tool);
+ lines.push(
+ ...renderToolTail(
+ width,
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120),
+ toolStateColor(tool),
+ ),
+ );
+ if (payload && options.showDetails && shouldRenderStructuredPayloadByDefault(tool.name)) {
+ lines.push(
+ ...renderStructuredBranch(
+ width,
+ payload,
+ options.showDetails,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ } else if (
+ parsedValue !== undefined &&
+ options.showDetails &&
+ shouldRenderStructuredPayloadByDefault(tool.name)
+ ) {
+ lines.push(
+ ...renderStructuredBranch(
+ width,
+ parsedValue,
+ options.showDetails,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ } else if (options.showDetails && shouldRenderStructuredPayloadByDefault(tool.name)) {
+ lines.push(
+ ...renderPreviewLines(
+ width,
+ nonEmptyLines(tool.result),
+ tool.isError ? palette.status.error : palette.text.assistant,
+ 8,
+ 4,
+ options.showDetails,
+ "lines",
+ ),
+ );
+ }
+ }
+
+ return lines;
+}
+
+export function renderGenericTool(
+ tool: ToolCallDisplay,
+ width: number,
+ options: DetailedToolRenderOptions,
+): string[] {
+ const title = toolDisplayName(tool);
+ const detail = tool.description ?? summarizeToolArguments(tool.name, tool.arguments);
+ const separator = title.startsWith("Query ") ? " · " : " ";
+ const lines = renderToolTitle(
+ width,
+ tool,
+ `${title}${detail ? `${separator}${detail}` : ""}`,
+ options.animationPhase,
+ );
+
+ if (isPlainObject(tool.arguments)) {
+ lines.push(
+ ...renderStructuredBranch(width, tool.arguments, options.showDetails, palette.text.dim),
+ );
+ }
+
+ if (tool.result) {
+ const summary =
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120);
+ lines.push(...renderToolTail(width, summary, toolStateColor(tool)));
+
+ const parsedResult = parseToolResultValue(tool);
+ if (parsedResult !== tool.result) {
+ lines.push(
+ ...renderStructuredBranch(
+ width,
+ parsedResult,
+ options.showDetails,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ } else if (options.showDetails) {
+ const previewLines = tool.result.split("\n").filter(Boolean);
+ const shown = previewLines.slice(0, tool.isError ? 2 : 4);
+ for (const line of shown) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ line,
+ tool.isError ? palette.status.error : palette.text.assistant,
+ ),
+ );
+ }
+ if (previewLines.length > shown.length) {
+ lines.push(
+ ...renderToolBranch(
+ width,
+ `+ ${previewLines.length - shown.length} more lines`,
+ palette.text.dim,
+ ),
+ );
+ }
+ }
+ }
+
+ return lines;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts
index 57a6eb8564..6d90f8d85f 100644
--- a/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts
@@ -1,1377 +1,35 @@
import type { Component } from "@mariozechner/pi-tui";
-import type { HistoryItem, ToolCallDisplay } from "../../../core/types.js";
-import { palette } from "../../theme.js";
-import { prefixedLines, renderWrappedText, summarize } from "../../rendering/text.js";
-
-const TOOL_BODY_PREFIX = "│ ";
-const TOOL_BODY_CONTINUATION = "│ ";
-const TOOL_TAIL_PREFIX = "└ ";
-const TOOL_TAIL_CONTINUATION = " ";
-const TOOL_EXPAND_HINT = "ctrl+o to expand";
-const MAX_STRUCTURED_LINES_COLLAPSED = 6;
-const MAX_STRUCTURED_LINES_EXPANDED = 18;
-
-function summarizePath(value: unknown): string | undefined {
- if (typeof value !== "string") return undefined;
- const parts = value.split(/[\\/]/).filter(Boolean);
- return parts.slice(-3).join("/");
-}
-
-function normalizePythonLiteralToJson(value: string): string {
- return value
- .replace(/\bNone\b/g, "null")
- .replace(/\bTrue\b/g, "true")
- .replace(/\bFalse\b/g, "false")
- .replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, (_match, content: string) => {
- const normalized = content.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
- return `"${normalized}"`;
- });
-}
-
-function parseLiteralFragment(value: string): unknown {
- const trimmed = value.trim();
- if (!trimmed || trimmed === "None") {
- return null;
- }
- try {
- return JSON.parse(trimmed);
- } catch {
- // Fall through.
- }
- try {
- return JSON.parse(normalizePythonLiteralToJson(trimmed));
- } catch {
- return trimmed;
- }
-}
-
-function parseProtocolWrapper(value: string): unknown | undefined {
- if (!value.includes("data=") && !value.includes("success=") && !value.includes("error=")) {
- return undefined;
- }
-
- let working = value.trim();
- let errorValue: unknown = undefined;
- const errorIndex = working.lastIndexOf(" error=");
- if (errorIndex >= 0) {
- errorValue = parseLiteralFragment(working.slice(errorIndex + " error=".length));
- working = working.slice(0, errorIndex);
- }
-
- let dataValue: unknown = undefined;
- const dataIndex = working.indexOf(" data=");
- if (dataIndex >= 0) {
- dataValue = parseLiteralFragment(working.slice(dataIndex + " data=".length));
- working = working.slice(0, dataIndex);
- }
-
- const successMatch = /\bsuccess=(True|False|true|false)\b/.exec(working);
- const successValue =
- successMatch?.[1] !== undefined ? successMatch[1].toLowerCase() === "true" : undefined;
-
- if (isPlainObject(dataValue)) {
- return {
- ...dataValue,
- ...(successValue !== undefined ? { success: successValue } : {}),
- ...(errorValue !== undefined ? { error: errorValue } : {}),
- };
- }
- if (Array.isArray(dataValue)) {
- return {
- items: dataValue,
- count: dataValue.length,
- ...(successValue !== undefined ? { success: successValue } : {}),
- ...(errorValue !== undefined ? { error: errorValue } : {}),
- };
- }
- if (dataValue !== undefined || successValue !== undefined || errorValue !== undefined) {
- return {
- ...(successValue !== undefined ? { success: successValue } : {}),
- ...(errorValue !== undefined ? { error: errorValue } : {}),
- ...(dataValue !== undefined ? { result: dataValue } : {}),
- };
- }
- return undefined;
-}
-
-function tryParseStructuredText(value: string): unknown {
- const trimmed = value.trim();
- if (!trimmed) {
- return value;
- }
- const wrapped = parseProtocolWrapper(trimmed);
- if (wrapped !== undefined) {
- return wrapped;
- }
- if (!["{", "["].includes(trimmed[0] ?? "")) {
- return value;
- }
- try {
- return JSON.parse(trimmed);
- } catch {
- try {
- return JSON.parse(normalizePythonLiteralToJson(trimmed));
- } catch {
- return value;
- }
- }
-}
-
-function isPlainObject(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
-}
-
-function isPrimitive(value: unknown): value is string | number | boolean | null {
- return (
- value === null ||
- typeof value === "string" ||
- typeof value === "number" ||
- typeof value === "boolean"
- );
-}
-
-function formatLeafValue(value: unknown): string {
- if (value === null) return "null";
- if (typeof value === "string") {
- const compact = value.replace(/\s+/g, " ").trim();
- return compact ? summarize(compact, 96) : '""';
- }
- if (typeof value === "number" || typeof value === "boolean") {
- return String(value);
- }
- return summarize(JSON.stringify(value), 96);
-}
-
-function formatStructuredValue(
- value: unknown,
- maxLines: number,
- maxDepth: number,
-): { lines: string[]; truncated: number } {
- const output: string[] = [];
-
- const append = (line: string): boolean => {
- if (output.length >= maxLines) {
- return false;
- }
- output.push(line);
- return true;
- };
-
- const visit = (current: unknown, indent: string, label?: string, depth = 0): void => {
- if (output.length >= maxLines) return;
- const parsed = typeof current === "string" ? tryParseStructuredText(current) : current;
-
- if (isPrimitive(parsed)) {
- if (typeof parsed === "string" && parsed.includes("\n")) {
- const compactLines = parsed
- .split("\n")
- .map((line) => line.trimEnd())
- .filter((line) => line.length > 0);
- if (label) {
- if (!append(`${indent}${label}:`)) return;
- }
- const visible = compactLines.slice(0, Math.max(1, maxLines - output.length));
- for (const line of visible) {
- if (!append(`${indent} ${summarize(line, 96)}`)) return;
- }
- return;
- }
- append(`${indent}${label ? `${label}: ` : ""}${formatLeafValue(parsed)}`);
- return;
- }
-
- if (depth >= maxDepth) {
- append(`${indent}${label ? `${label}: ` : ""}${Array.isArray(parsed) ? "[…]" : "{…}"}`);
- return;
- }
-
- if (Array.isArray(parsed)) {
- if (label) {
- if (!append(`${indent}${label}:`)) return;
- }
- if (parsed.length === 0) {
- append(`${indent}${label ? " " : ""}[]`);
- return;
- }
- const childIndent = indent + (label ? " " : "");
- for (const item of parsed) {
- if (output.length >= maxLines) return;
- if (isPrimitive(item)) {
- append(`${childIndent}- ${formatLeafValue(item)}`);
- continue;
- }
- if (!append(`${childIndent}-`)) return;
- visit(item, `${childIndent} `, undefined, depth + 1);
- }
- return;
- }
-
- if (isPlainObject(parsed)) {
- const entries = Object.entries(parsed).filter(([, item]) => item !== undefined);
- if (label) {
- if (!append(`${indent}${label}:`)) return;
- }
- if (entries.length === 0) {
- append(`${indent}${label ? " " : ""}{}`);
- return;
- }
- const childIndent = indent + (label ? " " : "");
- for (const [key, item] of entries) {
- visit(item, childIndent, key, depth + 1);
- if (output.length >= maxLines) return;
- }
- return;
- }
-
- append(`${indent}${label ? `${label}: ` : ""}${summarize(String(parsed), 96)}`);
- };
-
- visit(value, "");
- const truncated = Math.max(0, output.length - maxLines);
- return { lines: output.slice(0, maxLines), truncated };
-}
-
-function summarizeStructuredPayload(value: string): string | undefined {
- const parsed = tryParseStructuredText(value);
- if (Array.isArray(parsed)) {
- return `${parsed.length} item${parsed.length === 1 ? "" : "s"}`;
- }
- if (isPlainObject(parsed)) {
- const keys = Object.keys(parsed);
- return `${keys.length} field${keys.length === 1 ? "" : "s"}`;
- }
- return undefined;
-}
-
-function summarizeToolArguments(name: string, args: unknown): string | undefined {
- if (!args || typeof args !== "object") {
- return typeof args === "string" ? summarize(args, 72) : undefined;
- }
- const obj = args as Record<string, unknown>;
- const normalized = name.toLowerCase();
- if (normalized.includes("read") || normalized.includes("view")) {
- return summarizePath(obj.path ?? obj.file_path ?? obj.file);
- }
- if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) {
- return summarizePath(obj.path ?? obj.file_path ?? obj.file) ?? "content change";
- }
- if (normalized.includes("search") || normalized.includes("grep") || normalized.includes("glob")) {
- const pattern =
- typeof obj.pattern === "string"
- ? obj.pattern
- : typeof obj.query === "string"
- ? obj.query
- : undefined;
- const root = summarizePath(obj.path ?? obj.cwd ?? obj.root);
- return [pattern, root].filter(Boolean).join(" in ") || undefined;
- }
- if (
- normalized.includes("exec") ||
- normalized.includes("bash") ||
- normalized.includes("shell") ||
- normalized.includes("command")
- ) {
- return typeof obj.cmd === "string"
- ? summarize(obj.cmd, 72)
- : typeof obj.command === "string"
- ? summarize(obj.command, 72)
- : undefined;
- }
- if (typeof obj.path === "string") {
- return summarizePath(obj.path);
- }
- const keys = Object.keys(obj).filter((key) => obj[key] !== undefined);
- return keys.length > 0 ? `${keys.length} field${keys.length === 1 ? "" : "s"}` : undefined;
-}
-
-export function summarizeToolResultByKind(name: string, result: string): string | undefined {
- const normalized = name.toLowerCase();
- const lines = result.split("\n").filter(Boolean).length;
- if (normalized.includes("read") || normalized.includes("view")) return `${lines} lines loaded`;
- if (normalized.includes("search") || normalized.includes("grep")) return `${lines} matches`;
- if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch"))
- return "edit applied";
- if (
- normalized.includes("exec") ||
- normalized.includes("bash") ||
- normalized.includes("shell") ||
- normalized.includes("command")
- ) {
- return summarize(result.split("\n")[0] ?? "", 88);
- }
- return summarizeStructuredPayload(result);
-}
-
-function countLogicalLines(text: string): number {
- if (!text) return 0;
- return text.split("\n").length;
-}
-
-function isCodeLikePath(path: string | undefined): boolean {
- if (!path) return false;
- return /\.(ts|tsx|js|jsx|py|rs|go|java|c|cc|cpp|h|hpp|json|yaml|yml|toml|md|sh|sql|css|scss|html)$/i.test(
- path,
- );
-}
-
-function getToolFilePath(args: Record<string, unknown>): string | undefined {
- const value = args.path ?? args.file_path ?? args.file ?? args.dir_path;
- return typeof value === "string" && value ? (summarizePath(value) ?? value) : undefined;
-}
-
-function getStringArg(args: Record<string, unknown>, ...keys: string[]): string | undefined {
- for (const key of keys) {
- const value = args[key];
- if (typeof value === "string" && value.trim()) {
- return value;
- }
- }
- return undefined;
-}
-
-function getNumericArg(args: Record<string, unknown>, ...keys: string[]): number | undefined {
- for (const key of keys) {
- const value = args[key];
- if (typeof value === "number" && Number.isFinite(value)) {
- return value;
- }
- }
- return undefined;
-}
-
-function isReadTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return normalized === "read" || normalized === "read_file";
-}
-
-function isListTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return normalized === "ls" || normalized === "list_files";
-}
-
-function isWriteTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return normalized === "write" || normalized === "write_file";
-}
-
-function isEditTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return normalized === "edit" || normalized === "edit_file";
-}
-
-function isRunTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return (
- normalized === "bash" ||
- normalized === "shell" ||
- normalized === "sh" ||
- normalized === "powershell" ||
- normalized === "command" ||
- normalized === "exec" ||
- normalized === "run"
- );
-}
-
-function isGlobTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return normalized === "glob" || normalized === "glob_files";
-}
-
-function isSearchTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return (
- normalized === "search" ||
- normalized === "grep" ||
- normalized === "rg" ||
- normalized === "ripgrep" ||
- normalized === "memory_search"
- );
-}
-
-function isMcpTool(name: string): boolean {
- const normalized = name.toLowerCase();
- return normalized.startsWith("mcp_") || normalized.startsWith("mcp.");
-}
-
-function isToolRunning(tool: ToolCallDisplay): boolean {
- return tool.status === "running" && !tool.result;
-}
-
-function toolPrefix(tool: ToolCallDisplay): string {
- if (tool.isError || tool.status === "error") return "! ";
- if (isToolRunning(tool)) return "◉ ";
- return "● ";
-}
-
-function toolPrefixColor(tool: ToolCallDisplay): (value: string) => string {
- if (tool.isError || tool.status === "error") return palette.status.error;
- if (isToolRunning(tool)) return palette.text.tool;
- return palette.status.success;
-}
-
-function toolLineColor(tool: ToolCallDisplay): (value: string) => string {
- if (tool.isError || tool.status === "error") return palette.status.error;
- if (isToolRunning(tool)) return palette.text.tool;
- return palette.text.assistant;
-}
-
-function toolStateColor(tool: ToolCallDisplay): (value: string) => string {
- if (tool.isError || tool.status === "error") return palette.status.error;
- if (isToolRunning(tool)) return palette.text.tool;
- return palette.status.success;
-}
-
-function renderToolTitle(width: number, tool: ToolCallDisplay, text: string): string[] {
- return prefixedLines(
- renderWrappedText(Math.max(1, width - 2), text, toolLineColor(tool)),
- width,
- toolPrefix(tool),
- toolPrefixColor(tool),
- " ",
- );
-}
-
-function renderToolBranch(
- width: number,
- text: string,
- colorFn: (value: string) => string,
-): string[] {
- return prefixedLines(
- renderWrappedText(Math.max(1, width - 2), text, colorFn),
- width,
- TOOL_BODY_PREFIX,
- palette.text.subtle,
- TOOL_BODY_CONTINUATION,
- );
-}
-
-function renderToolBranchAnsi(width: number, text: string): string[] {
- return renderToolBranch(width, text, (value) => value);
-}
-
-function renderToolTail(width: number, text: string, colorFn: (value: string) => string): string[] {
- return prefixedLines(
- renderWrappedText(Math.max(1, width - 2), text, colorFn),
- width,
- TOOL_TAIL_PREFIX,
- palette.text.subtle,
- TOOL_TAIL_CONTINUATION,
- );
-}
-
-function renderDiffRow(
- width: number,
- sign: " " | "+" | "-",
- text: string,
- colorFn: (value: string) => string,
-): string[] {
- return renderWrappedText(width, `${sign} ${text}`, colorFn);
-}
-
-function renderSimpleDiff(width: number, beforeText: string, afterText: string): string[] {
- const beforeLines = beforeText.split("\n");
- const afterLines = afterText.split("\n");
- const total = Math.max(beforeLines.length, afterLines.length);
- const lines: string[] = [];
- for (let i = 0; i < total; i += 1) {
- const before = beforeLines[i];
- const after = afterLines[i];
- if (before === after && before !== undefined) {
- lines.push(...renderDiffRow(width, " ", before, palette.diff.context));
- continue;
- }
- if (before !== undefined) {
- lines.push(...renderDiffRow(width, "-", before, palette.diff.remove));
- }
- if (after !== undefined) {
- lines.push(...renderDiffRow(width, "+", after, palette.diff.add));
- }
- }
- return lines;
-}
-
-function renderAddedLines(width: number, text: string): string[] {
- return text
- .split("\n")
- .filter((line) => line.length > 0)
- .flatMap((line) => renderDiffRow(width, "+", line, palette.diff.add));
-}
-
-function extractTrailingBracketNotices(text: string): { mainLines: string[]; notices: string[] } {
- const lines = text.split("\n");
- const notices: string[] = [];
- let end = lines.length;
- while (end > 0) {
- const current = lines[end - 1]?.trim() ?? "";
- if (current.startsWith("[") && current.endsWith("]")) {
- notices.unshift(current);
- end -= 1;
- continue;
- }
- break;
- }
- return {
- mainLines: lines.slice(0, end).filter((line) => line.length > 0),
- notices,
- };
-}
-
-function toolDisplayName(tool: ToolCallDisplay): string {
- const name = tool.name.toLowerCase();
- if (name in { bash: true, shell: true, sh: true, powershell: true, command: true, exec: true }) {
- return "Run";
- }
- if (name in { glob: true, glob_files: true }) {
- return "Glob";
- }
- if (name.startsWith("mcp_")) {
- return `Query ${name
- .split("_")
- .slice(1)
- .filter(Boolean)
- .map((part) => part[0]?.toUpperCase() + part.slice(1))
- .join(" ")}`;
- }
- if (name.startsWith("mcp.")) {
- return `Query ${name
- .split(".")
- .slice(1)
- .filter(Boolean)
- .map((part) => part[0]?.toUpperCase() + part.slice(1))
- .join(" ")}`;
- }
- if (name in { read: true, read_file: true, read_memory: true, memory_get: true, view: true }) {
- return "Read";
- }
- if (name in { ls: true, list_files: true }) {
- return "List";
- }
- if (name === "memory_search") {
- return "Search memories";
- }
- if (name in { write: true, write_file: true, write_memory: true }) {
- return "Write";
- }
- if (name in { edit: true, edit_file: true, edit_memory: true }) {
- return "Edit";
- }
- if (name === "session") {
- return "Run session";
- }
- return tool.name
- .split(/[_\-.]+/)
- .filter(Boolean)
- .map((part) => part[0]?.toUpperCase() + part.slice(1))
- .join(" ");
-}
-
-function renderStructuredBranch(
- width: number,
- value: unknown,
- showDetails: boolean,
- colorFn: (value: string) => string,
-): string[] {
- const maxLines = showDetails ? MAX_STRUCTURED_LINES_EXPANDED : MAX_STRUCTURED_LINES_COLLAPSED;
- const { lines } = formatStructuredValue(value, maxLines, showDetails ? 4 : 2);
- return lines.flatMap((line) => renderToolBranch(width, line, colorFn));
-}
-
-function renderSearchMatchBranch(width: number, line: string): string[] {
- const trimmed = line.trim();
- const match = /^(.+?):(\d+)(?::(\d+))?(?:(:|\s+-\s+|\s+)(.*))?$/.exec(trimmed);
- if (!match) {
- return renderToolBranch(width, line, palette.text.assistant);
- }
- const [, filePath, lineNumber, columnNumber, separatorRaw, remainderRaw] = match;
- if (!filePath || (!filePath.includes("/") && !filePath.includes("."))) {
- return renderToolBranch(width, line, palette.text.assistant);
- }
- const separator = separatorRaw ?? "";
- const remainder = remainderRaw ?? "";
- const location = `${filePath}:${lineNumber}${columnNumber ? `:${columnNumber}` : ""}`;
- const formatted = `${palette.text.tool(filePath)}${palette.text.dim(`:${lineNumber}${columnNumber ? `:${columnNumber}` : ""}`)}${separator}${remainder ? palette.text.assistant(remainder) : ""}`;
- return renderToolBranchAnsi(width, formatted || location);
-}
-
-function parseToolResultPayload(tool: ToolCallDisplay): Record<string, unknown> | undefined {
- if (!tool.result) return undefined;
- const parsed = tryParseStructuredText(tool.result);
- return isPlainObject(parsed) ? parsed : undefined;
-}
-
-function parseToolResultValue(tool: ToolCallDisplay): unknown {
- if (!tool.result) return undefined;
- return tryParseStructuredText(tool.result);
-}
-
-function getStringList(payload: Record<string, unknown>, ...keys: string[]): string[] {
- for (const key of keys) {
- const value = payload[key];
- if (Array.isArray(value)) {
- const list = value.filter(
- (item): item is string => typeof item === "string" && item.length > 0,
- );
- if (list.length > 0) {
- return list;
- }
- }
- }
- return [];
-}
-
-function getStringListFromValue(value: unknown): string[] {
- if (!Array.isArray(value)) {
- return [];
- }
- return value.filter((item): item is string => typeof item === "string" && item.length > 0);
-}
-
-function nonEmptyLines(value: unknown): string[] {
- if (typeof value !== "string") return [];
- return value
- .split("\n")
- .map((line) => line.trimEnd())
- .filter((line) => line.trim().length > 0);
-}
-
-function renderPreviewLines(
- width: number,
- lines: string[],
- colorFn: (value: string) => string,
- expandedLimit: number,
- collapsedLimit: number,
- showDetails: boolean,
- noun: string,
-): string[] {
- const limit = showDetails ? expandedLimit : collapsedLimit;
- const shown = lines.slice(0, limit);
- const rendered = shown.flatMap((line) => renderToolBranch(width, line, colorFn));
- if (lines.length > shown.length) {
- rendered.push(
- ...renderToolBranch(width, `+ ${lines.length - shown.length} more ${noun}`, palette.text.dim),
- );
- }
- if (!showDetails && lines.length > 0) {
- rendered.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- return rendered;
-}
+import type { HistoryItem } from "../../../core/types.js";
+import { renderCompactToolLines } from "./compact-tool-renderers.js";
+import { renderDetailedToolLines } from "./detailed-tool-renderers.js";
export class ToolGroupMessageComponent implements Component {
constructor(
private readonly entry: Extract<HistoryItem, { kind: "tool_group" }>,
private readonly collapsed: boolean,
private readonly showDetails: boolean,
+ private readonly animationPhase: number,
) {}
invalidate(): void {}
- private renderSessionTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const description =
- typeof args.description === "string" && args.description
- ? args.description
- : (tool.description ?? "session task");
- const index = typeof args.index === "number" ? args.index : undefined;
- const total = typeof args.total === "number" ? args.total : undefined;
- const label =
- index !== undefined && total !== undefined
- ? `Run session ${index}/${total} · ${description}`
- : `Run session · ${description}`;
- const lines = renderToolTitle(width, tool, label);
-
- if (tool.result) {
- const previewLines = tool.result.split("\n").filter(Boolean);
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ??
- summarizeToolResultByKind(tool.name, tool.result) ??
- summarize(tool.result, 120),
- toolStateColor(tool),
- ),
- );
- if (this.showDetails) {
- for (const line of previewLines.slice(0, 6)) {
- lines.push(...renderToolBranch(width, line, palette.text.assistant));
- }
- if (previewLines.length > 6) {
- lines.push(
- ...renderToolBranch(width, `+ ${previewLines.length - 6} more lines`, palette.text.dim),
- );
- }
- } else if (previewLines.length > 0) {
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- }
-
- return lines;
- }
-
- private renderReadTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const payload = parseToolResultPayload(tool);
- const path = getToolFilePath(args) ?? getStringArg(payload ?? {}, "path", "file_path", "file");
- const offset = typeof args.offset === "number" ? args.offset : undefined;
- const limit = typeof args.limit === "number" ? args.limit : undefined;
- const rangeSuffix =
- offset !== undefined || limit !== undefined
- ? `:${offset ?? 1}${limit !== undefined ? `-${(offset ?? 1) + limit - 1}` : ""}`
- : "";
- const lines = renderToolTitle(
- width,
- tool,
- `Read ${path ?? tool.description ?? tool.name}${rangeSuffix}`,
- );
-
- if (tool.result) {
- const content = getStringArg(payload ?? {}, "content", "result", "data") ?? tool.result;
- const { mainLines, notices } = extractTrailingBracketNotices(content);
- const totalLines =
- getNumericArg(payload ?? {}, "totalLines", "total_lines") ?? countLogicalLines(content);
- const startLine = getNumericArg(payload ?? {}, "start_line", "startLine");
- const endLine = getNumericArg(payload ?? {}, "end_line", "endLine");
- const truncated = typeof payload?.truncated === "boolean" ? payload.truncated : undefined;
- if (path) {
- const lineRange =
- startLine !== undefined && endLine !== undefined ? ` · ${startLine}-${endLine}` : "";
- const meta = `${totalLines} lines${lineRange}${isCodeLikePath(path) ? " · code" : ""}`;
- lines.push(...renderToolBranch(width, meta, palette.text.dim));
- }
- if (this.showDetails) {
- for (const line of mainLines.slice(0, 10)) {
- lines.push(...renderToolBranch(width, line, palette.text.assistant));
- }
- if (mainLines.length > 10) {
- lines.push(
- ...renderToolBranch(width, `+ ${mainLines.length - 10} more lines`, palette.text.dim),
- );
- }
- } else {
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- if (truncated) {
- lines.push(...renderToolBranch(width, "result truncated", palette.status.warning));
- }
- for (const notice of notices) {
- lines.push(...renderToolBranch(width, notice, palette.status.warning));
- }
- }
-
- return lines;
- }
-
- private renderListTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const path = getToolFilePath(args) ?? ".";
- const limit = typeof args.limit === "number" ? args.limit : undefined;
- const lines = renderToolTitle(
- width,
- tool,
- `List ${path}${limit !== undefined ? ` (limit ${limit})` : ""}`,
- );
-
- if (tool.result) {
- const payload = parseToolResultPayload(tool);
- const files = getStringList(payload ?? {}, "files");
- const dirs = getStringList(payload ?? {}, "dirs").map((dir) => `${dir}/`);
- const payloadEntries = [...files, ...dirs];
- const { mainLines, notices } = extractTrailingBracketNotices(tool.result);
- const visibleEntries = payloadEntries.length > 0 ? payloadEntries : mainLines;
- const shown = visibleEntries.slice(0, this.showDetails ? 12 : 6);
- lines.push(
- ...renderToolTail(
- width,
- `${visibleEntries.length} entr${visibleEntries.length === 1 ? "y" : "ies"}`,
- palette.text.dim,
- ),
- );
- for (const entry of shown) {
- lines.push(...renderToolBranch(width, entry, palette.text.assistant));
- }
- if (visibleEntries.length > shown.length) {
- lines.push(
- ...renderToolBranch(
- width,
- `+ ${visibleEntries.length - shown.length} more entries`,
- palette.text.dim,
- ),
- );
- }
- if (!this.showDetails && visibleEntries.length > 0) {
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- for (const notice of notices) {
- lines.push(...renderToolBranch(width, notice, palette.status.warning));
- }
- }
-
- return lines;
- }
-
- private renderWriteTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const path = getToolFilePath(args);
- const content = typeof args.content === "string" ? args.content : "";
- const lines = renderToolTitle(width, tool, `Write ${path ?? tool.description ?? tool.name}`);
-
- if (content) {
- lines.push(
- ...renderToolBranch(
- width,
- `${countLogicalLines(content)} lines · ${content.length} chars`,
- palette.text.dim,
- ),
- );
- const diffLines = renderAddedLines(Math.max(1, width - 2), content);
- const shown = this.showDetails ? diffLines : diffLines.slice(0, 6);
- lines.push(...shown.flatMap((line) => renderToolBranch(width, line, (value) => value)));
- if (!this.showDetails && diffLines.length > shown.length) {
- lines.push(
- ...renderToolBranch(
- width,
- `+ ${diffLines.length - shown.length} more diff lines`,
- palette.text.dim,
- ),
- );
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- }
-
- if (tool.result) {
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ??
- summarizeToolResultByKind(tool.name, tool.result) ??
- summarize(tool.result, 120),
- toolStateColor(tool),
- ),
- );
- }
-
- return lines;
- }
-
- private renderEditTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const path = getToolFilePath(args);
- const lines = renderToolTitle(width, tool, `Edit ${path ?? tool.description ?? tool.name}`);
-
- const oldString =
- typeof args.old_string === "string"
- ? args.old_string
- : typeof args.oldText === "string"
- ? args.oldText
- : undefined;
- const newString =
- typeof args.new_string === "string"
- ? args.new_string
- : typeof args.newText === "string"
- ? args.newText
- : undefined;
-
- if (oldString !== undefined && newString !== undefined) {
- const diffLines = renderSimpleDiff(Math.max(1, width - 2), oldString, newString);
- const shown = this.showDetails ? diffLines : diffLines.slice(0, 6);
- lines.push(...shown.flatMap((line) => renderToolBranch(width, line, (value) => value)));
- if (!this.showDetails && diffLines.length > shown.length) {
- lines.push(
- ...renderToolBranch(
- width,
- `+ ${diffLines.length - shown.length} more diff lines`,
- palette.text.dim,
- ),
- );
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- } else if (Array.isArray(args.edits)) {
- lines.push(...renderToolTail(width, `${args.edits.length} edit block(s)`, palette.text.dim));
- const shownEdits = args.edits.slice(0, this.showDetails ? 3 : 1);
- for (const edit of shownEdits) {
- if (!isPlainObject(edit)) continue;
- const before =
- typeof edit.oldText === "string"
- ? edit.oldText
- : typeof edit.old_string === "string"
- ? edit.old_string
- : "";
- const after =
- typeof edit.newText === "string"
- ? edit.newText
- : typeof edit.new_string === "string"
- ? edit.new_string
- : "";
- if (!before && !after) continue;
- const diffLines = renderSimpleDiff(Math.max(1, width - 2), before, after);
- lines.push(
- ...diffLines
- .slice(0, this.showDetails ? 6 : 2)
- .flatMap((line) => renderToolBranch(width, line, (value) => value)),
- );
- }
- if (args.edits.length > shownEdits.length) {
- lines.push(
- ...renderToolBranch(
- width,
- `+ ${args.edits.length - shownEdits.length} more edit blocks`,
- palette.text.dim,
- ),
- );
- }
- if (!this.showDetails && args.edits.length > 0) {
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- }
-
- if (tool.result) {
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ??
- summarizeToolResultByKind(tool.name, tool.result) ??
- summarize(tool.result, 120),
- toolStateColor(tool),
- ),
- );
- }
-
- return lines;
- }
-
- private renderRunTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const payload = parseToolResultPayload(tool);
- const command =
- getStringArg(args, "command", "cmd", "script", "input") ??
- getStringArg(payload ?? {}, "command", "cmd") ??
- tool.description ??
- tool.name;
- const lines = renderToolTitle(width, tool, `Run ${summarize(command, 120)}`);
-
- const cwd = getStringArg(args, "cwd", "path", "workdir");
- if (cwd) {
- lines.push(...renderToolBranch(width, `cwd: ${summarizePath(cwd) ?? cwd}`, palette.text.dim));
- }
-
- if (tool.result) {
- const exitCode =
- getNumericArg(payload ?? {}, "exit_code", "exitCode", "code") ??
- getNumericArg(args, "exit_code", "exitCode", "code");
- const stdoutLines =
- nonEmptyLines(payload?.stdout) ||
- nonEmptyLines(payload?.output) ||
- nonEmptyLines(payload?.content) ||
- nonEmptyLines(payload?.result);
- const stderrLines = nonEmptyLines(payload?.stderr);
-
- const summaryParts: string[] = [];
- if (exitCode !== undefined) {
- summaryParts.push(`exit ${exitCode}`);
- }
- if (stdoutLines.length > 0) {
- summaryParts.push(`${stdoutLines.length} line${stdoutLines.length === 1 ? "" : "s"}`);
- } else if (stderrLines.length > 0) {
- summaryParts.push(
- `${stderrLines.length} stderr line${stderrLines.length === 1 ? "" : "s"}`,
- );
- }
-
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ?? (summaryParts.join(" | ") || summarize(tool.result, 120)),
- toolStateColor(tool),
- ),
- );
-
- if (stdoutLines.length > 0 || stderrLines.length > 0) {
- lines.push(
- ...renderPreviewLines(
- width,
- stdoutLines,
- palette.text.assistant,
- 8,
- 4,
- this.showDetails,
- "lines",
- ),
- );
- lines.push(
- ...renderPreviewLines(
- width,
- stderrLines,
- palette.status.warning,
- 8,
- 2,
- this.showDetails,
- "stderr lines",
- ),
- );
- } else if (payload && this.showDetails) {
- lines.push(
- ...renderStructuredBranch(
- width,
- payload,
- this.showDetails,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- } else if (!payload && this.showDetails) {
- lines.push(
- ...renderPreviewLines(
- width,
- nonEmptyLines(tool.result),
- tool.isError ? palette.status.error : palette.text.assistant,
- 8,
- 4,
- this.showDetails,
- "lines",
- ),
- );
- }
- }
-
- return lines;
- }
-
- private renderGlobTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const payload = parseToolResultPayload(tool);
- const parsedValue = parseToolResultValue(tool);
- const pattern =
- getStringArg(args, "glob", "pattern", "path", "file_path") ??
- getStringArg(payload ?? {}, "glob", "pattern") ??
- tool.description ??
- tool.name;
- const lines = renderToolTitle(width, tool, `Glob ${summarize(pattern, 120)}`);
- const root = getStringArg(args, "root", "cwd", "dir_path");
- if (root) {
- lines.push(
- ...renderToolBranch(width, `root: ${summarizePath(root) ?? root}`, palette.text.dim),
- );
- }
-
- if (tool.result) {
- const payloadMatchLines = getStringList(payload ?? {}, "matching_files", "files");
- const valueMatchLines = getStringListFromValue(parsedValue);
- const matchLines = payloadMatchLines.length > 0 ? payloadMatchLines : valueMatchLines;
- const count = getNumericArg(payload ?? {}, "count") ?? matchLines.length;
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ?? `${count} file${count === 1 ? "" : "s"}`,
- toolStateColor(tool),
- ),
- );
- if (matchLines.length > 0) {
- lines.push(
- ...renderPreviewLines(
- width,
- matchLines,
- palette.text.assistant,
- 8,
- 4,
- this.showDetails,
- "files",
- ),
- );
- } else if (payload && this.showDetails) {
- lines.push(
- ...renderStructuredBranch(width, payload, this.showDetails, palette.text.assistant),
- );
- } else if (parsedValue !== undefined && this.showDetails) {
- lines.push(
- ...renderStructuredBranch(width, parsedValue, this.showDetails, palette.text.assistant),
- );
- }
- }
-
- return lines;
- }
-
- private renderSearchTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const payload = parseToolResultPayload(tool);
- const parsedValue = parseToolResultValue(tool);
- const query =
- getStringArg(args, "pattern", "query", "q", "prompt", "glob") ??
- getStringArg(payload ?? {}, "pattern", "query", "q") ??
- tool.description ??
- tool.name;
- const root =
- getStringArg(args, "path", "cwd", "root", "dir_path") ??
- getStringArg(payload ?? {}, "path", "cwd", "root");
- const title = root
- ? `Search ${summarize(query, 96)} in ${summarizePath(root) ?? root}`
- : `Search ${summarize(query, 120)}`;
- const lines = renderToolTitle(width, tool, title);
-
- if (tool.result) {
- const payloadResultLines = getStringList(
- payload ?? {},
- "matches",
- "results",
- "items",
- "hits",
- "files",
- );
- const valueResultLines = getStringListFromValue(parsedValue);
- const resultLines = payloadResultLines.length > 0 ? payloadResultLines : valueResultLines;
- const fallbackLines = nonEmptyLines(tool.result);
- const visibleLines = resultLines.length > 0 ? resultLines : fallbackLines;
- const count =
- getNumericArg(payload ?? {}, "count", "match_count", "matches_count", "total") ??
- visibleLines.length;
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ?? `${count} match${count === 1 ? "" : "es"}`,
- toolStateColor(tool),
- ),
- );
- if (visibleLines.length > 0) {
- const limit = this.showDetails ? 8 : 4;
- const shown = visibleLines.slice(0, limit);
- for (const line of shown) {
- lines.push(
- ...(tool.isError
- ? renderToolBranch(width, line, palette.status.error)
- : renderSearchMatchBranch(width, line)),
- );
- }
- if (visibleLines.length > shown.length) {
- lines.push(
- ...renderToolBranch(
- width,
- `+ ${visibleLines.length - shown.length} more matches`,
- palette.text.dim,
- ),
- );
- }
- if (!this.showDetails && visibleLines.length > 0) {
- lines.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
- }
- } else if (payload && this.showDetails) {
- lines.push(
- ...renderStructuredBranch(
- width,
- payload,
- this.showDetails,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- } else if (parsedValue !== undefined && this.showDetails) {
- lines.push(
- ...renderStructuredBranch(
- width,
- parsedValue,
- this.showDetails,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- }
- }
-
- return lines;
- }
-
- private renderMcpTool(tool: ToolCallDisplay, width: number): string[] {
- const args =
- tool.arguments && typeof tool.arguments === "object"
- ? (tool.arguments as Record<string, unknown>)
- : {};
- const title = toolDisplayName(tool);
- const detail =
- getStringArg(args, "query", "q", "prompt", "url", "path", "file_path", "file") ??
- tool.description ??
- summarizeToolArguments(tool.name, args);
- const lines = renderToolTitle(
- width,
- tool,
- `${title}${detail ? ` · ${summarize(detail, 120)}` : ""}`,
- );
-
- if (isPlainObject(tool.arguments)) {
- lines.push(
- ...renderStructuredBranch(width, tool.arguments, this.showDetails, palette.text.dim),
- );
- }
-
- if (tool.result) {
- const payload = parseToolResultPayload(tool);
- const parsedValue = parseToolResultValue(tool);
- lines.push(
- ...renderToolTail(
- width,
- tool.summary ??
- summarizeToolResultByKind(tool.name, tool.result) ??
- summarize(tool.result, 120),
- toolStateColor(tool),
- ),
- );
- if (payload) {
- lines.push(
- ...renderStructuredBranch(
- width,
- payload,
- this.showDetails,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- } else if (parsedValue !== undefined && this.showDetails) {
- lines.push(
- ...renderStructuredBranch(
- width,
- parsedValue,
- this.showDetails,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- } else if (this.showDetails) {
- lines.push(
- ...renderPreviewLines(
- width,
- nonEmptyLines(tool.result),
- tool.isError ? palette.status.error : palette.text.assistant,
- 8,
- 4,
- this.showDetails,
- "lines",
- ),
- );
- }
- }
-
- return lines;
- }
-
- private renderGenericTool(tool: ToolCallDisplay, width: number): string[] {
- const title = toolDisplayName(tool);
- const detail = tool.description ?? summarizeToolArguments(tool.name, tool.arguments);
- const separator = title.startsWith("Query ") ? " · " : " ";
- const lines = renderToolTitle(width, tool, `${title}${detail ? `${separator}${detail}` : ""}`);
-
- if (isPlainObject(tool.arguments)) {
- const structuredArgs = renderStructuredBranch(
- width,
- tool.arguments,
- this.showDetails,
- palette.text.dim,
- );
- lines.push(...structuredArgs);
- }
-
- if (tool.result) {
- const summary =
- tool.summary ??
- summarizeToolResultByKind(tool.name, tool.result) ??
- summarize(tool.result, 120);
- lines.push(...renderToolTail(width, summary, toolStateColor(tool)));
-
- const parsedResult = tryParseStructuredText(tool.result);
- if (parsedResult !== tool.result) {
- lines.push(
- ...renderStructuredBranch(
- width,
- parsedResult,
- this.showDetails,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- } else if (this.showDetails) {
- const previewLines = tool.result.split("\n").filter(Boolean);
- const shown = previewLines.slice(0, tool.isError ? 2 : 4);
- for (const line of shown) {
- lines.push(
- ...renderToolBranch(
- width,
- line,
- tool.isError ? palette.status.error : palette.text.assistant,
- ),
- );
- }
- if (previewLines.length > shown.length) {
- lines.push(
- ...renderToolBranch(
- width,
- `+ ${previewLines.length - shown.length} more lines`,
- palette.text.dim,
- ),
- );
- }
- }
- }
-
- return lines;
- }
-
render(width: number): string[] {
const lines: string[] = [];
const tools = this.collapsed ? this.entry.tools.slice(-1) : this.entry.tools;
- for (const tool of tools) {
- if (tool.name === "session") {
- lines.push(...this.renderSessionTool(tool, width));
- continue;
- }
- if (isReadTool(tool.name)) {
- lines.push(...this.renderReadTool(tool, width));
- continue;
- }
- if (isListTool(tool.name)) {
- lines.push(...this.renderListTool(tool, width));
- continue;
- }
- if (isWriteTool(tool.name)) {
- lines.push(...this.renderWriteTool(tool, width));
- continue;
- }
- if (isEditTool(tool.name)) {
- lines.push(...this.renderEditTool(tool, width));
- continue;
- }
- if (isRunTool(tool.name)) {
- lines.push(...this.renderRunTool(tool, width));
- continue;
- }
- if (isGlobTool(tool.name)) {
- lines.push(...this.renderGlobTool(tool, width));
- continue;
- }
- if (isSearchTool(tool.name)) {
- lines.push(...this.renderSearchTool(tool, width));
- continue;
- }
- if (isMcpTool(tool.name)) {
- lines.push(...this.renderMcpTool(tool, width));
- continue;
+ for (const [index, tool] of tools.entries()) {
+ lines.push(
+ ...(this.showDetails
+ ? renderDetailedToolLines(tool, width, {
+ showDetails: this.showDetails,
+ animationPhase: this.animationPhase,
+ })
+ : renderCompactToolLines(tool, width, this.animationPhase)),
+ );
+
+ if (this.showDetails && index < tools.length - 1) {
+ lines.push(" ".repeat(width));
}
- lines.push(...this.renderGenericTool(tool, width));
}
return lines;
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-kind-utils.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-kind-utils.ts
new file mode 100644
index 0000000000..8202ac0d61
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-kind-utils.ts
@@ -0,0 +1,226 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { summarize } from "../../rendering/text.js";
+
+export function summarizePath(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const parts = value.split(/[\\/]/).filter(Boolean);
+ return parts.slice(-3).join("/");
+}
+
+export function summarizeToolArguments(name: string, args: unknown): string | undefined {
+ if (!args || typeof args !== "object") {
+ return typeof args === "string" ? summarize(args, 72) : undefined;
+ }
+ const obj = args as Record<string, unknown>;
+ const normalized = name.toLowerCase();
+ if (normalized.includes("read") || normalized.includes("view")) {
+ return summarizePath(obj.path ?? obj.file_path ?? obj.file);
+ }
+ if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) {
+ return summarizePath(obj.path ?? obj.file_path ?? obj.file) ?? "content change";
+ }
+ if (normalized.includes("fetch") || normalized.includes("webpage")) {
+ return typeof obj.url === "string" ? summarize(obj.url, 72) : undefined;
+ }
+ if (normalized.includes("search") || normalized.includes("grep") || normalized.includes("glob")) {
+ const pattern =
+ typeof obj.pattern === "string"
+ ? obj.pattern
+ : typeof obj.query === "string"
+ ? obj.query
+ : undefined;
+ const root = summarizePath(obj.path ?? obj.cwd ?? obj.root);
+ return [pattern, root].filter(Boolean).join(" in ") || undefined;
+ }
+ if (
+ normalized.includes("exec") ||
+ normalized.includes("bash") ||
+ normalized.includes("shell") ||
+ normalized.includes("command")
+ ) {
+ return typeof obj.cmd === "string"
+ ? summarize(obj.cmd, 72)
+ : typeof obj.command === "string"
+ ? summarize(obj.command, 72)
+ : undefined;
+ }
+ if (typeof obj.path === "string") return summarizePath(obj.path);
+ const keys = Object.keys(obj).filter((key) => obj[key] !== undefined);
+ return keys.length > 0 ? `${keys.length} field${keys.length === 1 ? "" : "s"}` : undefined;
+}
+
+export function countLogicalLines(text: string): number {
+ if (!text) return 0;
+ return text.split("\n").length;
+}
+
+export function isCodeLikePath(path: string | undefined): boolean {
+ if (!path) return false;
+ return /\.(ts|tsx|js|jsx|py|rs|go|java|c|cc|cpp|h|hpp|json|yaml|yml|toml|md|sh|sql|css|scss|html)$/i.test(
+ path,
+ );
+}
+
+export function getToolFilePath(args: Record<string, unknown>): string | undefined {
+ const value = args.path ?? args.file_path ?? args.file ?? args.dir_path;
+ return typeof value === "string" && value ? (summarizePath(value) ?? value) : undefined;
+}
+
+export function getStringArg(args: Record<string, unknown>, ...keys: string[]): string | undefined {
+ for (const key of keys) {
+ const value = args[key];
+ if (typeof value === "string" && value.trim()) return value;
+ }
+ return undefined;
+}
+
+export function getNumericArg(
+ args: Record<string, unknown>,
+ ...keys: string[]
+): number | undefined {
+ for (const key of keys) {
+ const value = args[key];
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ }
+ return undefined;
+}
+
+export function isReadTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return (
+ normalized === "read" ||
+ normalized === "read_file" ||
+ normalized === "read_text_file" ||
+ normalized === "read_memory" ||
+ normalized === "memory_get" ||
+ normalized === "view"
+ );
+}
+
+export function isListTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized === "ls" || normalized === "list_files" || normalized === "list_dir";
+}
+
+export function isWriteTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return (
+ normalized === "write" ||
+ normalized === "write_file" ||
+ normalized === "write_text_file" ||
+ normalized === "write_memory"
+ );
+}
+
+export function isEditTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return (
+ normalized === "edit" ||
+ normalized === "edit_file" ||
+ normalized === "edit_memory" ||
+ normalized === "search_replace"
+ );
+}
+
+export function isRunTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return (
+ normalized === "bash" ||
+ normalized === "shell" ||
+ normalized === "sh" ||
+ normalized === "powershell" ||
+ normalized === "command" ||
+ normalized === "exec" ||
+ normalized === "run" ||
+ normalized === "mcp_exec_command" ||
+ normalized === "create_terminal"
+ );
+}
+
+export function isGlobTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized === "glob" || normalized === "glob_files" || normalized === "glob_file_search";
+}
+
+export function isSearchTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return (
+ normalized === "search" ||
+ normalized === "grep" ||
+ normalized === "rg" ||
+ normalized === "ripgrep" ||
+ normalized === "memory_search" ||
+ normalized === "mcp_free_search" ||
+ normalized === "mcp_paid_search"
+ );
+}
+
+export function isFetchTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return (
+ normalized === "fetch" || normalized === "fetch_webpage" || normalized === "mcp_fetch_webpage"
+ );
+}
+
+export function isMcpTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized.startsWith("mcp_") || normalized.startsWith("mcp.");
+}
+
+export function isToolRunning(tool: ToolCallDisplay): boolean {
+ return tool.status === "running" && !tool.result;
+}
+
+export function toolDisplayName(tool: ToolCallDisplay): string {
+ const name = tool.name.toLowerCase();
+ if (name in { bash: true, shell: true, sh: true, powershell: true, command: true, exec: true }) {
+ return "Run";
+ }
+ if (name in { mcp_exec_command: true, create_terminal: true }) return "Run";
+ if (name in { glob: true, glob_files: true, glob_file_search: true }) return "Glob";
+ if (name in { fetch: true, fetch_webpage: true, mcp_fetch_webpage: true }) return "Fetch";
+ if (name.startsWith("mcp_")) {
+ return `Query ${name
+ .split("_")
+ .slice(1)
+ .filter(Boolean)
+ .map((part) => part[0]?.toUpperCase() + part.slice(1))
+ .join(" ")}`;
+ }
+ if (name.startsWith("mcp.")) {
+ return `Query ${name
+ .split(".")
+ .slice(1)
+ .filter(Boolean)
+ .map((part) => part[0]?.toUpperCase() + part.slice(1))
+ .join(" ")}`;
+ }
+ if (
+ name in
+ {
+ read: true,
+ read_file: true,
+ read_memory: true,
+ memory_get: true,
+ view: true,
+ read_text_file: true,
+ }
+ ) {
+ return "Read";
+ }
+ if (name in { ls: true, list_files: true, list_dir: true }) return "List";
+ if (name === "memory_search") return "Search memories";
+ if (name in { mcp_free_search: true, mcp_paid_search: true }) return "Search web";
+ if (name in { write: true, write_file: true, write_memory: true, write_text_file: true }) {
+ return "Write";
+ }
+ if (name in { edit: true, edit_file: true, edit_memory: true, search_replace: true }) {
+ return "Edit";
+ }
+ if (name === "session") return "Run session";
+ return tool.name
+ .split(/[_\-.]+/)
+ .filter(Boolean)
+ .map((part) => part[0]?.toUpperCase() + part.slice(1))
+ .join(" ");
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-line-renderers.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-line-renderers.ts
new file mode 100644
index 0000000000..5d7ebd71c2
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-line-renderers.ts
@@ -0,0 +1,170 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import { prefixedLines, renderWrappedText } from "../../rendering/text.js";
+import { isToolRunning } from "./tool-kind-utils.js";
+import { formatStructuredValue } from "./tool-structured-data.js";
+
+const TOOL_BODY_PREFIX = " ⎿ ";
+const TOOL_BODY_CONTINUATION = " ";
+const TOOL_TAIL_PREFIX = " ⎿ ";
+const TOOL_TAIL_CONTINUATION = " ";
+export const TOOL_EXPAND_HINT = "ctrl+o to expand";
+const MAX_STRUCTURED_LINES_COLLAPSED = 6;
+const MAX_STRUCTURED_LINES_EXPANDED = 18;
+
+function toolPrefix(tool: ToolCallDisplay, animationPhase = 0): string {
+ if (tool.isError || tool.status === "error") return "! ";
+ if (tool.status === "timeout") return "◌ ";
+ if (isToolRunning(tool)) return ["◐ ", "◓ ", "◑ ", "◒ "][animationPhase % 4]!;
+ return "● ";
+}
+
+function toolPrefixColor(tool: ToolCallDisplay): (value: string) => string {
+ if (tool.isError || tool.status === "error") return palette.status.error;
+ if (tool.status === "timeout") return palette.status.warning;
+ if (isToolRunning(tool)) return palette.text.tool;
+ return palette.status.success;
+}
+
+function toolLineColor(tool: ToolCallDisplay): (value: string) => string {
+ if (tool.isError || tool.status === "error") return palette.status.error;
+ if (tool.status === "timeout") return palette.status.warning;
+ if (isToolRunning(tool)) return palette.text.tool;
+ return palette.text.dim;
+}
+
+export function toolStateColor(tool: ToolCallDisplay): (value: string) => string {
+ if (tool.isError || tool.status === "error") return palette.status.error;
+ if (tool.status === "timeout") return palette.status.warning;
+ if (isToolRunning(tool)) return palette.text.tool;
+ return palette.text.dim;
+}
+
+export function renderToolTitle(
+ width: number,
+ tool: ToolCallDisplay,
+ text: string,
+ animationPhase = 0,
+): string[] {
+ return prefixedLines(
+ renderWrappedText(Math.max(1, width - 2), text, toolLineColor(tool)),
+ width,
+ toolPrefix(tool, animationPhase),
+ toolPrefixColor(tool),
+ " ",
+ );
+}
+
+export function renderToolBranch(
+ width: number,
+ text: string,
+ colorFn: (value: string) => string,
+): string[] {
+ return prefixedLines(
+ renderWrappedText(Math.max(1, width - 2), text, colorFn),
+ width,
+ TOOL_BODY_PREFIX,
+ palette.text.subtle,
+ TOOL_BODY_CONTINUATION,
+ );
+}
+
+export function renderToolBranchAnsi(width: number, text: string): string[] {
+ return renderToolBranch(width, text, (value) => value);
+}
+
+export function renderToolTail(
+ width: number,
+ text: string,
+ colorFn: (value: string) => string,
+): string[] {
+ return prefixedLines(
+ renderWrappedText(Math.max(1, width - 2), text, colorFn),
+ width,
+ TOOL_TAIL_PREFIX,
+ palette.text.subtle,
+ TOOL_TAIL_CONTINUATION,
+ );
+}
+
+export function renderDiffRow(
+ width: number,
+ sign: " " | "+" | "-",
+ text: string,
+ colorFn: (value: string) => string,
+): string[] {
+ return renderWrappedText(width, `${sign} ${text}`, colorFn);
+}
+
+export function renderSimpleDiff(width: number, beforeText: string, afterText: string): string[] {
+ const beforeLines = beforeText.split("\n");
+ const afterLines = afterText.split("\n");
+ const total = Math.max(beforeLines.length, afterLines.length);
+ const lines: string[] = [];
+ for (let i = 0; i < total; i += 1) {
+ const before = beforeLines[i];
+ const after = afterLines[i];
+ if (before === after && before !== undefined) {
+ lines.push(...renderDiffRow(width, " ", before, palette.diff.context));
+ continue;
+ }
+ if (before !== undefined) lines.push(...renderDiffRow(width, "-", before, palette.diff.remove));
+ if (after !== undefined) lines.push(...renderDiffRow(width, "+", after, palette.diff.add));
+ }
+ return lines;
+}
+
+export function renderAddedLines(width: number, text: string): string[] {
+ return text
+ .split("\n")
+ .filter((line) => line.length > 0)
+ .flatMap((line) => renderDiffRow(width, "+", line, palette.diff.add));
+}
+
+export function renderStructuredBranch(
+ width: number,
+ value: unknown,
+ showDetails: boolean,
+ colorFn: (value: string) => string,
+): string[] {
+ const maxLines = showDetails ? MAX_STRUCTURED_LINES_EXPANDED : MAX_STRUCTURED_LINES_COLLAPSED;
+ const { lines } = formatStructuredValue(value, maxLines, showDetails ? 4 : 2);
+ return lines.flatMap((line) => renderToolBranch(width, line, colorFn));
+}
+
+export function renderSearchMatchBranch(width: number, line: string): string[] {
+ const trimmed = line.trim();
+ const match = /^(.+?):(\d+)(?::(\d+))?(?:(:|\s+-\s+|\s+)(.*))?$/.exec(trimmed);
+ if (!match) return renderToolBranch(width, line, palette.text.assistant);
+ const [, filePath, lineNumber, columnNumber, separatorRaw, remainderRaw] = match;
+ if (!filePath || (!filePath.includes("/") && !filePath.includes("."))) {
+ return renderToolBranch(width, line, palette.text.assistant);
+ }
+ const separator = separatorRaw ?? "";
+ const remainder = remainderRaw ?? "";
+ const formatted = `${palette.text.tool(filePath)}${palette.text.dim(`:${lineNumber}${columnNumber ? `:${columnNumber}` : ""}`)}${separator}${remainder ? palette.text.assistant(remainder) : ""}`;
+ return renderToolBranchAnsi(width, formatted);
+}
+
+export function renderPreviewLines(
+ width: number,
+ lines: string[],
+ colorFn: (value: string) => string,
+ expandedLimit: number,
+ collapsedLimit: number,
+ showDetails: boolean,
+ noun: string,
+): string[] {
+ const limit = showDetails ? expandedLimit : collapsedLimit;
+ const shown = lines.slice(0, limit);
+ const rendered = shown.flatMap((line) => renderToolBranch(width, line, colorFn));
+ if (lines.length > shown.length) {
+ rendered.push(
+ ...renderToolBranch(width, `+ ${lines.length - shown.length} more ${noun}`, palette.text.dim),
+ );
+ }
+ if (!showDetails && lines.length > 0) {
+ rendered.push(...renderToolBranch(width, TOOL_EXPAND_HINT, palette.text.dim));
+ }
+ return rendered;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-render-shared.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-render-shared.ts
new file mode 100644
index 0000000000..36e0674ffd
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-render-shared.ts
@@ -0,0 +1,37 @@
+import { summarize } from "../../rendering/text.js";
+import { isPlainObject, tryParseStructuredText } from "./tool-structured-data.js";
+
+export * from "./tool-kind-utils.js";
+export * from "./tool-line-renderers.js";
+export * from "./tool-structured-data.js";
+
+function summarizeStructuredPayload(value: string): string | undefined {
+ const parsed = tryParseStructuredText(value);
+ if (Array.isArray(parsed)) return `${parsed.length} item${parsed.length === 1 ? "" : "s"}`;
+ if (isPlainObject(parsed)) {
+ const keys = Object.keys(parsed);
+ return `${keys.length} field${keys.length === 1 ? "" : "s"}`;
+ }
+ return undefined;
+}
+
+export function summarizeToolResultByKind(name: string, result: string): string | undefined {
+ const normalized = name.toLowerCase();
+ const lines = result.split("\n").filter(Boolean).length;
+ if (normalized.includes("read") || normalized.includes("view")) return `${lines} lines loaded`;
+ if (normalized.includes("search") || normalized.includes("grep")) return `${lines} matches`;
+ if (normalized.includes("fetch") || normalized.includes("webpage"))
+ return `${lines} lines fetched`;
+ if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) {
+ return "edit applied";
+ }
+ if (
+ normalized.includes("exec") ||
+ normalized.includes("bash") ||
+ normalized.includes("shell") ||
+ normalized.includes("command")
+ ) {
+ return summarize(result.split("\n")[0] ?? "", 88);
+ }
+ return summarizeStructuredPayload(result);
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-render-types.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-render-types.ts
new file mode 100644
index 0000000000..14f970b2c0
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-render-types.ts
@@ -0,0 +1,4 @@
+export interface DetailedToolRenderOptions {
+ showDetails: boolean;
+ animationPhase: number;
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-structured-data.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-structured-data.ts
new file mode 100644
index 0000000000..138e4d1914
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-structured-data.ts
@@ -0,0 +1,297 @@
+import type { ToolCallDisplay } from "../../../core/types.js";
+import { summarize } from "../../rendering/text.js";
+import { getStringArg, isEditTool, isWriteTool } from "./tool-kind-utils.js";
+
+function normalizePythonLiteralToJson(value: string): string {
+ return value
+ .replace(/\bNone\b/g, "null")
+ .replace(/\bTrue\b/g, "true")
+ .replace(/\bFalse\b/g, "false")
+ .replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, (_match, content: string) => {
+ const normalized = content.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+ return `"${normalized}"`;
+ });
+}
+
+function parseLiteralFragment(value: string): unknown {
+ const trimmed = value.trim();
+ if (!trimmed || trimmed === "None") return null;
+ try {
+ return JSON.parse(trimmed);
+ } catch {}
+ try {
+ return JSON.parse(normalizePythonLiteralToJson(trimmed));
+ } catch {
+ return trimmed;
+ }
+}
+
+export function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function parseProtocolWrapper(value: string): unknown | undefined {
+ if (!value.includes("data=") && !value.includes("success=") && !value.includes("error=")) {
+ return undefined;
+ }
+
+ let working = value.trim();
+ let errorValue: unknown = undefined;
+ const errorIndex = working.lastIndexOf(" error=");
+ if (errorIndex >= 0) {
+ errorValue = parseLiteralFragment(working.slice(errorIndex + " error=".length));
+ working = working.slice(0, errorIndex);
+ }
+
+ let dataValue: unknown = undefined;
+ const dataIndex = working.indexOf(" data=");
+ if (dataIndex >= 0) {
+ dataValue = parseLiteralFragment(working.slice(dataIndex + " data=".length));
+ working = working.slice(0, dataIndex);
+ }
+
+ const successMatch = /\bsuccess=(True|False|true|false)\b/.exec(working);
+ const successValue =
+ successMatch?.[1] !== undefined ? successMatch[1].toLowerCase() === "true" : undefined;
+
+ if (isPlainObject(dataValue)) {
+ return {
+ ...dataValue,
+ ...(successValue !== undefined ? { success: successValue } : {}),
+ ...(errorValue !== undefined ? { error: errorValue } : {}),
+ };
+ }
+ if (Array.isArray(dataValue)) {
+ return {
+ items: dataValue,
+ count: dataValue.length,
+ ...(successValue !== undefined ? { success: successValue } : {}),
+ ...(errorValue !== undefined ? { error: errorValue } : {}),
+ };
+ }
+ if (dataValue !== undefined || successValue !== undefined || errorValue !== undefined) {
+ return {
+ ...(successValue !== undefined ? { success: successValue } : {}),
+ ...(errorValue !== undefined ? { error: errorValue } : {}),
+ ...(dataValue !== undefined ? { result: dataValue } : {}),
+ };
+ }
+ return undefined;
+}
+
+export function tryParseStructuredText(value: string): unknown {
+ const trimmed = value.trim();
+ if (!trimmed) return value;
+ const wrapped = parseProtocolWrapper(trimmed);
+ if (wrapped !== undefined) return wrapped;
+ if (!["{", "["].includes(trimmed[0] ?? "")) return value;
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ try {
+ return JSON.parse(normalizePythonLiteralToJson(trimmed));
+ } catch {
+ return value;
+ }
+ }
+}
+
+function isPrimitive(value: unknown): value is string | number | boolean | null {
+ return (
+ value === null ||
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean"
+ );
+}
+
+function formatLeafValue(value: unknown): string {
+ if (value === null) return "null";
+ if (typeof value === "string") {
+ const compact = value.replace(/\s+/g, " ").trim();
+ return compact ? summarize(compact, 96) : '""';
+ }
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
+ return summarize(JSON.stringify(value), 96);
+}
+
+export function formatStructuredValue(
+ value: unknown,
+ maxLines: number,
+ maxDepth: number,
+): { lines: string[]; truncated: number } {
+ const output: string[] = [];
+ const append = (line: string): boolean => {
+ if (output.length >= maxLines) return false;
+ output.push(line);
+ return true;
+ };
+
+ const visit = (current: unknown, indent: string, label?: string, depth = 0): void => {
+ if (output.length >= maxLines) return;
+ const parsed = typeof current === "string" ? tryParseStructuredText(current) : current;
+
+ if (isPrimitive(parsed)) {
+ if (typeof parsed === "string" && parsed.includes("\n")) {
+ const compactLines = parsed
+ .split("\n")
+ .map((line) => line.trimEnd())
+ .filter((line) => line.length > 0);
+ if (label && !append(`${indent}${label}:`)) return;
+ const visible = compactLines.slice(0, Math.max(1, maxLines - output.length));
+ for (const line of visible) {
+ if (!append(`${indent} ${summarize(line, 96)}`)) return;
+ }
+ return;
+ }
+ append(`${indent}${label ? `${label}: ` : ""}${formatLeafValue(parsed)}`);
+ return;
+ }
+
+ if (depth >= maxDepth) {
+ append(`${indent}${label ? `${label}: ` : ""}${Array.isArray(parsed) ? "[…]" : "{…}"}`);
+ return;
+ }
+
+ if (Array.isArray(parsed)) {
+ if (label && !append(`${indent}${label}:`)) return;
+ if (parsed.length === 0) {
+ append(`${indent}${label ? " " : ""}[]`);
+ return;
+ }
+ const childIndent = indent + (label ? " " : "");
+ for (const item of parsed) {
+ if (output.length >= maxLines) return;
+ if (isPrimitive(item)) {
+ append(`${childIndent}- ${formatLeafValue(item)}`);
+ continue;
+ }
+ if (!append(`${childIndent}-`)) return;
+ visit(item, `${childIndent} `, undefined, depth + 1);
+ }
+ return;
+ }
+
+ if (isPlainObject(parsed)) {
+ const entries = Object.entries(parsed).filter(([, item]) => item !== undefined);
+ if (label && !append(`${indent}${label}:`)) return;
+ if (entries.length === 0) {
+ append(`${indent}${label ? " " : ""}{}`);
+ return;
+ }
+ const childIndent = indent + (label ? " " : "");
+ for (const [key, item] of entries) {
+ visit(item, childIndent, key, depth + 1);
+ if (output.length >= maxLines) return;
+ }
+ return;
+ }
+
+ append(`${indent}${label ? `${label}: ` : ""}${summarize(String(parsed), 96)}`);
+ };
+
+ visit(value, "");
+ const truncated = Math.max(0, output.length - maxLines);
+ return { lines: output.slice(0, maxLines), truncated };
+}
+
+export function extractTrailingBracketNotices(text: string): {
+ mainLines: string[];
+ notices: string[];
+} {
+ const lines = text.split("\n");
+ const notices: string[] = [];
+ let end = lines.length;
+ while (end > 0) {
+ const current = lines[end - 1]?.trim() ?? "";
+ if (current.startsWith("[") && current.endsWith("]")) {
+ notices.unshift(current);
+ end -= 1;
+ continue;
+ }
+ break;
+ }
+ return { mainLines: lines.slice(0, end).filter((line) => line.length > 0), notices };
+}
+
+export function parseToolResultPayload(tool: ToolCallDisplay): Record<string, unknown> | undefined {
+ if (!tool.result) return undefined;
+ const parsed = tryParseStructuredText(tool.result);
+ return isPlainObject(parsed) ? parsed : undefined;
+}
+
+export function parseToolResultValue(tool: ToolCallDisplay): unknown {
+ if (!tool.result) return undefined;
+ return tryParseStructuredText(tool.result);
+}
+
+export function parseFetchResult(tool: ToolCallDisplay): {
+ url?: string;
+ status?: string;
+ title?: string;
+ contentLines: string[];
+} {
+ if (!tool.result) return { contentLines: [] };
+ const parsed = parseToolResultPayload(tool);
+ if (parsed) {
+ return {
+ url: getStringArg(parsed, "url"),
+ status:
+ typeof parsed.status_code === "number"
+ ? String(parsed.status_code)
+ : getStringArg(parsed, "status", "status_code"),
+ title: getStringArg(parsed, "title"),
+ contentLines: nonEmptyLines(parsed.content),
+ };
+ }
+ const lines = tool.result.split("\n").map((line) => line.trimEnd());
+ const contentStartIndex = lines.findIndex((line) => line.trim().toLowerCase() === "content:");
+ return {
+ url: lines
+ .find((line) => line.startsWith("URL:"))
+ ?.slice(4)
+ .trim(),
+ status: lines
+ .find((line) => line.startsWith("Status:"))
+ ?.slice(7)
+ .trim(),
+ title: lines
+ .find((line) => line.startsWith("Title:"))
+ ?.slice(6)
+ .trim(),
+ contentLines:
+ contentStartIndex >= 0
+ ? lines.slice(contentStartIndex + 1).filter((line) => line.trim().length > 0)
+ : nonEmptyLines(tool.result),
+ };
+}
+
+export function getStringList(payload: Record<string, unknown>, ...keys: string[]): string[] {
+ for (const key of keys) {
+ const value = payload[key];
+ if (Array.isArray(value)) {
+ const list = value.filter(
+ (item): item is string => typeof item === "string" && item.length > 0,
+ );
+ if (list.length > 0) return list;
+ }
+ }
+ return [];
+}
+
+export function getStringListFromValue(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return value.filter((item): item is string => typeof item === "string" && item.length > 0);
+}
+
+export function nonEmptyLines(value: unknown): string[] {
+ if (typeof value !== "string") return [];
+ return value
+ .split("\n")
+ .map((line) => line.trimEnd())
+ .filter((line) => line.trim().length > 0);
+}
+
+export function shouldRenderStructuredPayloadByDefault(name: string): boolean {
+ return isWriteTool(name) || isEditTool(name);
+}
diff --git a/jiuwenclaw/cli/src/ui/keymap.ts b/jiuwenclaw/cli/src/ui/keymap.ts
index 1720f20bbc..714dfc50e7 100644
--- a/jiuwenclaw/cli/src/ui/keymap.ts
+++ b/jiuwenclaw/cli/src/ui/keymap.ts
@@ -5,9 +5,10 @@ export interface AppScreenKeymapDelegate {
getSnapshot(): AppSnapshot;
cancel(): void;
requestExit(): void;
- toggleThinking(): void;
- toggleToolDetails(): void;
- toggleShortcutHelp(): void;
+ toggleTodos(): void;
+ toggleTeamPanel(): void;
+ toggleTranscript(): void;
+ redraw(): void;
}
interface KeyBinding {
@@ -31,28 +32,36 @@ export const APP_SCREEN_KEY_BINDINGS: readonly KeyBinding[] = [
}
},
},
+ {
+ key: "ctrl+l",
+ label: "ctrl+l",
+ description: "redraw screen",
+ run: (delegate) => {
+ delegate.redraw();
+ },
+ },
{
key: "ctrl+t",
label: "ctrl+t",
- description: "toggle thinking detail",
+ description: "toggle todos",
run: (delegate) => {
- delegate.toggleThinking();
+ delegate.toggleTodos();
},
},
{
- key: "ctrl+o",
- label: "ctrl+o",
- description: "toggle tool detail",
+ key: "ctrl+g",
+ label: "ctrl+g",
+ description: "toggle team panel",
run: (delegate) => {
- delegate.toggleToolDetails();
+ delegate.toggleTeamPanel();
},
},
{
- key: "ctrl+k",
- label: "ctrl+k",
- description: "toggle shortcut help",
+ key: "ctrl+o",
+ label: "ctrl+o",
+ description: "toggle transcript detail",
run: (delegate) => {
- delegate.toggleShortcutHelp();
+ delegate.toggleTranscript();
},
},
] as const;
diff --git a/jiuwenclaw/cli/src/ui/screen-layout.ts b/jiuwenclaw/cli/src/ui/screen-layout.ts
index 849e3225f8..e2347f0df3 100644
--- a/jiuwenclaw/cli/src/ui/screen-layout.ts
+++ b/jiuwenclaw/cli/src/ui/screen-layout.ts
@@ -1,20 +1,26 @@
import type { AppSnapshot } from "../app-state.js";
-import type { HistoryItem, ToolCallDisplay } from "../core/types.js";
-import { renderHistoryEntry } from "./components/messages/index.js";
+import { renderMiniTeamTree, renderTeamPanel } from "./components/team-panel.js";
+import { renderTeamStatusPill } from "./components/team-status-pill.js";
import { renderTodoList } from "./components/todo-list.js";
import { APP_SCREEN_KEY_BINDINGS } from "./keymap.js";
import { padToWidth } from "./rendering/text.js";
import { palette } from "./theme.js";
-import { buildWelcomeLines } from "./welcome.js";
+import { buildTranscriptLines } from "./transcript-renderer.js";
export interface ScreenLayoutOptions {
width: number;
questionLines: string[];
editorLines: string[];
+ composerPreviewLines: string[];
showFullThinking: boolean;
showToolDetails: boolean;
showShortcutHelp: boolean;
+ showTodos: boolean;
+ showTeamPanel: boolean;
+ selectedTeamMemberId: string | null;
transientNotice: string | null;
+ animationPhase: number;
+ runningElapsedMs?: number;
}
function formatSubtaskStatus(status: string): string {
@@ -34,16 +40,42 @@ function formatSubtaskStatus(status: string): string {
}
}
+function formatElapsed(ms: number | undefined): string {
+ if (ms === undefined || !Number.isFinite(ms) || ms < 0) {
+ return "0s";
+ }
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
+}
+
+function renderRunningStatus(animationPhase: number, elapsedMs: number | undefined): string {
+ const label = "Working";
+ const sweep = animationPhase % (label.length + 3);
+ const focus = sweep - 1;
+ const animatedLabel = label
+ .split("")
+ .map((char, index) => {
+ const distance = Math.abs(index - focus);
+ if (distance === 0) return palette.text.assistant(char);
+ if (distance === 1) return palette.text.dim(char);
+ return palette.text.subtle(char);
+ })
+ .join("");
+ return `• ${animatedLabel} (${formatElapsed(elapsedMs)} • esc to interrupt)`;
+}
+
function buildStatusLines(
snapshot: AppSnapshot,
width: number,
transientNotice: string | null,
+ animationPhase: number,
+ runningElapsedMs: number | undefined,
): string[] {
- const left = [
- `status:${snapshot.connectionStatus}`,
- `mode:${snapshot.mode}`,
- `view:${snapshot.transcriptMode}`,
- ];
+ const left: string[] = [];
+ if (snapshot.connectionStatus !== "connected") left.push(`status:${snapshot.connectionStatus}`);
+ if (snapshot.mode !== "plan") left.push(`mode:${snapshot.mode}`);
if (snapshot.transcriptFoldMode !== "none") left.push(`fold:${snapshot.transcriptFoldMode}`);
const right = snapshot.lastError
@@ -51,13 +83,17 @@ function buildStatusLines(
: snapshot.isPaused
? "paused"
: snapshot.isProcessing
- ? "running"
- : "ready";
+ ? renderRunningStatus(animationPhase, runningElapsedMs)
+ : null;
const lines = transientNotice ? [padToWidth(palette.status.warning(transientNotice), width)] : [];
- const content = `${left.join(" | ")} | ${right}`;
- lines.push(padToWidth(palette.text.dim(content), width));
const leadSubtask = snapshot.activeSubtasks[0];
+
+ const content = right ? [...left, right].join(" | ") : left.join(" | ");
+ if (content) {
+ lines.push(padToWidth(palette.text.dim(content), width));
+ }
+
if (leadSubtask) {
const parts = [
`subtask ${leadSubtask.index}/${leadSubtask.total || "?"}`,
@@ -87,78 +123,14 @@ function buildShortcutLines(width: number): string[] {
return lines;
}
-function isTodoTool(tool: ToolCallDisplay): boolean {
- const normalized = tool.name.trim().toLowerCase();
- return normalized === "todo" || normalized.startsWith("todo_");
-}
-
-function filterTodoToolEntry(entry: HistoryItem): HistoryItem | null {
- if (entry.kind !== "tool_group") {
- return entry;
- }
- const tools = entry.tools.filter((tool) => !isTodoTool(tool));
- if (tools.length === 0) {
- return null;
- }
- return tools.length === entry.tools.length ? entry : { ...entry, tools };
-}
-
-function buildTranscriptLines(
- snapshot: AppSnapshot,
- width: number,
- showFullThinking: boolean,
- showToolDetails: boolean,
-): string[] {
- let displayEntries =
- snapshot.transcriptMode === "compact"
- ? snapshot.entries
- .filter((entry) => entry.kind !== "system")
- .map((entry) =>
- entry.kind === "tool_group" ? { ...entry, tools: entry.tools.slice(-1) } : entry,
- )
- : snapshot.entries;
-
- if (snapshot.transcriptFoldMode === "all") {
- displayEntries = displayEntries.filter(
- (entry) =>
- entry.kind === "user" ||
- entry.kind === "assistant" ||
- entry.kind === "thinking" ||
- entry.kind === "error",
- );
- } else if (snapshot.transcriptFoldMode === "thinking") {
- displayEntries = displayEntries.filter((entry) => entry.kind !== "thinking");
- } else if (snapshot.transcriptFoldMode === "tools") {
- displayEntries = displayEntries.filter(
- (entry) => entry.kind !== "system" && entry.kind !== "info",
- );
- }
-
- displayEntries = displayEntries
- .map((entry) => filterTodoToolEntry(entry))
- .filter((entry): entry is HistoryItem => entry !== null);
-
- const allLines: string[] = [];
- if (displayEntries.length === 0) {
- allLines.push(...buildWelcomeLines(width));
- }
- for (const entry of displayEntries) {
- const collapsed = entry.kind === "tool_group" && snapshot.collapsedToolGroupIds.has(entry.id);
- allLines.push(
- ...renderHistoryEntry(entry, width, {
- compact: snapshot.transcriptMode === "compact",
- collapsed,
- thinkingExpanded: showFullThinking,
- toolDetailsExpanded: showToolDetails,
- }),
- );
- allLines.push(" ".repeat(width));
- }
- return allLines;
-}
-
export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayoutOptions): string[] {
- const statusLines = buildStatusLines(snapshot, options.width, options.transientNotice);
+ const statusLines = buildStatusLines(
+ snapshot,
+ options.width,
+ options.transientNotice,
+ options.animationPhase,
+ options.runningElapsedMs,
+ );
const shortcutLines = options.showShortcutHelp ? buildShortcutLines(options.width) : [];
const transcriptLines = buildTranscriptLines(
@@ -166,13 +138,61 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout
options.width,
options.showFullThinking,
options.showToolDetails,
+ options.animationPhase,
);
- const todoLines = renderTodoList(snapshot.todos, options.width);
+ const todoLines = options.showTodos ? renderTodoList(snapshot.todos, options.width) : [];
+ const teamStatusLines =
+ snapshot.mode === "team" ||
+ snapshot.teamMemberEvents.length > 0 ||
+ snapshot.teamTaskEvents.length > 0 ||
+ snapshot.teamMessageEvents.length > 0
+ ? renderTeamStatusPill(
+ snapshot.teamMemberEvents,
+ snapshot.teamTaskEvents,
+ snapshot.teamMessageEvents,
+ options.width,
+ )
+ : [];
+ const teamPanelLines =
+ options.showTeamPanel &&
+ (snapshot.mode === "team" ||
+ snapshot.teamMemberEvents.length > 0 ||
+ snapshot.teamTaskEvents.length > 0 ||
+ snapshot.teamMessageEvents.length > 0)
+ ? renderTeamPanel(
+ snapshot.teamMemberEvents,
+ snapshot.teamTaskEvents,
+ snapshot.teamMessageEvents,
+ options.width,
+ options.selectedTeamMemberId,
+ )
+ : [];
+ const miniTeamTreeLines =
+ !options.showTeamPanel &&
+ (snapshot.mode === "team" ||
+ snapshot.teamMemberEvents.length > 0 ||
+ snapshot.teamTaskEvents.length > 0 ||
+ snapshot.teamMessageEvents.length > 0)
+ ? renderMiniTeamTree(
+ snapshot.teamMemberEvents,
+ snapshot.teamTaskEvents,
+ snapshot.teamMessageEvents,
+ options.width,
+ )
+ : [];
return [
...transcriptLines,
...todoLines,
+ ...(todoLines.length > 0 &&
+ (teamStatusLines.length > 0 || miniTeamTreeLines.length > 0 || teamPanelLines.length > 0)
+ ? [" ".repeat(options.width)]
+ : []),
+ ...teamStatusLines,
+ ...miniTeamTreeLines,
+ ...teamPanelLines,
...options.questionLines,
...options.editorLines,
+ ...options.composerPreviewLines,
...statusLines,
...shortcutLines,
];
diff --git a/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts b/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts
new file mode 100644
index 0000000000..2fc089ad59
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts
@@ -0,0 +1,72 @@
+import type { AppSnapshot } from "../app-state.js";
+import type { HistoryItem, ToolCallDisplay } from "../core/types.js";
+import { buildTranscriptEntries } from "../core/transcript-timeline.js";
+
+function isTodoTool(tool: ToolCallDisplay): boolean {
+ const normalized = tool.name.trim().toLowerCase();
+ return normalized === "todo" || normalized.startsWith("todo_");
+}
+
+function filterTodoToolEntry(entry: HistoryItem): HistoryItem | null {
+ if (entry.kind !== "tool_group" && entry.kind !== "collapsed_tool_group") {
+ return entry;
+ }
+ const tools = entry.tools.filter((tool) => !isTodoTool(tool));
+ if (tools.length === 0) {
+ return null;
+ }
+ return tools.length === entry.tools.length ? entry : { ...entry, tools };
+}
+
+export interface SelectedTranscriptEntries {
+ entries: HistoryItem[];
+ latestThinkingId?: string;
+}
+
+export function selectTranscriptEntries(snapshot: AppSnapshot): SelectedTranscriptEntries {
+ let entries =
+ snapshot.transcriptMode === "compact"
+ ? buildTranscriptEntries(snapshot.entries, snapshot.toolExecutions)
+ .filter((entry) => entry.kind !== "system")
+ .map((entry) =>
+ entry.kind === "collapsed_tool_group"
+ ? { ...entry, tools: entry.tools.slice(-1) }
+ : entry,
+ )
+ : buildTranscriptEntries(snapshot.entries, snapshot.toolExecutions);
+
+ if (snapshot.transcriptFoldMode === "all") {
+ entries = entries.filter(
+ (entry) =>
+ entry.kind === "user" ||
+ entry.kind === "assistant" ||
+ entry.kind === "thinking" ||
+ entry.kind === "error",
+ );
+ } else if (snapshot.transcriptFoldMode === "thinking") {
+ entries = entries.filter((entry) => entry.kind !== "thinking");
+ } else if (snapshot.transcriptFoldMode === "tools") {
+ entries = entries.filter((entry) => entry.kind !== "system" && entry.kind !== "info");
+ }
+
+ entries = entries
+ .map((entry) => filterTodoToolEntry(entry))
+ .filter((entry): entry is HistoryItem => entry !== null);
+
+ const latestUserIndex =
+ [...entries]
+ .map((entry, index) => ({ entry, index }))
+ .reverse()
+ .find(({ entry }) => entry.kind === "user")?.index ?? -1;
+ const latestThinkingId =
+ [...entries]
+ .slice(latestUserIndex + 1)
+ .reverse()
+ .find((entry) => entry.kind === "thinking")?.id ?? undefined;
+
+ if (snapshot.transcriptMode === "compact") {
+ entries = entries.filter((entry) => entry.kind !== "thinking");
+ }
+
+ return { entries, latestThinkingId };
+}
diff --git a/jiuwenclaw/cli/src/ui/transcript-renderer.ts b/jiuwenclaw/cli/src/ui/transcript-renderer.ts
new file mode 100644
index 0000000000..05260a08a3
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/transcript-renderer.ts
@@ -0,0 +1,47 @@
+import type { AppSnapshot } from "../app-state.js";
+import { renderHistoryEntry } from "./components/messages/index.js";
+import { shouldEmphasizeAssistantTransition } from "./components/messages/presentation-rules.js";
+import { selectTranscriptEntries } from "./transcript-entry-selection.js";
+import { buildWelcomeLines } from "./welcome.js";
+
+export function buildTranscriptLines(
+ snapshot: AppSnapshot,
+ width: number,
+ showFullThinking: boolean,
+ showToolDetails: boolean,
+ animationPhase: number,
+): string[] {
+ const { entries: displayEntries, latestThinkingId } = selectTranscriptEntries(snapshot);
+
+ const allLines: string[] = [];
+ if (displayEntries.length === 0) {
+ allLines.push(...buildWelcomeLines(width));
+ }
+
+ for (const [index, entry] of displayEntries.entries()) {
+ const nextEntry = displayEntries[index + 1];
+ const collapsed =
+ (entry.kind === "tool_group" || entry.kind === "collapsed_tool_group") &&
+ snapshot.collapsedToolGroupIds.has(entry.id);
+ const rendered = renderHistoryEntry(entry, width, {
+ compact: snapshot.transcriptMode === "compact",
+ collapsed,
+ thinkingExpanded: showFullThinking,
+ activeThinkingId: snapshot.isProcessing ? latestThinkingId : undefined,
+ toolDetailsExpanded: showToolDetails,
+ animationPhase,
+ });
+ allLines.push(...rendered.lines);
+
+ if (rendered.gapAfter) {
+ allLines.push(" ".repeat(width));
+ }
+ if (
+ shouldEmphasizeAssistantTransition(entry, nextEntry, snapshot.transcriptMode === "compact")
+ ) {
+ allLines.push(" ".repeat(width));
+ }
+ }
+
+ return allLines;
+}
diff --git a/jiuwenclaw/cli/src/ui/welcome.ts b/jiuwenclaw/cli/src/ui/welcome.ts
index 69d75208b3..bc6897fc53 100644
--- a/jiuwenclaw/cli/src/ui/welcome.ts
+++ b/jiuwenclaw/cli/src/ui/welcome.ts
@@ -1,19 +1,27 @@
+import { visibleWidth } from "@mariozechner/pi-tui";
import { padToWidth } from "./rendering/text.js";
import { palette } from "./theme.js";
+const ART_TITLE = ["╭──╮ ╭──╮ ╭──╮", "│九│ │纹│ │爪│", "╰──╯ ╰──╯ ╰──╯"] as const;
+
+function centerLine(line: string, width: number): string {
+ const padding = Math.max(0, Math.floor((width - visibleWidth(line)) / 2));
+ return padToWidth(`${" ".repeat(padding)}${line}`, width);
+}
+
export function buildWelcomeLines(width: number): string[] {
+ const artWidth = Math.max(...ART_TITLE.map((line) => visibleWidth(line)));
+ if (width >= artWidth + 6) {
+ return [
+ ...ART_TITLE.map((line) => centerLine(palette.text.dim(line), width)),
+ centerLine(palette.text.subtle("/resume to continue · /help for commands"), width),
+ " ".repeat(width),
+ ];
+ }
+
return [
- padToWidth(palette.text.secondary("JiuwenClaw CLI"), width),
- padToWidth(
- palette.text.dim(
- "Ask questions, inspect tool output, and drive the session from the terminal.",
- ),
- width,
- ),
- padToWidth(
- palette.text.dim("Use /help for commands or /hotkey for keyboard shortcuts."),
- width,
- ),
+ padToWidth(palette.text.dim("九纹爪"), width),
+ padToWidth(palette.text.subtle("/resume to continue · /help for commands"), width),
" ".repeat(width),
];
}