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(rewind): truncate session-specific file_ops logs on rewind_session

ldstyle85bf200998f07
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.py
index 015ba5c051..91541dbd8d 100644
--- a/jiuwenswarm/agents/harness/common/session_ops_service.py
+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py
@@ -187,6 +187,9 @@ def rewind_session(
# 剥离 <file-content> 块(系统注入的文件元数据,非用户实际输入)
removed_turn_content = re.sub(r"<file-content[^>]*>.*?</file-content>", "", raw, flags=re.DOTALL).strip()
+ # 在截断 history 之前,记录目标 turn 的时间戳(用于后续清理 file_ops)
+ cut_timestamp = history[cut_index].get("timestamp")
+
result = truncate_history_records(session_id=session_id, cut_index=cut_index)
from jiuwenswarm.server.runtime.session.session_metadata import update_session_metadata
@@ -196,6 +199,16 @@ def rewind_session(
set_message_count=result["remaining_records"],
)
+ # 清理 session-specific file_ops 日志,使 turn diff 显示与截断后的 history 一致
+ # 必须在 truncate_history_records 之后调用,但传入截断前获取的时间戳
+ if cut_timestamp is not None:
+ try:
+ from jiuwenswarm.server.utils.diff_service import get_diff_service
+
+ get_diff_service().truncate_file_ops_by_timestamp(session_id, cut_timestamp)
+ except Exception as exc:
+ logger.warning("rewind_session: failed to truncate file_ops: %s", exc)
+
return {
"session_id": session_id,
"turn_index": turn_index,
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
index 6a20d50dfd..9abf5ab2b5 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
@@ -10,6 +10,8 @@ export interface SessionMeta {
created_at?: number;
last_message_at?: number;
message_count?: number;
+ /** 会话所属项目目录(由 gateway 从 channel_metadata 中提取) */
+ project_dir?: string;
}
export interface SessionListPayload {
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 725ba89a7d..b055827fb0 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -14,7 +14,7 @@ import {
truncateToWidth,
} from "@mariozechner/pi-tui";
import { spawnSync } from "node:child_process";
-import { statSync } from "node:fs";
+import { statSync, realpathSync } from "node:fs";
import type { CliPiAppState } from "../app-state.js";
import { openFileInEditor as openInExternalEditor } from "../core/utils/editor.js";
import {
@@ -481,9 +481,14 @@ function wrapPlainText(text: string, width: number): string[] {
return lines.length > 0 ? lines : [text.slice(0, maxWidth)];
}
-function formatSessionTime(timestamp: number | undefined): string {
+function formatRelativeTime(timestamp: number | undefined): string {
if (!timestamp) return "-";
- return new Date(timestamp * 1000).toLocaleString();
+ const diff = Date.now() / 1000 - timestamp;
+ if (diff < 60) return "just now";
+ if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
+ if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
+ if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
+ return new Date(timestamp * 1000).toLocaleDateString();
}
function getDisplayLabel(s: SessionMeta): string {
@@ -491,10 +496,13 @@ function getDisplayLabel(s: SessionMeta): string {
}
function sessionToSelectItem(s: SessionMeta): SelectItem {
+ const parts: string[] = [formatRelativeTime(s.last_message_at)];
+ const msgCount = s.message_count ?? 0;
+ if (msgCount > 0) parts.push(`${msgCount} msgs`);
return {
value: s.session_id,
label: getDisplayLabel(s),
- description: `${s.session_id} · msgs ${s.message_count ?? 0} · ${formatSessionTime(s.last_message_at)}`,
+ description: parts.join(" · "),
};
}
@@ -505,7 +513,11 @@ function buildResumeSessionItems(sessions: SessionMeta[]): SelectItem[] {
function filterResumeSessions(sessions: SessionMeta[], query: string): SelectItem[] {
const normalizedQuery = query.toLowerCase();
return sessions
- .filter((s) => getDisplayLabel(s).toLowerCase().includes(normalizedQuery))
+ .filter((s) => {
+ const label = getDisplayLabel(s).toLowerCase();
+ const sid = s.session_id.toLowerCase();
+ return label.includes(normalizedQuery) || sid.includes(normalizedQuery);
+ })
.map(sessionToSelectItem);
}
@@ -1754,10 +1766,33 @@ export class AppScreen implements Component, Focusable {
if (!nextSessionId) {
return;
}
- // 在清空 resumeSessionList 之前获取 accent_color
+ // 在清空 resumeSessionList 之前获取 accent_color 和项目信息
const sessions = this.resumeSessionList?.sessions ?? [];
const matchedSession = sessions.find((s) => s.session_id === nextSessionId);
const accentColor = matchedSession?.accent_color ?? "default";
+
+ // 跨项目恢复保护(对齐 Claude Code checkCrossProjectResume)
+ // 使用 realpathSync 规范化路径以处理 macOS 符号链接(如 /tmp → /private/tmp)
+ let currentProject = (getCurrentProjectDir() || process.cwd()).trim();
+ let sessionProject = (matchedSession?.project_dir || "").trim();
+ try { currentProject = realpathSync(currentProject); } catch { /* path may not exist */ }
+ if (sessionProject) {
+ try { sessionProject = realpathSync(sessionProject); } catch { /* path may not exist */ }
+ }
+ if (sessionProject && currentProject && sessionProject !== currentProject
+ && !sessionProject.startsWith(currentProject + "/")
+ && !currentProject.startsWith(sessionProject + "/")) {
+ this.resumeSessionList = null;
+ const dirName = sessionProject.split("/").pop() || sessionProject;
+ this.state.addItem(addInfo(
+ this.state.getSnapshot().sessionId,
+ `Session belongs to project "${dirName}". Please cd to that directory first.`,
+ "r",
+ ));
+ this.tui.requestRender();
+ return;
+ }
+
this.resumeSessionList = null;
this.state.updateSession(nextSessionId);
this.state.clearEntries();
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 55f053bc09..26cd37099e 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -665,11 +665,15 @@ class GatewayServer:
params = dict(params)
params.setdefault("mode", mode.value)
- # 从 params 中提取 cwd,注入到 metadata 中以便 message_handler 解析 @file 引用
+ # 从 params 中提取 cwd/project_dir,注入到 metadata 中
+ # cwd 供 message_handler 解析 @file 引用;project_dir 供 session.list 按项目过滤
metadata = {"method": method}
cwd = params.get("cwd")
if cwd and isinstance(cwd, str) and cwd.strip():
metadata["cwd"] = cwd.strip()
+ project_dir = params.get("project_dir")
+ if project_dir and isinstance(project_dir, str) and project_dir.strip():
+ metadata["project_dir"] = project_dir.strip()
is_stream = bool(data.get("is_stream", False))
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 7077c62697..e47450996b 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -984,9 +984,63 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
if isinstance(resp.payload, dict)
else []
)
- cli_sessions = [
- s for s in all_sessions if s.get("channel_id", "") == "tui"
- ][:limit]
+ # 按项目目录过滤 + 排除当前会话(对齐 Claude Code /resume 行为)
+ project_dir = (
+ str(params.get("project_dir", "")).strip()
+ if isinstance(params, dict) else ""
+ )
+ # 规范化路径以处理 macOS 符号链接(如 /tmp → /private/tmp)
+ if project_dir:
+ try:
+ project_dir = os.path.realpath(project_dir)
+ except OSError:
+ pass
+ current_sid = str(session_id or "").strip()
+
+ def _session_matches_project(s):
+ if not project_dir:
+ return True
+ ch_meta = s.get("channel_metadata") or {}
+ session_project = (
+ ch_meta.get("project_dir") or ch_meta.get("cwd") or ""
+ ).strip()
+ if not session_project:
+ return True # 无项目信息的会话作为兜底保留
+ try:
+ session_project = os.path.realpath(session_project)
+ except OSError:
+ pass
+ return (
+ session_project == project_dir
+ or session_project.startswith(project_dir + "/")
+ )
+
+ cli_sessions = []
+ for s in all_sessions:
+ if s.get("channel_id", "") != "tui":
+ continue
+ if not _session_matches_project(s):
+ continue
+ if s.get("session_id", "") == current_sid:
+ continue
+ cli_sessions.append(s)
+ # 按 last_message_at 降序排序(最近活跃优先)
+ cli_sessions.sort(
+ key=lambda s: s.get("last_message_at", 0) or 0, reverse=True
+ )
+ cli_sessions = cli_sessions[:limit]
+
+ # 附带每个会话的 project_dir 供前端判断跨项目恢复
+ for s in cli_sessions:
+ ch_meta = s.get("channel_metadata") or {}
+ sp = (ch_meta.get("project_dir") or ch_meta.get("cwd") or "").strip()
+ if sp:
+ try:
+ sp = os.path.realpath(sp)
+ except OSError:
+ pass
+ s["project_dir"] = sp
+
await channel.send_response(ws, req_id, ok=True, payload={"sessions": cli_sessions})
async def _session_create(ws, req_id, params, session_id):
diff --git a/jiuwenswarm/server/runtime/session/session_metadata.py b/jiuwenswarm/server/runtime/session/session_metadata.py
index 9018e3ae0d..ee8be51d68 100644
--- a/jiuwenswarm/server/runtime/session/session_metadata.py
+++ b/jiuwenswarm/server/runtime/session/session_metadata.py
@@ -5,6 +5,7 @@ import copy
import json
import logging
import queue
+import re
import shutil
import threading
from pathlib import Path
@@ -31,6 +32,34 @@ _TITLE_MAX_LEN = 50
_HEARTBEAT_SESSION_PREFIX = "heartbeat_"
_DELIVERY_KIND_SERVER_PUSH = "server_push"
+# 匹配所有小写 XML 块(对齐 Claude Code stripDisplayTags),
+# 如 <system-reminder>、<file-content>、<command-name> 等系统/工具注入内容
+_INJECTED_TAG_RE = re.compile(
+ r"<([a-z][\w-]*)(?:\s[^>]*)?>.*?</\1>\n?", re.DOTALL
+)
+# 匹配截断的 XML 开始标签(标题被 _TITLE_MAX_LEN 截断时可能只剩开始标签)
+_INJECTED_TAG_START_RE = re.compile(
+ r"<[a-z][\w-]*(?:\s[^>]*)?>?"
+)
+
+
+def _sanitize_title(title: str) -> str:
+ """清理标题中的系统注入 XML 标签(对齐 Claude Code stripDisplayTags)。
+
+ 匹配所有小写 XML 标签(如 <system-reminder>、<file-content>、<command-name>),
+ 不匹配用户提及的大写 HTML/JSX(如 <Button>、<Component>)。
+
+ 处理两种情况:
+ 1. 完整的 <tag>...</tag> 块(正则移除)
+ 2. 被 _TITLE_MAX_LEN 截断的 <tag ... 开头(无闭合标签,整段丢弃)
+ """
+ if not title:
+ return title
+ cleaned = _INJECTED_TAG_RE.sub("", title).strip()
+ if _INJECTED_TAG_START_RE.match(cleaned):
+ return ""
+ return cleaned
+
def _current_timestamp() -> float:
"""返回显式使用 UTC 时区的当前时间戳"""
@@ -125,7 +154,12 @@ def _enqueue_write(session_id: str, metadata: dict[str, Any]) -> None:
def _auto_title(content: str) -> str:
"""从首条用户消息自动生成会话标题"""
- title = content.strip().replace("\n", " ")
+ # 先剥离所有小写 XML 注入标签(对齐 Claude Code stripDisplayTags),
+ # 避免将系统提示/文件注入/工具标签误识别为会话标题
+ cleaned = _INJECTED_TAG_RE.sub("", content).strip()
+ if not cleaned:
+ return ""
+ title = cleaned.replace("\n", " ")
if len(title) > _TITLE_MAX_LEN:
title = title[:_TITLE_MAX_LEN] + "..."
return title
@@ -245,7 +279,13 @@ def get_session_metadata(session_id: str, cache_bust: bool = False) -> dict[str,
session_id: 会话 ID
cache_bust: 强制跳过缓存,直接从磁盘读取(用于跨进程同步场景)
"""
- return _read_metadata(session_id, cache_bust)
+ metadata = _read_metadata(session_id, cache_bust)
+ # 清理已有会话中可能被误写入的系统注入标签标题(<system-reminder>、<file-content> 等)
+ if isinstance(metadata, dict) and metadata.get("title"):
+ sanitized = _sanitize_title(metadata["title"])
+ if sanitized != metadata["title"]:
+ metadata["title"] = sanitized
+ return metadata
def increment_session_round_count(session_id: str) -> int:
@@ -447,6 +487,13 @@ def get_all_sessions_metadata(
sessions.append(metadata)
+ # 清理已有会话中可能被误写入的系统注入标签标题(<system-reminder>、<file-content> 等)
+ for s in sessions:
+ if s.get("title"):
+ sanitized = _sanitize_title(s["title"])
+ if sanitized != s["title"]:
+ s["title"] = sanitized
+
# 按最后消息时间倒序排序
sessions.sort(key=lambda x: x.get("last_message_at", 0), reverse=True)
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index 0ed41310a0..ce6c85cb8f 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -727,6 +727,78 @@ class DiffService:
return files_to_restore
+ def truncate_file_ops_by_timestamp(self, session_id: str, cutoff_ts: float) -> None:
+ """截断 session-specific file_ops 日志,移除 timestamp >= cutoff_ts 的条目.
+
+ 在 rewind 操作后调用,确保 file_ops 日志与截断后的 history.json 一致。
+ 仅处理 session-specific 文件(文件名包含 session_id),不动全局 file_ops。
+
+ Args:
+ session_id: 会话 ID
+ cutoff_ts: 截断阈值(Unix timestamp),>= 此时间的条目将被移除
+ """
+
+ # 收集所有 session-specific file_ops 文件
+ file_ops_paths: list[Path] = []
+ for base_dir in (get_agent_workspace_dir(), get_user_workspace_dir()):
+ hist_dir = base_dir / ".agent_history"
+ if not hist_dir.is_dir():
+ continue
+ for f in hist_dir.iterdir():
+ if self._is_valid_file_ops_file(f.name, session_id, require_session=True):
+ file_ops_paths.append(f)
+
+ # 也从项目目录扫描
+ project_dir = self._get_project_dir_from_metadata(session_id)
+ if project_dir:
+ project_hist_dir = Path(project_dir) / ".agent_history"
+ if project_hist_dir.is_dir():
+ for f in project_hist_dir.iterdir():
+ if self._is_valid_file_ops_file(f.name, session_id, require_session=True):
+ if f not in file_ops_paths:
+ file_ops_paths.append(f)
+
+ for file_ops_path in file_ops_paths:
+ try:
+ data = json.loads(file_ops_path.read_text(encoding="utf-8"))
+ if not isinstance(data, dict):
+ continue
+
+ truncated = False
+ new_data: dict[str, Any] = {}
+ for file_path, entries in data.items():
+ if not isinstance(entries, list):
+ continue
+ filtered = []
+ for e in entries:
+ try:
+ entry_ts = self._iso_to_timestamp(e.get("timestamp", ""))
+ except (ValueError, TypeError):
+ filtered.append(e) # 无法解析的条目保留
+ continue
+ if entry_ts < cutoff_ts:
+ filtered.append(e)
+ if len(filtered) != len(entries):
+ truncated = True
+ if filtered:
+ new_data[file_path] = filtered
+
+ if truncated:
+ file_ops_path.write_text(
+ json.dumps(new_data, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+ logger.info(
+ "truncate_file_ops: cleaned %s (cutoff_ts=%s)",
+ file_ops_path.name, cutoff_ts,
+ )
+ except Exception as exc:
+ logger.warning(
+ "truncate_file_ops: failed to process %s: %s",
+ file_ops_path, exc,
+ )
+
+
_diff_service: DiffService | None = None