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: process rewind info show and logic

ldstyle8c8cdb4ef267e
diff --git a/jiuwenclaw/agents/harness/common/session_ops_service.py b/jiuwenclaw/agents/harness/common/session_ops_service.py
index 22b5bb7979..d0f7882a6a 100644
--- a/jiuwenclaw/agents/harness/common/session_ops_service.py
+++ b/jiuwenclaw/agents/harness/common/session_ops_service.py
@@ -241,6 +241,7 @@ def list_session_turns(
return {"turns": [], "total": 0}
diff_stats_map: dict[int, dict[str, int]] = {}
+ diff_files_map: dict[int, list[dict[str, Any]]] = {}
try:
from jiuwenclaw.server.utils.diff_service import get_diff_service
@@ -251,6 +252,15 @@ def list_session_turns(
ti = td.get("turnIndex")
if isinstance(ti, int) and ti > 0:
diff_stats_map[ti] = td.get("stats", {})
+ files_data: list[dict[str, Any]] = []
+ for fp, finfo in td.get("files", {}).items():
+ files_data.append({
+ "path": fp,
+ "linesAdded": finfo.get("linesAdded", 0),
+ "linesRemoved": finfo.get("linesRemoved", 0),
+ "isNewFile": finfo.get("isNewFile", False),
+ })
+ diff_files_map[ti] = files_data
except Exception as exc:
logger.debug("list_session_turns: diff service unavailable: %s", exc)
@@ -263,7 +273,12 @@ def list_session_turns(
content = record.get("content", "")
if isinstance(content, str) and not _is_selectable_user_message(content):
continue
- preview = content[:80] if isinstance(content, str) else ""
+ if isinstance(content, str):
+ # 剥离 <file-content>...</file-content> 块(系统元数据),只保留用户实际输入
+ cleaned = re.sub(r"<file-content[^>]*>.*?</file-content>", "", content, flags=re.DOTALL)
+ preview = cleaned.strip()[:80]
+ else:
+ preview = ""
stats = diff_stats_map.get(user_count, {
"filesChanged": 0,
"linesAdded": 0,
@@ -276,6 +291,7 @@ def list_session_turns(
"id": record.get("id", ""),
"request_id": record.get("request_id", ""),
"stats": stats,
+ "files": diff_files_map.get(user_count, []),
})
return {"turns": turns, "total": user_count}
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.ts
index 06bff89be7..5a3532449a 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.ts
@@ -1,6 +1,13 @@
import { addCommandEcho, addError, addInfo } from "../helpers.js";
import { CommandKind, type SlashCommand } from "../types.js";
+export interface TurnFileChange {
+ path: string;
+ linesAdded: number;
+ linesRemoved: number;
+ isNewFile: boolean;
+}
+
export interface TurnInfo {
turn_index: number;
content_preview: string;
@@ -12,6 +19,7 @@ export interface TurnInfo {
linesAdded: number;
linesRemoved: number;
};
+ files?: TurnFileChange[];
}
export interface ListTurnsPayload {
@@ -34,6 +42,25 @@ export interface RewindPayload {
/** 恢复选项类型 */
type RestoreOption = "both" | "conversation" | "code" | "cancel";
+const GREEN = "\x1b[32m";
+const RED = "\x1b[31m";
+const RESET = "\x1b[0m";
+
+function toRelativePath(absPath: string, workspaceDir?: string): string {
+ if (!workspaceDir) return absPath;
+ const prefix = workspaceDir.endsWith("/") ? workspaceDir : workspaceDir + "/";
+ if (absPath.startsWith(prefix)) return absPath.slice(prefix.length);
+ return absPath;
+}
+
+function formatFileChange(f: TurnFileChange, workspaceDir?: string): string {
+ const relPath = toRelativePath(f.path, workspaceDir);
+ const prefix = f.isNewFile ? "+" : "";
+ const a = f.linesAdded > 0 ? `${GREEN}+${f.linesAdded}${RESET}` : `+${f.linesAdded}`;
+ const r = f.linesRemoved > 0 ? `${RED}-${f.linesRemoved}${RESET}` : `-${f.linesRemoved}`;
+ return `${prefix}${relPath} (${a}/${r})`;
+}
+
export function createRewindCommand(): SlashCommand {
return {
name: "rewind",
@@ -81,43 +108,46 @@ export function createRewindCommand(): SlashCommand {
}
selectedTurnIndex = parsed;
} else {
- const items = turns.map((t) => {
- const time = t.timestamp
- ? new Date(t.timestamp * 1000).toLocaleString()
- : "-";
- const statsStr =
- t.stats.filesChanged > 0
- ? ` | files: ${t.stats.filesChanged} +${t.stats.linesAdded}/-${t.stats.linesRemoved}`
- : "";
- return {
- label: String(t.turn_index),
- value: `${t.content_preview} | ${time}${statsStr}`,
- };
- });
+ const workspaceDir = ctx.getWorkspaceDir();
- ctx.addItem(
- addInfo(ctx.sessionId, `Conversation Turns (${total} total)`, "r", {
- view: "list",
- title: "Rewind - Select a Turn",
- items,
- }),
- );
+ const turnOptions: { label: string; description: string }[] = [
+ {
+ label: "current",
+ description: "Stay at current session (no change)",
+ },
+ ];
+ for (const t of turns) {
+ let desc = t.content_preview;
+ if (t.files && t.files.length > 0) {
+ const fileList = t.files
+ .map((f) => formatFileChange(f, workspaceDir))
+ .join(", ");
+ desc += ` [${fileList}]`;
+ } else if (t.stats.filesChanged > 0) {
+ desc += ` [files: ${t.stats.filesChanged} +${t.stats.linesAdded}/-${t.stats.linesRemoved}]`;
+ }
+ turnOptions.push({
+ label: String(t.turn_index),
+ description: desc,
+ });
+ }
const answers = await ctx.askQuestions(
[
{
header: "Turn",
question: "Which turn do you want to rewind to? (this turn and all after will be removed)",
- options: turns.map((t) => ({
- label: String(t.turn_index),
- description: t.content_preview,
- })),
+ options: turnOptions,
},
],
"rewind",
);
const userInput = answers[0]?.selected_options?.[0] || answers[0]?.custom_input || "";
+ if (userInput === "current" || !userInput) {
+ ctx.addItem(addInfo(ctx.sessionId, "Rewind cancelled, staying at current session", "c"));
+ return;
+ }
const parsed = parseInt(userInput, 10);
if (Number.isNaN(parsed) || parsed < 1 || parsed > total) {
ctx.addItem(addError(ctx.sessionId, `Invalid turn number: ${userInput}`));
@@ -132,11 +162,13 @@ export function createRewindCommand(): SlashCommand {
return;
}
- // 判断目标 turn 是否有文件变更(决定是否显示 code 相关选项)
- const hasCodeChanges = selectedTurn.stats.filesChanged > 0;
-
// 构建恢复选项
const restoreOptions: { label: string; description: string; value: RestoreOption }[] = [
+ {
+ label: "Cancel",
+ description: "Keep conversation and files as is",
+ value: "cancel",
+ },
{
label: "Restore conversation and code",
description: "Remove this turn and all after; restore modified files to their prior state",
@@ -147,21 +179,12 @@ export function createRewindCommand(): SlashCommand {
description: "Remove this turn and all after; files remain unchanged",
value: "conversation",
},
- ];
-
- if (hasCodeChanges) {
- restoreOptions.push({
+ {
label: "Restore code only",
description: "Restore modified files to their prior state; conversation remains unchanged",
value: "code",
- });
- }
-
- restoreOptions.push({
- label: "Cancel",
- description: "Keep conversation and files as is",
- value: "cancel",
- });
+ },
+ ];
// 局限提示
const limitationNote =
diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
index 0fb17e38f0..95d5e04c45 100644
--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
@@ -2976,8 +2976,8 @@ export class AppScreen implements Component, Focusable {
const reject = question.options.find((option) => option.label === "拒绝");
if (reject) {
this.handleQuestionSelection(reject.label);
- } else if (question.options.length > 0) {
- this.handleQuestionSelection(question.options[0].label);
+ } else {
+ this.handleQuestionSelection("");
}
};
const selectedValue = this.pendingQuestionAnswers.get(this.activeQuestionIndex);
diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface_code.py b/jiuwenclaw/server/runtime/agent_adapter/interface_code.py
index 9586893325..d6a13045fb 100644
--- a/jiuwenclaw/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenclaw/server/runtime/agent_adapter/interface_code.py
@@ -210,6 +210,13 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
)
await self._instance.ensure_initialized()
+ # 修正 .agent_history 写入路径:openjiuwen 文件工具默认将
+ # .agent_history 写到 Workspace.root_path(即项目目录),
+ # 这里覆写为 agent 系统 workspace,避免污染用户项目目录。
+ for rail in getattr(self._instance, '_registered_rails', []):
+ for tool in getattr(rail, 'tools', []) or []:
+ if hasattr(tool, '_workspace_path'):
+ setattr(tool, '_workspace_path', self._agent_workspace_dir)
if self._project_dir:
set_cwd(self._project_dir)
diff --git a/jiuwenclaw/server/utils/diff_service.py b/jiuwenclaw/server/utils/diff_service.py
index 2403c6b8fe..b75a2293e3 100644
--- a/jiuwenclaw/server/utils/diff_service.py
+++ b/jiuwenclaw/server/utils/diff_service.py
@@ -122,9 +122,9 @@ class DiffService:
)
turns_with_files = [t for t in turns if t["files"]]
- for i, turn in enumerate(turns_with_files):
- turn["turnIndex"] = i + 1
-
+ # Keep original turnIndex (aligned with user_count in history)
+ # instead of renumbering — allows list_session_turns to correctly
+ # map stats by the actual turn position.
return turns_with_files
@staticmethod