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

[fix](tui) Interactive diff dialog with file list and scrolling detail view, remove static detail view Refs:#1554

haowenzhong14404acf763c8
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index 3da9e772c2..2f4b6a12fc 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -158,14 +158,27 @@ Behavior:
- Switching model validates config and environment variable placeholders, updates `MODEL_NAME` / `MODEL_PROVIDER` / `API_BASE` / `API_KEY`, writes back to `.env`.
- Secure display: Sensitive fields like `api_key`, `token` are masked.
-### `/diff` (Session Change Review)
+### `/diff` (Interactive Change Review)
- Usage: `/diff` (no subcommands).
-- Data source: TUI requests Agent diff service via `command.diff`, returns `turns` (change sets per turn) for current `session_id`.
-- Display rules:
- - With changes: Shows `Found N turn(s) with file changes` with structured `turns`;
- - Without changes: Shows `No file changes in this session`.
-- Scope: For viewing uncommitted per-turn change traces in current session, not a replacement for `git diff` full version control perspective.
+- Data source: TUI requests Agent diff service via `command.diff`, returns `turns` (change sets per turn) and `gitDiff` (uncommitted working tree changes) for current `session_id`.
+- Display mode: Opens a **full-screen interactive Diff viewer**:
+ - **List view**: Shows all changed files (working tree `working` and per-turn `Turn N`) with relative paths, source label, and added/removed line counts;
+ - **Detail view**: Press `Enter` on a selected file to view its full hunk-by-hunk diff with scrolling support.
+- List view keybindings:
+ - `↑` / `↓` — Move selection (auto-scrolls);
+ - `Enter` — View full diff for the selected file;
+ - `Home` / `g` — Jump to top;
+ - `End` / `Shift+g` — Jump to bottom;
+ - `Esc` / `Ctrl+C` — Close.
+- Detail view keybindings:
+ - `↑` / `↓` — Scroll line by line;
+ - `PgUp` / `PgDn` — Page up / down;
+ - `Home` / `g` — Go to file top;
+ - `End` / `Shift+g` — Go to file bottom;
+ - `←` / `Esc` — Return to list view.
+- Scope: Covers both the working tree (`git diff HEAD`) and per-turn change traces. Not a replacement for `git diff` full version control perspective.
+- Fallback: When the TUI does not provide the `enterDiffViewer` capability, falls back to inline display (file names, source, and line stats only).
### `/compact` (Context Compression)
diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
index d348f6bc09..a81a64a377 100644
--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
@@ -160,14 +160,27 @@
- 切换模型会校验配置与环境变量占位符,更新 `MODEL_NAME` / `MODEL_PROVIDER` / `API_BASE` / `API_KEY`,并回写 `.env`。
- 安全展示:涉及 `api_key`、`token` 等敏感字段会掩码显示。
-### `/diff`(会话改动回顾)
+### `/diff`(交互式改动回顾)
- 用法:`/diff`(无子命令)。
-- 数据来源:TUI 通过 `command.diff` 请求 Agent 侧 diff 服务,按当前 `session_id` 返回 `turns`(每轮改动集合)。
-- 展示规则:
- - 有改动:显示 `Found N turn(s) with file changes` 并附结构化 `turns`;
- - 无改动:显示 `No file changes in this session`。
-- 作用范围:用于查看当前会话内未提交的按轮次改动轨迹,不替代 `git diff` 的完整版本控制视角。
+- 数据来源:TUI 通过 `command.diff` 请求 Agent 侧 diff 服务,按当前 `session_id` 返回 `turns`(每轮改动集合)及 `gitDiff`(未提交的工作树改动)。
+- 展示方式:打开 **交互式 Diff 查看器**(全屏覆盖模式):
+ - **列表视图**:展示所有变更文件(含工作树 `working` 和按轮次 `Turn N`),显示相对路径、来源、增删行数;
+ - **详情视图**:选中文件后 `Enter` 进入,展示完整的 hunk diff,支持上下滚动。
+- 列表视图快捷键:
+ - `↑` / `↓` — 移动选择,自动滚动;
+ - `Enter` — 查看选中文件的完整 diff;
+ - `Home` / `g` — 跳至列表顶部;
+ - `End` / `Shift+g` — 跳至列表底部;
+ - `Esc` / `Ctrl+C` — 关闭。
+- 详情视图快捷键:
+ - `↑` / `↓` — 逐行滚动;
+ - `PgUp` / `PgDn` — 上下翻页;
+ - `Home` / `g` — 跳至文件开头;
+ - `End` / `Shift+g` — 跳至文件末尾;
+ - `←` / `Esc` — 返回列表视图。
+- 作用范围:同时覆盖工作树(`git diff HEAD`)和会话按轮次改动轨迹,不替代 `git diff` 的完整版本控制视角。
+- 回退行为:当 TUI 不提供 `enterDiffViewer` 能力时,回退为内联展示(仅显示文件名、来源和增删行数)。
### `/compact`(上下文压缩)
diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
index 3a36d03de7..70eefe27f5 100644
--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
@@ -66,7 +66,7 @@
| `/compact` | - | 压缩上下文,保留摘要 | `/compact` | 全部 |
| `/config` | `/settings`, `/setting` | 查看/设置后端配置 | `/config`、`/config get`、`/config set key value` | 全部 |
| `/context` | - | 查看上下文窗口占用与 Token 用量明细 | `/context` | 全部 |
-| `/diff` | - | 查看本会话按轮次的文件改动 | `/diff` | 全部 |
+| `/diff` | - | 交互式查看工作树与按轮次的文件改动 | `/diff` | 全部 |
| `/evolve` | - | 触发技能演进 | `/evolve myskill 修正错误处理` | `agent.plan` / `team`(见下) |
| `/evolve_list` | - | 列出某技能的演进条目 | `/evolve_list myskill --sort score` | `agent.plan` / `team` |
| `/evolve_rebuild` | - | 从归档与演进记录重建 SKILL.md | `/evolve_rebuild myskill 强化错误处理` | `agent.plan` / `team` |
@@ -197,9 +197,24 @@
- 交互选择范围:团队共享 `JIUWENSWARM.md`、个人 `JIUWENSWARM.local.md` 或两者;然后向后端发送编排提示(`logAsUser: false`)。
- 详见 [Slash命令表.md](Slash命令表.md) 与源码 `init.ts`。
-#### `/diff` 与 `/compact`
+#### `/diff`(交互式改动回顾)
+
+- **`/diff`**:调用 `command.diff`,获取工作树(uncommitted changes)及本会话内有文件变更的轮次,然后打开 **交互式 Diff 查看器**(全屏覆盖模式)。
+
+ **快捷键**:
+
+ | 按键 | 功能 |
+ |------|------|
+ | `↑` / `↓` | 在文件列表间移动焦点 |
+ | `Enter` | 查看焦点文件的完整 diff(进入详情视图) |
+ | `Esc` / `Ctrl+C` | 详情视图 → 返回列表;列表视图 → 关闭 |
+ | `←` | 从详情视图返回列表 |
+ | `PgUp` / `PgDn` | 详情视图上下翻页 |
+ | `Home` / `g` | 列表 → 跳至顶部;详情 → 跳至文件开头 |
+ | `End` / `Shift+g` | 列表 → 跳至底部;详情 → 跳至文件末尾 |
+
+ 注意:未提交的工作树改动通过 `git diff HEAD` 获取;同一文件在工作树和某轮次中均出现时会重复列出,来源标注为 `working` 或 `Turn N`。
-- **`/diff`**:调用 `command.diff`,展示本会话内有文件变更的轮次(非完整 `git diff` 替代)。
- **`/compact`**:调用 `command.compact`,返回 `busy` | `compressed` | `noop`;成功时展示 token 节省比例(`compact.ts`)。
#### `/context`(上下文窗口用量)
@@ -427,10 +442,16 @@
### 输入、附件与 `@` 引用
-- **文件/图片附件**:在输入中使用 `@路径` 或 `@"含空格路径"`;解析规则见 `attachments.ts`。
-- **图片扩展名**:`.png`、`.jpg`、`.jpeg`、`.gif`、`.webp`。
+- **`@` 路径自动补全**:在输入框中键入 `@` 后,TUI 会自动弹出文件路径补全下拉框,支持:
+ - 相对路径补全(基于当前工作目录 `cwd`);
+ - 绝对路径补全(`/` 开头);
+ - home 目录简写补全(`~` / `~/` 开头);
+ - 含空格路径补全:使用 `@"路径"` 语法。
+ - 选择补全项后自动补全路径并追加一个空格。
+ - 补全来源为文件系统实时扫描,目录优先排序。
+- **文件附件**:在输入中使用 `@路径` 或 `@"含空格路径"` 后,`@` 引用的文件会作为消息附件发送给 Agent;解析规则见 `attachments.ts`。
- **常见作为附件的文件扩展名**:含源码、文档、配置、压缩包、Office 文档等一大类扩展名(见 `SUPPORTED_FILE_EXTENSIONS`);未在列表中的扩展名可能不会生成附件。
-- **粘贴路径**:支持引号路径、`file://`、Windows 盘符路径等,由 `extractFilePathsFromPaste` 解析。
+- **粘贴路径**:支持拖拽文件到终端(纯文件路径粘贴)、`file://` 协议路径、Windows 盘符路径等,由 `extractFilePathsFromPaste` 解析并自动转换为 `@路径` 引用。
### 命令与路径补全
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
index 6d2d2cb0ca..195648da6e 100644
--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
@@ -1022,6 +1022,8 @@ export class CliPiAppState {
getCurrentProjectDir: getCurrentProjectDir,
getWorkspaceDir: () => getCurrentCwd() || process.cwd(),
enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.
+ enterFileViewer: undefined, // AppScreen injects the real handler when executing slash commands.
+ enterDiffViewer: undefined, // AppScreen injects the real handler when executing slash commands.
setInput: this._setInputRef ?? undefined,
enterStatusView: undefined,
getUsageSummary: () => this.getUsageSummary(),
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts
index b7f9aa60e7..34d646dff3 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts
@@ -12,17 +12,20 @@ export function createDiffCommand(): SlashCommand {
return {
name: "diff",
description: "View uncommitted changes and per-turn diffs",
- usage: "/diff [--detail]",
+ usage: "/diff",
example: "/diff",
kind: CommandKind.BUILT_IN,
action: async (ctx, args) => {
try {
- const showDetail = (args || "").split(/\s+/).filter(Boolean).includes("--detail");
-
const payload = await ctx.request<DiffPayload>("command.diff", {});
const turns = payload.turns || [];
const gitDiff = payload.gitDiff || null;
+ if (ctx.enterDiffViewer) {
+ ctx.enterDiffViewer(payload as unknown as Record<string, unknown>);
+ return;
+ }
+
const parts: string[] = [];
if (gitDiff && gitDiff.stats.filesChanged > 0) {
parts.push(
@@ -37,7 +40,7 @@ export function createDiffCommand(): SlashCommand {
: "No file changes in this session";
ctx.addItem(
- addDiff(ctx.sessionId, summary, { turns, gitDiff, showDetail }),
+ addDiff(ctx.sessionId, summary, { turns, gitDiff }),
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts
index 1dafc902a3..3a0fc1f5fd 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts
@@ -100,6 +100,8 @@ export interface CommandContext {
openInEditor?: (filePath: string) => void;
/** Enter FileViewer mode to view large content (e.g., formatted logs) */
enterFileViewer?: (content: string, title: string, source: string) => void;
+ /** Enter DiffViewer mode to browse git/turn diffs interactively */
+ enterDiffViewer?: (payload: Record<string, unknown>) => void;
restartStatusLine?: () => void;
/** Get the current JSON data that would be piped to the statusline command */
getStatusLineJsonInput?: () => Record<string, unknown>;
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index bc02de4418..6c479ff144 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -78,6 +78,7 @@ import {
} from "./components/team-shared.js";
import { padToWidth, renderWrappedText } from "./rendering/text.js";
import { chalk, editorTheme, palette, selectListTheme, setCurrentThemeName } from "./theme.js";
+import type { Hunk, GitDiffData, TurnDiff } from "../core/types.js";
const END_CURSOR = "\x1b[7m \x1b[0m";
const ENABLE_MOUSE_TRACKING = "\x1b[?1000h\x1b[?1006h";
@@ -317,6 +318,25 @@ type FileViewerState = {
searchTerm: string; // Search term
};
+interface DiffFileEntry {
+ filePath: string;
+ linesAdded: number;
+ linesRemoved: number;
+ isNewFile: boolean;
+ isUntracked: boolean;
+ hunks: Hunk[];
+ source: "working" | string;
+}
+
+type DiffViewerState = {
+ viewMode: "list" | "detail";
+ selectedIndex: number;
+ files: DiffFileEntry[];
+ scrollOffset: number;
+ title: string;
+ subtitle: string;
+};
+
const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
function findLastPathDelimiter(text: string): number {
@@ -1116,6 +1136,8 @@ export class AppScreen implements Component, Focusable {
private composerAttachments: FileAttachment[] = [];
/** FileViewer state for viewing large content (e.g., formatted logs) */
private fileViewerState: FileViewerState | null = null;
+ /** DiffViewer state for interactive diff browsing */
+ private diffViewerState: DiffViewerState | null = null;
/** Previous session title for terminal window title sync. */
private previousSessionTitle: string = "";
@@ -1410,6 +1432,277 @@ export class AppScreen implements Component, Focusable {
return lines;
}
+ /** Enter DiffViewer mode to browse git/turn diffs interactively */
+ enterDiffViewer(payload: Record<string, unknown>): void {
+ const turns = (payload.turns || []) as TurnDiff[];
+ const gitDiff = (payload.gitDiff || null) as GitDiffData | null;
+ const files: DiffFileEntry[] = [];
+
+ if (gitDiff) {
+ for (const f of Object.values(gitDiff.files)) {
+ files.push({
+ filePath: f.filePath,
+ linesAdded: f.linesAdded,
+ linesRemoved: f.linesRemoved,
+ isNewFile: f.isNewFile,
+ isUntracked: f.isNewFile,
+ hunks: f.hunks || [],
+ source: "working",
+ });
+ }
+ }
+
+ for (const turn of turns) {
+ for (const f of Object.values(turn.files)) {
+ files.push({
+ filePath: f.filePath,
+ linesAdded: f.linesAdded,
+ linesRemoved: f.linesRemoved,
+ isNewFile: f.isNewFile,
+ isUntracked: false,
+ hunks: f.hunks || [],
+ source: `Turn ${turn.turnIndex}`,
+ });
+ }
+ }
+
+ const totalAdded = files.reduce((s, f) => s + f.linesAdded, 0);
+ const totalRemoved = files.reduce((s, f) => s + f.linesRemoved, 0);
+ const title = `Diff`;
+ const subtitle = `${files.length} files changed +${totalAdded} -${totalRemoved}`;
+
+ this.diffViewerState = {
+ viewMode: "list",
+ selectedIndex: 0,
+ files,
+ scrollOffset: 0,
+ title,
+ subtitle,
+ };
+ this.tui.requestRender();
+ }
+
+ exitDiffViewer(): void {
+ this.diffViewerState = null;
+ this.tui.requestRender();
+ }
+
+ private handleDiffViewerInput(data: string, height: number): void {
+ if (!this.diffViewerState) return;
+
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
+ if (this.diffViewerState.viewMode === "detail") {
+ this.diffViewerState.viewMode = "list";
+ this.diffViewerState.scrollOffset = 0;
+ } else {
+ this.exitDiffViewer();
+ }
+ this.tui.requestRender();
+ return;
+ }
+
+ if (this.diffViewerState.viewMode === "list") {
+ const visibleFiles = Math.max(1, height - 5);
+ if (matchesKey(data, "up") || data.toLowerCase() === "k") {
+ if (this.diffViewerState.selectedIndex > 0) {
+ this.diffViewerState.selectedIndex--;
+ if (this.diffViewerState.selectedIndex < this.diffViewerState.scrollOffset) {
+ this.diffViewerState.scrollOffset = this.diffViewerState.selectedIndex;
+ }
+ this.tui.requestRender();
+ }
+ return;
+ }
+ if (matchesKey(data, "down") || data.toLowerCase() === "j") {
+ if (this.diffViewerState.selectedIndex < this.diffViewerState.files.length - 1) {
+ this.diffViewerState.selectedIndex++;
+ if (this.diffViewerState.selectedIndex >= this.diffViewerState.scrollOffset + visibleFiles) {
+ this.diffViewerState.scrollOffset = this.diffViewerState.selectedIndex - visibleFiles + 1;
+ }
+ this.tui.requestRender();
+ }
+ return;
+ }
+ if (matchesKey(data, "return")) {
+ const file = this.diffViewerState.files[this.diffViewerState.selectedIndex];
+ if (file) {
+ this.diffViewerState.viewMode = "detail";
+ this.diffViewerState.scrollOffset = 0;
+ this.tui.requestRender();
+ }
+ return;
+ }
+ if (matchesKey(data, "home") || data.toLowerCase() === "g") {
+ this.diffViewerState.selectedIndex = 0;
+ this.diffViewerState.scrollOffset = 0;
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "end") || data.toLowerCase() === "shift+g") {
+ this.diffViewerState.selectedIndex = Math.max(0, this.diffViewerState.files.length - 1);
+ this.diffViewerState.scrollOffset = Math.max(0, this.diffViewerState.files.length - visibleFiles);
+ this.tui.requestRender();
+ return;
+ }
+ return;
+ }
+
+ if (this.diffViewerState.viewMode === "detail") {
+ const file = this.diffViewerState.files[this.diffViewerState.selectedIndex];
+ if (!file) return;
+
+ if (matchesKey(data, "left") || data.toLowerCase() === "h") {
+ this.diffViewerState.viewMode = "list";
+ this.diffViewerState.scrollOffset = 0;
+ this.tui.requestRender();
+ return;
+ }
+
+ const totalLines = this._countDiffLines(file);
+ const availableHeight = Math.max(1, height - 3);
+
+ if (matchesKey(data, "up") || data.toLowerCase() === "k") {
+ this.diffViewerState.scrollOffset = Math.max(0, this.diffViewerState.scrollOffset - 1);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "down") || data.toLowerCase() === "j") {
+ const maxScroll = Math.max(0, totalLines - availableHeight);
+ this.diffViewerState.scrollOffset = Math.min(maxScroll, this.diffViewerState.scrollOffset + 1);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "pageUp")) {
+ this.diffViewerState.scrollOffset = Math.max(0, this.diffViewerState.scrollOffset - availableHeight);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "pageDown")) {
+ const maxScroll = Math.max(0, totalLines - availableHeight);
+ this.diffViewerState.scrollOffset = Math.min(maxScroll, this.diffViewerState.scrollOffset + availableHeight);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "home") || data.toLowerCase() === "g") {
+ this.diffViewerState.scrollOffset = 0;
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "end") || data.toLowerCase() === "shift+g") {
+ const maxScroll = Math.max(0, totalLines - availableHeight);
+ this.diffViewerState.scrollOffset = maxScroll;
+ this.tui.requestRender();
+ return;
+ }
+ return;
+ }
+ }
+
+ private _countDiffLines(file: DiffFileEntry): number {
+ let count = 2;
+ for (const hunk of file.hunks) {
+ count++;
+ count += hunk.lines.length;
+ }
+ return count;
+ }
+
+ private _toRelativePath(absPath: string): string {
+ const cwd = getCurrentCwd() || process.cwd();
+ const normalized = path.resolve(absPath);
+ if (normalized.startsWith(cwd + path.sep) || normalized === cwd) {
+ const rel = path.relative(cwd, normalized);
+ return rel || path.basename(absPath);
+ }
+ return absPath;
+ }
+
+ private _renderDiffDetailLines(file: DiffFileEntry, width: number): string[] {
+ const lines: string[] = [];
+ const displayPath = this._toRelativePath(file.filePath);
+ const label = file.isUntracked ? "(untracked)" : file.isNewFile ? "(new)" : "";
+
+ lines.push(`│ ${displayPath} ${label} +${file.linesAdded} -${file.linesRemoved}`);
+ lines.push(`│ ${"─".repeat(Math.max(0, width - 4))}`);
+
+ for (const hunk of file.hunks) {
+ lines.push(`│ @@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
+ for (const line of hunk.lines) {
+ const display = `│ ${line}`;
+ lines.push(truncateToWidth(display, width, ""));
+ }
+ }
+ return lines;
+ }
+
+ private renderDiffViewer(width: number): string[] {
+ if (!this.diffViewerState) return [];
+
+ const safeWidth = Math.max(1, width);
+ const lines: string[] = [];
+
+ // Title
+ lines.push(padToWidth(palette.border.panel(`━━━ ${this.diffViewerState.title} ━━━`), safeWidth));
+ // Subtitle
+ lines.push(padToWidth(palette.text.dim(` ${this.diffViewerState.subtitle}`), safeWidth));
+ lines.push(padToWidth(palette.text.dim(` ${"─".repeat(Math.max(0, safeWidth - 4))}`), safeWidth));
+
+ if (this.diffViewerState.viewMode === "list") {
+ const availableHeight = Math.max(1, this.tui.terminal.rows - 5);
+
+ for (let i = this.diffViewerState.scrollOffset; i < this.diffViewerState.files.length; i++) {
+ const file = this.diffViewerState.files[i]!;
+ const isSelected = i === this.diffViewerState.selectedIndex;
+ const pointer = isSelected ? "❯ " : " ";
+ const relativePath = this._toRelativePath(file.filePath);
+ const displayPath = relativePath.length > safeWidth - 16
+ ? relativePath.slice(0, safeWidth - 19) + "..."
+ : relativePath;
+ const label = file.isUntracked ? "untracked" : file.source;
+ const stats = `+${file.linesAdded} -${file.linesRemoved}`;
+ const line = `${pointer}${displayPath}`;
+ const padded = padToWidth(line, safeWidth - stats.length - label.length - 3);
+ const fullLine = `${padded}${label} ${stats}`;
+ if (isSelected) {
+ lines.push(palette.text.accent(fullLine));
+ } else {
+ lines.push(fullLine);
+ }
+
+ if (lines.length >= availableHeight + 4) break;
+ }
+ } else {
+ const file = this.diffViewerState.files[this.diffViewerState.selectedIndex];
+ if (!file) return lines;
+
+ const detailLines = this._renderDiffDetailLines(file, safeWidth);
+ const availableHeight = Math.max(1, this.tui.terminal.rows - 4);
+
+ const offset = this.diffViewerState.scrollOffset;
+ const maxLines = Math.min(detailLines.length, offset + availableHeight);
+
+ for (let i = offset; i < maxLines; i++) {
+ lines.push(detailLines[i] || "");
+ }
+
+ const totalLines = detailLines.length;
+ const scrollPercent = totalLines > 0 ? Math.round((offset / totalLines) * 100) : 0;
+ const positionInfo = totalLines > availableHeight
+ ? ` [${offset + 1}-${Math.min(offset + availableHeight, totalLines)}/${totalLines} (${scrollPercent}%)]`
+ : "";
+ const hintText = ` ↑/↓ scroll · ← back · Esc back${positionInfo}`;
+ lines.push(padToWidth(palette.text.dim(hintText), safeWidth));
+ return lines;
+ }
+
+ const hintText = this.diffViewerState.files.length > 0
+ ? " ↑/↓ to select · Enter to view · Esc to close"
+ : " Esc to close";
+ lines.push(padToWidth(palette.text.dim(hintText), safeWidth));
+
+ return lines;
+ }
+
/**
* Ctrl+C / SIGINT 始终尝试向服务端发送当前 session 的中断请求。
* 是否真的存在运行任务由服务端判断;CLI/TUI 本身不退出。
@@ -1430,6 +1723,12 @@ export class AppScreen implements Component, Focusable {
return;
}
+ // DiffViewer mode: handle input separately
+ if (this.diffViewerState) {
+ this.handleDiffViewerInput(data, this.tui.terminal.rows);
+ return;
+ }
+
const snapshot = this.state.getSnapshot();
const pendingQuestion = snapshot.pendingQuestion;
const activeQuestion =
@@ -1450,7 +1749,8 @@ export class AppScreen implements Component, Focusable {
this.toolSelector !== null ||
this.themeList !== null ||
this.swarmWorkflowsViewState !== null ||
- this.configEditorState !== null;
+ this.configEditorState !== null ||
+ this.diffViewerState !== null;
if (!pendingQuestion && !hasOverlay && this.handleTranscriptScrollInput(data)) {
return;
@@ -1879,6 +2179,11 @@ export class AppScreen implements Component, Focusable {
return this.renderFileViewer(width);
}
+ // DiffViewer mode: render diff viewer instead of normal view
+ if (this.diffViewerState) {
+ return this.renderDiffViewer(width);
+ }
+
const snapshot = this.state.getSnapshot();
const teamWorking =
isTeamMode(snapshot.mode) &&
@@ -2249,6 +2554,9 @@ export class AppScreen implements Component, Focusable {
enterFileViewer: (content, title, source) => {
this.enterFileViewer(content, title, source);
},
+ enterDiffViewer: (payload) => {
+ this.enterDiffViewer(payload);
+ },
});
} finally {
this.clearPendingSubmittedInput();
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/diff-component.ts b/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/diff-component.ts
index 13b89d28bf..d002f5445a 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/diff-component.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/diff-component.ts
@@ -3,16 +3,13 @@ import type { HistoryItem, FileDiff, GitDiffFile } from "../../../core/types.js"
import { palette } from "../../theme.js";
import { renderWrappedText } from "../../rendering/text.js";
-const MAX_FILES_PER_SECTION = 5;
-
export class DiffComponent implements Component {
constructor(private readonly entry: Extract<HistoryItem, { kind: "diff" }>) {}
invalidate(): void {}
render(width: number): string[] {
- const showDetail = this.entry.meta.showDetail === true;
- return showDetail ? this._renderDetail(width) : this._renderCompact(width);
+ return this._renderCompact(width);
}
// ── Compact view (default /diff) ──────────────────────────────────
@@ -50,26 +47,13 @@ export class DiffComponent implements Component {
palette.text.accent));
// Tracked
- for (const f of trackedFiles.slice(0, MAX_FILES_PER_SECTION)) {
+ for (const f of trackedFiles) {
lines.push(...this._renderCompactFile(f, innerWidth));
}
- const remainingTracked = trackedFiles.length - MAX_FILES_PER_SECTION;
- if (remainingTracked > 0) {
- lines.push(...renderWrappedText(innerWidth,
- `│ ...and ${remainingTracked} more tracked file(s)`, palette.text.dim));
- }
// Untracked
- if (untrackedFiles.length > 0) {
- const shown = untrackedFiles.slice(0, MAX_FILES_PER_SECTION);
- for (const f of shown) {
- lines.push(...this._renderCompactFile(f, innerWidth, "(untracked)"));
- }
- const remainingUntracked = untrackedFiles.length - MAX_FILES_PER_SECTION;
- if (remainingUntracked > 0) {
- lines.push(...renderWrappedText(innerWidth,
- `│ ...and ${remainingUntracked} more untracked file(s)`, palette.text.dim));
- }
+ for (const f of untrackedFiles) {
+ lines.push(...this._renderCompactFile(f, innerWidth, "(untracked)"));
}
// separator before turns
@@ -89,20 +73,16 @@ export class DiffComponent implements Component {
`│ 📋 Turn ${turn.turnIndex}: "${promptPreview}" +${turn.stats.linesAdded} -${turn.stats.linesRemoved}`,
palette.text.accent));
- for (const f of fileList.slice(0, MAX_FILES_PER_SECTION)) {
+ for (const f of fileList) {
lines.push(...this._renderCompactFile(f, innerWidth));
}
- if (fileList.length > MAX_FILES_PER_SECTION) {
- lines.push(...renderWrappedText(innerWidth,
- `│ ...and ${fileList.length - MAX_FILES_PER_SECTION} more`, palette.text.dim));
- }
}
// Footer
lines.push(...renderWrappedText(innerWidth,
`╰${"─".repeat(innerWidth - 2)}`, palette.text.dim));
lines.push(...renderWrappedText(innerWidth,
- "Use /diff --detail to see full diffs", palette.text.dim));
+ "Press Esc or use /diff to see interactive diff viewer", palette.text.dim));
lines.push("");
return lines;
@@ -124,108 +104,4 @@ export class DiffComponent implements Component {
palette.text.assistant));
return lines;
}
-
- // ── Detail view (/diff --detail) ──────────────────────────────────
-
- private _renderDetail(width: number): string[] {
- const lines: string[] = [];
- const turns = this.entry.meta.turns || [];
- const gitDiff = this.entry.meta.gitDiff || null;
- const innerWidth = Math.max(1, width);
-
- const hasTurns = turns.length > 0;
- const hasGitDiff = gitDiff && gitDiff.stats.filesChanged > 0;
-
- if (!hasTurns && !hasGitDiff) {
- lines.push(...renderWrappedText(innerWidth, "· No file changes in this session", palette.text.dim));
- return lines;
- }
-
- const totalFiles = (gitDiff?.stats.filesChanged ?? 0)
- + turns.reduce((sum, t) => sum + t.stats.filesChanged, 0);
- const totalAdded = (gitDiff?.stats.linesAdded ?? 0)
- + turns.reduce((sum, t) => sum + t.stats.linesAdded, 0);
- const totalRemoved = (gitDiff?.stats.linesRemoved ?? 0)
- + turns.reduce((sum, t) => sum + t.stats.linesRemoved, 0);
-
- lines.push("");
- lines.push(...renderWrappedText(innerWidth,
- `╭─ /diff --detail ${"─".repeat(Math.max(0, innerWidth - 18))}`,
- palette.text.info));
-
- const statsLine = `│ ${totalFiles} files +${totalAdded} -${totalRemoved}`;
- lines.push(...renderWrappedText(innerWidth, statsLine, palette.text.dim));
-
- if (hasGitDiff) {
- lines.push(...renderWrappedText(innerWidth, `├${"─".repeat(innerWidth - 2)}`, palette.text.dim));
- lines.push(...renderWrappedText(innerWidth,
- `│ 🗂 Working Tree +${gitDiff!.stats.linesAdded} -${gitDiff!.stats.linesRemoved}`,
- palette.text.accent));
- for (const [, fileDiff] of Object.entries(gitDiff!.files)) {
- lines.push(...this._renderFileDiff(fileDiff, innerWidth));
- }
- }
-
- for (const turn of turns) {
- lines.push(...renderWrappedText(innerWidth, `├${"─".repeat(innerWidth - 2)}`, palette.text.dim));
- const promptPreview = turn.userPromptPreview.length >= 30
- ? turn.userPromptPreview + "..."
- : turn.userPromptPreview;
- lines.push(...renderWrappedText(innerWidth,
- `│ Turn ${turn.turnIndex}: "${promptPreview}"`,
- palette.text.accent));
- for (const [, fileDiff] of Object.entries(turn.files)) {
- lines.push(...this._renderFileDiff(fileDiff, innerWidth));
- }
- }
-
- lines.push(...renderWrappedText(innerWidth, `╰${"─".repeat(innerWidth - 2)}`, palette.text.dim));
- lines.push("");
-
- return lines;
- }
-
- // ── Shared: full diff with hunks ──────────────────────────────────
-
- private _renderFileDiff(fileDiff: FileDiff | GitDiffFile, width: number): string[] {
- const lines: string[] = [];
- const fileName = fileDiff.filePath.split(/[/\\]/).pop() || fileDiff.filePath;
-
- let timeStr = "";
- if (fileDiff.lastEditTime) {
- const dt = new Date(fileDiff.lastEditTime);
- timeStr = ` [${dt.toLocaleDateString()} ${dt.toLocaleTimeString()}]`;
- }
-
- const header = `│ ${fileName} ${fileDiff.isNewFile ? "(new)" : ""} +${fileDiff.linesAdded} -${fileDiff.linesRemoved}${timeStr}`;
- lines.push(...renderWrappedText(width, header, palette.text.assistant));
-
- const maxHunkLines = 20;
- let totalLines = 0;
-
- for (const hunk of fileDiff.hunks) {
- if (totalLines >= maxHunkLines) {
- lines.push(...renderWrappedText(width, `│ ... (truncated)`, palette.text.dim));
- break;
- }
-
- const hunkHeader = `│ @@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`;
- lines.push(...renderWrappedText(width, hunkHeader, palette.text.dim));
-
- for (const line of hunk.lines) {
- if (totalLines >= maxHunkLines) break;
- totalLines++;
-
- if (line.startsWith("+")) {
- lines.push(...renderWrappedText(width, `│ ${palette.status.success(line)}`, palette.text.dim));
- } else if (line.startsWith("-")) {
- lines.push(...renderWrappedText(width, `│ ${palette.status.error(line)}`, palette.text.dim));
- } else {
- lines.push(...renderWrappedText(width, `│ ${palette.text.dim(line)}`, palette.text.dim));
- }
- }
- }
-
- return lines;
- }
}