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(diff): display git and file_ops info both
ldstyle8a63f06017a59
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.tsindex 62a7dfd194..1af4350a55 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/diff.ts@@ -1,28 +1,43 @@import { addError, addDiff } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";-import type { TurnDiff } from "../../types.js";+import type { TurnDiff, GitDiffData } from "../../types.js";interface DiffPayload {type: "list";turns: TurnDiff[];+ gitDiff?: GitDiffData | null;}export function createDiffCommand(): SlashCommand {return {name: "diff",description: "View uncommitted changes and per-turn diffs",- usage: "/diff",+ usage: "/diff [--detail]",example: "/diff",kind: CommandKind.BUILT_IN,- action: async (ctx) => {+ action: async (ctx, args) => {try {+ const showDetail = /\b--detail\b/.test(args || "");+const payload = await ctx.request<DiffPayload>("command.diff", {});const turns = payload.turns || [];- const summary = turns.length > 0- ? `Found ${turns.length} turn(s) with file changes`+ const gitDiff = payload.gitDiff || null;++ const parts: string[] = [];+ if (gitDiff && gitDiff.stats.filesChanged > 0) {+ parts.push(+ `Working tree: ${gitDiff.stats.filesChanged} files, +${gitDiff.stats.linesAdded} -${gitDiff.stats.linesRemoved}`+ );+ }+ if (turns.length > 0) {+ parts.push(`${turns.length} turn(s) with file changes`);+ }+ const summary = parts.length > 0+ ? parts.join(" | "): "No file changes in this session";+ctx.addItem(- addDiff(ctx.sessionId, summary, { turns }),+ addDiff(ctx.sessionId, summary, { turns, gitDiff, showDetail }),);} catch (error) {const message = error instanceof Error ? error.message : String(error);diff --git a/jiuwenswarm/channels/tui/frontend/src/core/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/types.tsindex dd2ea80d5a..c6e4c17e1e 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/types.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/types.ts@@ -161,8 +161,30 @@ export interface TurnDiff {};}+export interface GitDiffFile {+ filePath: string;+ hunks: Hunk[];+ isNewFile: boolean;+ linesAdded: number;+ linesRemoved: number;+ lastEditTime: string | null;+}++export interface GitDiffStats {+ filesChanged: number;+ linesAdded: number;+ linesRemoved: number;+}++export interface GitDiffData {+ stats: GitDiffStats;+ files: Record<string, GitDiffFile>;+}+export interface DiffMeta {turns: TurnDiff[];+ gitDiff?: GitDiffData | null;+ showDetail?: boolean;}export type HistoryItem =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.tsindex 47f6492d1e..13b89d28bf 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@@ -1,41 +1,179 @@import type { Component } from "@mariozechner/pi-tui";-import type { HistoryItem, FileDiff } from "../../../core/types.js";+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);+ }++ // ── Compact view (default /diff) ──────────────────────────────────++ private _renderCompact(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;+ }++ // Header+ lines.push("");+ lines.push(...renderWrappedText(innerWidth,+ `╭─ /diff ${"─".repeat(Math.max(0, innerWidth - 9))}`,+ palette.text.info));++ // --- Git working tree ---+ if (hasGitDiff) {+ const trackedFiles: GitDiffFile[] = [];+ const untrackedFiles: GitDiffFile[] = [];+ for (const f of Object.values(gitDiff!.files)) {+ (f.isNewFile ? untrackedFiles : trackedFiles).push(f);+ }++ lines.push(...renderWrappedText(innerWidth,+ `│ 🗂 Working Tree +${gitDiff!.stats.linesAdded} -${gitDiff!.stats.linesRemoved}`,+ palette.text.accent));++ // Tracked+ for (const f of trackedFiles.slice(0, MAX_FILES_PER_SECTION)) {+ 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));+ }+ }++ // separator before turns+ if (hasTurns) {+ lines.push(...renderWrappedText(innerWidth, `│ ${"─".repeat(Math.max(0, innerWidth - 3))}`, palette.text.dim));+ }+ }++ // --- Per-turn sections ---+ for (const turn of turns) {+ const fileList = Object.values(turn.files);+ const promptPreview = turn.userPromptPreview.length > 40+ ? turn.userPromptPreview.slice(0, 40) + "..."+ : turn.userPromptPreview;++ lines.push(...renderWrappedText(innerWidth,+ `│ 📋 Turn ${turn.turnIndex}: "${promptPreview}" +${turn.stats.linesAdded} -${turn.stats.linesRemoved}`,+ palette.text.accent));++ for (const f of fileList.slice(0, MAX_FILES_PER_SECTION)) {+ 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));+ lines.push("");++ return lines;+ }++ private _renderCompactFile(+ fileDiff: FileDiff | GitDiffFile,+ width: number,+ tag?: string,+ ): string[] {+ const fileName = fileDiff.filePath.split(/[/\\]/).pop() || fileDiff.filePath;+ const label = tag || (fileDiff.isNewFile ? "(new)" : "");+ const added = palette.status.success(`+${fileDiff.linesAdded}`);+ const removed = palette.status.error(`-${fileDiff.linesRemoved}`);++ const lines: string[] = [];+ lines.push(...renderWrappedText(width,+ `│ ${fileName} ${label} ${added} ${removed}`,+ 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);- if (turns.length === 0) {+ 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 = turns.reduce((sum, t) => sum + t.stats.filesChanged, 0);- const totalAdded = turns.reduce((sum, t) => sum + t.stats.linesAdded, 0);- const totalRemoved = turns.reduce((sum, t) => sum + t.stats.linesRemoved, 0);+ 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, `╭─ Workspace Diff ─${"─".repeat(Math.max(0, innerWidth - 22))}`, palette.text.info));+ lines.push(...renderWrappedText(innerWidth,+ `╭─ /diff --detail ${"─".repeat(Math.max(0, innerWidth - 18))}`,+ palette.text.info));- const statsLine = `│ Turns: ${turns.length} Files: ${totalFiles} +${totalAdded} -${totalRemoved}`;+ const statsLine = `│ ${totalFiles} files +${totalAdded} -${totalRemoved}`;lines.push(...renderWrappedText(innerWidth, statsLine, palette.text.dim));- for (const turn of turns) {+ 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));-+ 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));}@@ -47,16 +185,18 @@ export class DiffComponent implements Component {return lines;}- private _renderFileDiff(fileDiff: FileDiff, width: number): string[] {+ // ── 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));diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 5d57fe3ff8..7969636db8 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -2309,22 +2309,28 @@ class AgentWebSocketServer:project_dir = resolve_request_project_dir(request)diff_service = get_diff_service()turns = diff_service.get_turn_diffs(session_id, project_dir)+ git_diff = diff_service.get_git_diff(project_dir)logger.info(- "[AgentWebSocketServer] command.diff response: session_id=%s turns=%s project_dir=%s",+ "[AgentWebSocketServer] command.diff response: session_id=%s turns=%s git_diff=%s project_dir=%s",session_id,- turns,+ len(turns),+ git_diff is not None,project_dir,)+ payload: dict[str, Any] = {+ "type": "list",+ "turns": turns,+ }+ if git_diff is not None:+ payload["gitDiff"] = git_diff+resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,ok=True,- payload={- "type": "list",- "turns": turns,- },+ payload=payload,)except Exception as e:logger.exception("[AgentWebSocketServer] command.diff failed: %s", e)diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.pyindex 19e2153d79..0ed41310a0 100644--- a/jiuwenswarm/server/utils/diff_service.py+++ b/jiuwenswarm/server/utils/diff_service.py@@ -391,6 +391,269 @@ class DiffService:return hunks+ @staticmethod+ def _run_git_command(project_dir: str, args: list[str]) -> str | None:+ """在 project_dir 中运行 git 命令,返回 stdout 或 None."""+ import subprocess++ try:+ result = subprocess.run(+ ["git"] + args,+ cwd=project_dir,+ capture_output=True,+ text=True,+ timeout=10,+ )+ if result.returncode != 0:+ return None+ return result.stdout+ except Exception:+ return None++ @staticmethod+ def _is_git_repo(project_dir: str) -> bool:+ """检查 project_dir 是否是一个 git 仓库."""+ import subprocess++ try:+ result = subprocess.run(+ ["git", "rev-parse", "--git-dir"],+ cwd=project_dir,+ capture_output=True,+ text=True,+ timeout=5,+ )+ return result.returncode == 0+ except Exception:+ return False++ @staticmethod+ def _parse_git_numstat(output: str) -> dict[str, dict[str, int | bool]]:+ """解析 git diff --numstat 输出为 per-file 统计.++ 输入格式:+ 3\t2\tpath/to/file.py+ -\t-\tbinary_file.png++ 返回:+ { "/abs/path/file.py": {"added": 3, "removed": 2, "isBinary": false}, ... }+ """+ result: dict[str, dict[str, int | bool]] = {}+ for line in output.strip().splitlines():+ if not line.strip():+ continue+ parts = line.split("\t")+ if len(parts) < 3:+ continue+ added_str, removed_str, file_path = parts[0], parts[1], parts[2]+ is_binary = added_str == "-" and removed_str == "-"+ result[file_path] = {+ "added": 0 if is_binary else int(added_str),+ "removed": 0 if is_binary else int(removed_str),+ "isBinary": is_binary,+ }+ return result++ @staticmethod+ def _parse_git_diff_hunks(output: str) -> dict[str, list[dict[str, Any]]]:+ """解析 git diff 输出为按文件分组的 hunk 列表.++ 每个 hunk 格式与 _compute_hunks() 一致:+ {+ "oldStart": int, "oldLines": int,+ "newStart": int, "newLines": int,+ "lines": ["-removed line", "+added line", " context line"],+ }+ """+ import re++ files: dict[str, list[dict[str, Any]]] = {}+ current_file: str | None = None+ current_hunk: dict[str, Any] | None = None++ # 匹配 diff 头部: diff --git a/path b/path, --- a/path, +++ b/path+ # 对于删除文件,+++ b/ 行是 +++ /dev/null 不会匹配,需要回退到 --- a/ 行+ file_header_new_re = re.compile(r"^\+\+\+ b/(.+)$")+ file_header_old_re = re.compile(r"^--- a/(.+)$")+ # 匹配 hunk 头部: @@ -oldStart,oldLines +newStart,newLines @@+ hunk_header_re = re.compile(+ r"^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@"+ )++ for line in output.splitlines():+ # 检测文件头(优先 +++ b/ 行)+ file_match = file_header_new_re.match(line)+ if file_match:+ current_file = file_match.group(1)+ if current_file not in files:+ files[current_file] = []+ current_hunk = None+ continue++ # 回退:对于删除文件,+++ b/ 不匹配(是 +++ /dev/null),+ # 从 --- a/ 行提取文件路径+ file_match = file_header_old_re.match(line)+ if file_match:+ path = file_match.group(1)+ if path != "/dev/null":+ current_file = path+ if current_file not in files:+ files[current_file] = []+ current_hunk = None+ continue++ if current_file is None:+ continue++ # 检测 hunk 头+ hunk_match = hunk_header_re.match(line)+ if hunk_match:+ old_start = int(hunk_match.group(1))+ old_lines = int(hunk_match.group(2) or "1")+ new_start = int(hunk_match.group(3))+ new_lines = int(hunk_match.group(4) or "1")++ current_hunk = {+ "oldStart": old_start,+ "oldLines": old_lines,+ "newStart": new_start,+ "newLines": new_lines,+ "lines": [],+ }+ files[current_file].append(current_hunk)+ continue++ if current_hunk is None:+ continue++ # 收集 hunk 行(+, -, 空格前缀的上下文行)+ if line.startswith("+") or line.startswith("-") or line.startswith(" "):+ current_hunk["lines"].append(line)++ return files++ def _get_untracked_files(+ self, project_dir: str+ ) -> dict[str, dict[str, Any]]:+ """获取未跟踪文件列表并生成合成 diff(全部为新增行)."""+ output = self._run_git_command(+ project_dir,+ ["ls-files", "--others", "--exclude-standard"],+ )+ if not output or not output.strip():+ return {}++ files: dict[str, dict[str, Any]] = {}+ for rel_path in output.strip().splitlines():+ rel_path = rel_path.strip()+ if not rel_path:+ continue+ abs_path = str(Path(project_dir) / rel_path)+ try:+ content = Path(abs_path).read_text(encoding="utf-8", errors="replace")+ except (OSError, ValueError):+ # 二进制文件或无法读取,只记录文件名不含 hunk+ content = None++ if content is not None:+ lines = content.splitlines()+ hunks = [{+ "oldStart": 0,+ "oldLines": 0,+ "newStart": 1,+ "newLines": len(lines),+ "lines": [f"+{line}" for line in lines],+ }]+ lines_added = len(lines)+ else:+ hunks = []+ lines_added = 0++ files[abs_path] = {+ "filePath": abs_path,+ "hunks": hunks,+ "isNewFile": True,+ "linesAdded": lines_added,+ "linesRemoved": 0,+ "lastEditTime": None,+ }++ return files++ def get_git_diff(self, project_dir: str | None) -> dict[str, Any] | None:+ """获取工作区相对于 HEAD 的 git diff.++ 包含两类改动:+ 1. 已跟踪文件的修改(git diff HEAD)+ 2. 未跟踪的新文件(git ls-files --others --exclude-standard)++ Args:+ project_dir: 项目目录路径.++ Returns:+ {+ "stats": {"filesChanged": int, "linesAdded": int, "linesRemoved": int},+ "files": { file_path: { "filePath": str, "hunks": [...],+ "isNewFile": bool, "linesAdded": int, "linesRemoved": int } }+ }+ 如果不是 git 仓库或没有任何改动(含未跟踪文件),返回 None.+ """+ if not project_dir:+ return None+ if not self._is_git_repo(project_dir):+ return None++ files: dict[str, dict[str, Any]] = {}+ total_added = 0+ total_removed = 0++ # 1. 已跟踪文件的改动: git diff HEAD+ shortstat = self._run_git_command(project_dir, ["diff", "HEAD", "--shortstat"])+ has_tracked_changes = shortstat and shortstat.strip() != ""++ if has_tracked_changes:+ numstat_output = self._run_git_command(project_dir, ["diff", "HEAD", "--numstat"])+ diff_output = self._run_git_command(project_dir, ["diff", "HEAD"])+ if numstat_output and diff_output:+ per_file_stats = self._parse_git_numstat(numstat_output)+ all_hunks = self._parse_git_diff_hunks(diff_output)++ for rel_path, stats in per_file_stats.items():+ abs_path = str(Path(project_dir) / rel_path)+ hunks = all_hunks.get(rel_path, [])+ lines_added = stats["added"]+ lines_removed = stats["removed"]+ total_added += lines_added+ total_removed += lines_removed++ files[abs_path] = {+ "filePath": abs_path,+ "hunks": hunks,+ "isNewFile": False,+ "linesAdded": lines_added,+ "linesRemoved": lines_removed,+ "lastEditTime": None,+ }++ # 2. 未跟踪的新文件: git ls-files --others --exclude-standard+ untracked = self._get_untracked_files(project_dir)+ for abs_path, file_info in untracked.items():+ if abs_path not in files: # 避免重复(理论上不会)+ files[abs_path] = file_info+ total_added += file_info["linesAdded"]++ if not files:+ return None++ return {+ "stats": {+ "filesChanged": len(files),+ "linesAdded": total_added,+ "linesRemoved": total_removed,+ },+ "files": files,+ }+@staticmethoddef _finalize_turn(turn: dict[str, Any]) -> None:"""完成 turn 的统计信息计算."""