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(aipc): 新增git状态按照轮次索引
kdgmpw380ab4d61739
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 8e4cf9827f..b213a0ce7f 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -3541,6 +3541,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:project_id = str(params.get("project_id") or "").strip()proj, err, code = _resolve_git_project(project_id)if proj is None:+ if code == "NOT_FOUND":+ code = "PROJECT_NOT_FOUND"await channel.send_response(ws, req_id, ok=False, error=err, code=code, payload={},)@@ -3806,6 +3808,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:project_id = str(params.get("project_id") or "").strip()proj, err, code = _resolve_git_project(project_id)if proj is None:+ if code == "NOT_FOUND":+ code = "PROJECT_NOT_FOUND"await channel.send_response(ws, req_id, ok=False, error=err, code=code, payload={},)@@ -3847,6 +3851,213 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload=status.to_dict(include_hunks=include_hunks),)+ async def _validate_session_project_binding(+ ws: Any, req_id: str, project_id: str, session_id: str,+ ) -> tuple[bool, str | None, str | None]:+ """校验 session 与 project 的绑定关系。"""+ from jiuwenswarm.server.runtime.session.session_metadata import (+ get_session_metadata,+ )+ try:+ session_meta = await asyncio.to_thread(+ get_session_metadata, session_id,+ cache_bust=True, enable_writeback=False,+ )+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "[ProjectGit] failed to read session metadata (session=%s): %s",+ session_id, exc,+ )+ return False, f"failed to read session metadata: {exc}", "INTERNAL_ERROR"+ if not session_meta:+ return False, f"session not found: {session_id}", "SESSION_NOT_FOUND"+ session_project_id = str(session_meta.get("project_id") or "").strip()+ if not session_project_id:+ return False, (+ "session has no project_id binding; cannot verify project ownership"+ ), "SESSION_NOT_BOUND"+ if session_project_id != project_id:+ return False, (+ f"session_id does not belong to project_id: "+ f"expected {project_id}, got {session_project_id}"+ ), "PROJECT_SESSION_MISMATCH"+ return True, None, None++ async def _project_git_turn_diff_list(ws, req_id, params, session_id):+ """查询历史 Diff 摘要列表。"""+ if not isinstance(params, dict):+ params = {}+ project_id = str(params.get("project_id") or "").strip()+ proj, err, code = _resolve_git_project(project_id)+ if proj is None:+ await channel.send_response(+ ws, req_id, ok=False, error=err, code=code, payload={},+ )+ return+ session_id_param = str(params.get("session_id") or "").strip()+ if not session_id_param:+ await channel.send_response(+ ws, req_id, ok=False,+ error="session_id is required", code="BAD_REQUEST",+ )+ return+ ok_val, v_err, v_code = await _validate_session_project_binding(+ ws, req_id, project_id, session_id_param,+ )+ if not ok_val:+ await channel.send_response(+ ws, req_id, ok=False, error=v_err, code=v_code, payload={},+ )+ return+ limit_raw = params.get("limit")+ if limit_raw is None:+ limit = 50+ else:+ try:+ limit = int(limit_raw)+ except (ValueError, TypeError):+ limit = 50+ if limit < 0:+ limit = 50+ cursor_raw = params.get("cursor", 0)+ try:+ cursor = int(cursor_raw)+ except (ValueError, TypeError):+ cursor = 0+ if cursor < 0:+ cursor = 0+ from jiuwenswarm.server.runtime.session.git_diff_status import (+ get_diff_status_service,+ )+ service = get_diff_status_service()+ try:+ result = await asyncio.to_thread(+ service.get_turn_diff_list,+ project=proj,+ session_id=session_id_param,+ limit=limit,+ cursor=cursor,+ )+ except Exception as exc: # noqa: BLE001+ git_error = getattr(exc, "git_error", None)+ if git_error is not None:+ await _send_git_error_response(ws, req_id, git_error)+ return+ logger.warning(+ "[ProjectGit] turn_diff_list failed (project=%s): %s",+ proj.project_id, exc,+ )+ await channel.send_response(+ ws, req_id, ok=False,+ error=f"handler error: {exc}", code="INTERNAL_ERROR",+ )+ return+ await channel.send_response(ws, req_id, ok=True, payload=result)++ async def _project_git_turn_diff(ws, req_id, params, session_id):+ """查询指定轮次 Diff 详情。"""+ if not isinstance(params, dict):+ params = {}+ project_id = str(params.get("project_id") or "").strip()+ proj, err, code = _resolve_git_project(project_id)+ if proj is None:+ await channel.send_response(+ ws, req_id, ok=False, error=err, code=code, payload={},+ )+ return+ session_id_param = str(params.get("session_id") or "").strip()+ if not session_id_param:+ await channel.send_response(+ ws, req_id, ok=False,+ error="session_id is required", code="BAD_REQUEST",+ )+ return+ change_set_id = str(params.get("change_set_id") or "").strip() or None+ turn_index: int | None = None+ if change_set_id is None:+ turn_index_raw = params.get("turn_index")+ try:+ turn_index = int(turn_index_raw)+ except (ValueError, TypeError):+ await channel.send_response(+ ws, req_id, ok=False,+ error="either change_set_id or turn_index (integer) is required",+ code="BAD_REQUEST",+ )+ return++ def _bool_param(name: str, default: bool) -> bool:+ raw = params.get(name, default)+ if isinstance(raw, bool):+ return raw+ if raw is None:+ return default+ if isinstance(raw, (int, float)):+ return bool(raw)+ raw_str = str(raw).strip().lower()+ if raw_str in {"1", "true", "yes", "on"}:+ return True+ if raw_str in {"0", "false", "no", "off"}:+ return False+ return default++ include_hunks = _bool_param("include_hunks", True)+ include_files = _bool_param("include_files", True) or include_hunks+ ok_val, v_err, v_code = await _validate_session_project_binding(+ ws, req_id, project_id, session_id_param,+ )+ if not ok_val:+ await channel.send_response(+ ws, req_id, ok=False, error=v_err, code=v_code, payload={},+ )+ return+ from jiuwenswarm.server.runtime.session.git_diff_status import (+ get_diff_status_service,+ )+ from jiuwenswarm.server.utils.diff_service import DiffHistoryExpiredError+ service = get_diff_status_service()+ try:+ result = await asyncio.to_thread(+ service.get_turn_diff_detail,+ project=proj,+ session_id=session_id_param,+ turn_index=turn_index,+ change_set_id=change_set_id,+ include_files=include_files,+ include_hunks=include_hunks,+ )+ except DiffHistoryExpiredError as exc:+ await channel.send_response(+ ws, req_id, ok=False,+ error=str(exc) or "diff history expired",+ code="DIFF_HISTORY_EXPIRED",+ )+ return+ except Exception as exc: # noqa: BLE001+ git_error = getattr(exc, "git_error", None)+ if git_error is not None:+ await _send_git_error_response(ws, req_id, git_error)+ return+ logger.warning(+ "[ProjectGit] turn_diff failed (project=%s): %s",+ proj.project_id, exc,+ )+ await channel.send_response(+ ws, req_id, ok=False,+ error=f"handler error: {exc}", code="INTERNAL_ERROR",+ )+ return+ if result is None:+ identifier = change_set_id or f"turn_index={turn_index}"+ not_found_code = "CHANGE_SET_NOT_FOUND" if change_set_id else "TURN_DIFF_NOT_FOUND"+ await channel.send_response(+ ws, req_id, ok=False,+ error=f"turn diff not found for {identifier}",+ code=not_found_code,+ )+ return+ await channel.send_response(ws, req_id, ok=True, payload=result)+async def _path_get(ws, req_id, params, session_id):"""读 browser.chrome_path 并返回给前端(会解析环境变量)。"""try:@@ -4975,6 +5186,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("project.git.switch_branch", _project_git_switch_branch)channel.register_method("project.git.create_branch", _project_git_create_branch)channel.register_method("project.git.diff_status", _project_git_diff_status)+ channel.register_method("project.git.turn_diff_list", _project_git_turn_diff_list)+ channel.register_method("project.git.turn_diff", _project_git_turn_diff)channel.register_method("path.get", _path_get)channel.register_method("path.set", _path_set)diff --git a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.pyindex ead19d9431..0bfc67619a 100644--- a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py+++ b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py@@ -589,9 +589,15 @@ class GitDiffWebSocketHandler:# 确保扫描到项目目录下的 session-specific file_ops。restore_errors = restore_result.get("errors", []) or []file_ops_truncated = False+ discarded_change_set_id: str | None = Noneif cut_timestamp > 0 and not restore_errors:from jiuwenswarm.server.utils.diff_service import get_diff_servicediff_service = get_diff_service()+ discarded_change_set_id = await asyncio.to_thread(+ diff_service.mark_turn_discarded,+ session_id, turn_index,+ project_dir=proj.project_dir,+ )await asyncio.to_thread(diff_service.truncate_file_ops_by_timestamp,session_id, cut_timestamp,@@ -616,6 +622,7 @@ class GitDiffWebSocketHandler:payload={"session_id": session_id,"turn_index": turn_index,+ "change_set_id": discarded_change_set_id,"restored_files": restore_result.get("restored_files", []),"deleted_files": restore_result.get("deleted_files", []),"errors": restore_errors,diff --git a/jiuwenswarm/server/runtime/session/git_diff_status.py b/jiuwenswarm/server/runtime/session/git_diff_status.pyindex cfee3b686f..c86c352cb7 100644--- a/jiuwenswarm/server/runtime/session/git_diff_status.py+++ b/jiuwenswarm/server/runtime/session/git_diff_status.py@@ -4,8 +4,7 @@``DiffService.get_git_diff()`` / ``get_turn_diffs()`` 并转换为 snake_case schema,合并 ``ProjectGitService`` 的 repo 状态。-第一版能力边界(§2.7):untracked 文件、staged/unstaged 分类计数不在范围内;-``DiffFileEntry.is_untracked`` 第一版不序列化。+第一版能力边界(§2.7):staged/unstaged 分类计数不在范围内。"""from __future__ import annotations@@ -60,11 +59,7 @@ class DiffHunk:@dataclass(slots=True)class DiffFileEntry:- """单个文件的 diff 条目。-- 注意: ``is_untracked`` 字段第一版不序列化(设计文档 §3.5 实现要求),- ``to_dict`` 不写入该 key。后续版本支持 untracked diff 后再统一输出。- """+ """单个文件的 diff 条目。"""file_path: str = ""status: str = "modified" # modified | added | deleted | renamed | missing@@ -72,7 +67,8 @@ class DiffFileEntry:lines_removed: int = 0is_binary: bool = Falseis_new_file: bool = False- is_untracked: bool = False # 第一版不序列化,仅捕获供后续版本使用+ is_deleted_file: bool = False+ is_untracked: bool = Falseis_large_file: bool = Falseis_truncated: bool = Falsehunks: list[DiffHunk] = field(default_factory=list)@@ -81,11 +77,13 @@ class DiffFileEntry:result: dict[str, Any] = {"file_path": self.file_path,"status": self.status,+ "change_type": self.status,"lines_added": self.lines_added,"lines_removed": self.lines_removed,"is_binary": self.is_binary,"is_new_file": self.is_new_file,- # is_untracked 故意不输出(第一版不支持 untracked 文件分类)+ "is_deleted_file": self.is_deleted_file,+ "is_untracked": self.is_untracked,"is_large_file": self.is_large_file,"is_truncated": self.is_truncated,"hunks": [h.to_dict() for h in self.hunks] if include_hunks else [],@@ -124,9 +122,15 @@ class DiffTurnSummary:stats: DiffStats = field(default_factory=DiffStats)files: dict[str, DiffFileEntry] = field(default_factory=dict)kind: str = "conversation_turn"+ # 阶段 B1: change_set 稳定标识(惰性回填自 change_sets.json)+ change_set_id: str = ""+ request_id: str = ""+ assistant_message_id: str = ""+ user_message_id: str = ""+ status: str = "completed"def to_dict(self, *, include_hunks: bool = True) -> dict[str, Any]:- return {+ result: dict[str, Any] = {"kind": self.kind,"turn_index": self.turn_index,"timestamp": self.timestamp,@@ -137,6 +141,13 @@ class DiffTurnSummary:for k, v in self.files.items()},}+ if self.change_set_id:+ result["change_set_id"] = self.change_set_id+ result["request_id"] = self.request_id+ result["assistant_message_id"] = self.assistant_message_id+ result["user_message_id"] = self.user_message_id+ result["status"] = self.status+ return result@dataclass(slots=True)@@ -202,14 +213,19 @@ def _infer_file_status(entry: dict[str, Any]) -> str:DiffService 原始返回中没有显式 status 字段,按可用信号映射:- ``isUntracked=True`` → ``"added"``(未跟踪文件)- ``isNewFile=True`` → ``"added"``(新增已跟踪文件)+ - ``isDeletedFile=True`` → ``"deleted"``- 其他 → ``"modified"``- 已知局限(设计文档 §2.7): DiffService 不区分 deleted / renamed / missing,- 这些状态在第一版都归为 ``"modified"``。准确区分需增强 DiffService 输出- (如 git status letter),不在本次实现范围。+ 已知局限:历史 rename 需要 file_ops 额外记录 rename 语义,当前只能准确+ 覆盖 added/deleted/modified。"""+ status = entry.get("status") or entry.get("changeType")+ if isinstance(status, str) and status.strip():+ return status.strip()if entry.get("isUntracked") or entry.get("isNewFile"):return "added"+ if entry.get("isDeletedFile"):+ return "deleted"return "modified"@@ -262,6 +278,7 @@ def _convert_file_entry(lines_removed=int(entry.get("linesRemoved", 0) or 0),is_binary=bool(entry.get("isBinary", False)),is_new_file=bool(entry.get("isNewFile", False)),+ is_deleted_file=bool(entry.get("isDeletedFile", False)),is_untracked=bool(entry.get("isUntracked", False)),is_large_file=bool(entry.get("isLargeFile", False)),is_truncated=bool(entry.get("isTruncated", False)),@@ -357,7 +374,95 @@ def _convert_turn_diff(user_prompt_preview=str(turn.get("userPromptPreview", "") or ""),stats=stats,files=files,+ change_set_id=str(turn.get("change_set_id", "") or ""),+ request_id=str(turn.get("request_id", "") or ""),+ assistant_message_id=str(turn.get("assistant_message_id", "") or ""),+ user_message_id=str(turn.get("user_message_id", "") or ""),+ status=str(turn.get("status", "completed") or "completed"),+ )+++def _historical_repo_context(+ turn: dict[str, Any], fallback: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """返回持久化的历史 Git 上下文,缺失时使用当前上下文兜底。"""+ fallback = fallback or {}+ return {+ "repo_root": turn.get("repo_root") or fallback.get("repo_root"),+ "branch": turn.get("branch") or fallback.get("branch"),+ "base_head": turn.get("base_head") or fallback.get("base_head"),+ }+++def _convert_turn_summary(+ turn: dict[str, Any], *, repo_context: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """转换单个 ``get_turn_diffs()`` 返回的 turn 为摘要(不含 hunks)。++ 用于 ``project.git.turn_diff_list`` 摘要接口,响应包含文件列表但不含+ hunk,用于刷新后恢复历史编辑卡片。+ """+ stats = _convert_stats(turn.get("stats"))+ historical_repo = _historical_repo_context(turn, repo_context)+ files = _convert_file_map(+ turn.get("files"),+ repo_root=historical_repo.get("repo_root"),+ include_files=True,+ include_hunks=False,)+ result: dict[str, Any] = {+ "kind": "conversation_turn",+ "turn_index": int(turn.get("turnIndex", 0) or 0),+ "timestamp": str(turn.get("timestamp", "") or ""),+ "user_prompt_preview": str(turn.get("userPromptPreview", "") or ""),+ "stats": stats.to_dict(),+ **historical_repo,+ "files": {+ k: v.to_dict(include_hunks=False)+ for k, v in files.items()+ },+ }+ change_set_id = turn.get("change_set_id")+ if change_set_id:+ result["change_set_id"] = str(change_set_id)+ result["request_id"] = str(turn.get("request_id", "") or "")+ result["assistant_message_id"] = str(turn.get("assistant_message_id", "") or "")+ result["user_message_id"] = str(turn.get("user_message_id", "") or "")+ result["status"] = str(turn.get("status", "completed") or "completed")+ return result+++def _repo_context_from_status(project: Any, *, reject_transient: bool = False) -> dict[str, Any]:+ """读取 Git 上下文,必要时抛出结构化 Git 错误。"""+ from jiuwenswarm.server.runtime.session.project_git import (+ get_project_git_service,+ )+ git_service = get_project_git_service()+ repo_status = git_service.status(project)+ if repo_status.error is not None:+ raise GitOperationError(repo_status.error)+ if reject_transient and repo_status.transient:+ project_id = str(getattr(project, "project_id", "") or "")+ project_dir = str(getattr(project, "project_dir", "") or "")+ raise GitOperationError(GitError(+ "GIT_TRANSIENT_STATE",+ "git is in transient state (merge/rebase)",+ hint="请先解决中间状态(merge/rebase/cherry-pick)后重试",+ retryable=False,+ repo={+ "project_id": project_id,+ "project_dir": project_dir,+ "repo_root": repo_status.repo_root,+ "branch": repo_status.branch,+ "head": repo_status.head,+ "transient": repo_status.transient,+ },+ ))+ return {+ "repo_root": repo_status.repo_root,+ "branch": repo_status.branch,+ "base_head": repo_status.head,+ }class DiffStatusService:@@ -439,7 +544,15 @@ class DiffStatusService:if session_id:diff_service = get_diff_service()try:- turns = diff_service.get_turn_diffs(session_id, project_dir)+ turns = diff_service.get_turn_diffs(+ session_id,+ project_dir,+ repo_context={+ "repo_root": repo_status.repo_root,+ "branch": repo_status.branch,+ "base_head": repo_status.head,+ },+ )except Exception as exc: # noqa: BLE001# 与 get_git_diff 保持对称:错误向上抛,让 handler 感知并触发# 订阅状态回滚。否则 source=last_turn 时会静默@@ -467,6 +580,85 @@ class DiffStatusService:generated_at=time.time(),)+ @staticmethod+ def get_turn_diff_list(+ *,+ project: Any,+ session_id: str,+ limit: int = 50,+ cursor: int = 0,+ ) -> dict[str, Any]:+ """返回历史轮次摘要列表。"""+ project_id = getattr(project, "project_id", "")+ project_dir = getattr(project, "project_dir", "")+ repo_context = _repo_context_from_status(project, reject_transient=True)+ diff_service = get_diff_service()+ turns = diff_service.get_turn_diff_summaries(+ session_id, project_dir, repo_context=repo_context,+ )+ total = len(turns)+ cursor = max(0, int(cursor or 0))+ if cursor > total:+ cursor = total+ page_turns = turns[cursor:]+ if limit > 0:+ page_turns = page_turns[:limit]+ next_cursor = cursor + len(page_turns)+ summaries = [+ _convert_turn_summary(t, repo_context=repo_context)+ for t in page_turns+ ]+ return {+ "project_id": project_id,+ "session_id": session_id,+ **repo_context,+ "turns": summaries,+ "cursor": cursor,+ "next_cursor": next_cursor,+ "has_more": next_cursor < total,+ "limit": limit,+ "total": total,+ }++ @staticmethod+ def get_turn_diff_detail(+ *,+ project: Any,+ session_id: str,+ turn_index: int | None = None,+ change_set_id: str | None = None,+ include_files: bool = True,+ include_hunks: bool = True,+ ) -> dict[str, Any] | None:+ """返回指定轮次详情,优先按 ``change_set_id`` 查询。"""+ project_id = getattr(project, "project_id", "")+ project_dir = getattr(project, "project_dir", "")+ repo_context = _repo_context_from_status(project, reject_transient=True)+ repo_root = repo_context.get("repo_root")++ diff_service = get_diff_service()+ turn = diff_service.get_turn_diff(+ session_id,+ turn_index=turn_index,+ change_set_id=change_set_id,+ project_dir=project_dir,+ repo_context=repo_context,+ )+ if turn is None:+ return None+ turn_summary = _convert_turn_diff(+ turn,+ repo_root=turn.get("repo_root") or repo_root,+ include_files=include_files or include_hunks,+ include_hunks=include_hunks,+ )+ result = turn_summary.to_dict(include_hunks=include_hunks)+ result["project_id"] = project_id+ result["session_id"] = session_id+ result.update(repo_context)+ result.update(_historical_repo_context(turn, repo_context))+ return result+_service_instance: DiffStatusService | None = None@@ -486,8 +678,9 @@ def reset_diff_status_service() -> None:_FILES_EVENT_FIELDS: tuple[str, ...] = (- "file_path", "status", "lines_added", "lines_removed",- "is_binary", "is_new_file", "is_large_file", "is_truncated",+ "file_path", "status", "change_type", "lines_added", "lines_removed",+ "is_binary", "is_new_file", "is_deleted_file", "is_untracked",+ "is_large_file", "is_truncated",)@@ -503,10 +696,13 @@ def file_entry_to_dict_no_hunks(entry: dict[str, Any]) -> dict[str, Any]:return {"file_path": entry.get("file_path", ""),"status": entry.get("status", "modified"),+ "change_type": entry.get("change_type", entry.get("status", "modified")),"lines_added": entry.get("lines_added", 0),"lines_removed": entry.get("lines_removed", 0),"is_binary": entry.get("is_binary", False),"is_new_file": entry.get("is_new_file", False),+ "is_deleted_file": entry.get("is_deleted_file", False),+ "is_untracked": entry.get("is_untracked", False),"is_large_file": entry.get("is_large_file", False),"is_truncated": entry.get("is_truncated", False),"hunks": [],@@ -581,7 +777,12 @@ def build_turn_summary_entry(last_turn: dict[str, Any] | None) -> dict[str, Any]return Nonereturn {"kind": last_turn.get("kind", "conversation_turn"),+ "change_set_id": last_turn.get("change_set_id", ""),"turn_index": last_turn.get("turn_index", 0),+ "request_id": last_turn.get("request_id", ""),+ "assistant_message_id": last_turn.get("assistant_message_id", ""),+ "user_message_id": last_turn.get("user_message_id", ""),+ "status": last_turn.get("status", "completed"),"stats": last_turn.get("stats", {}),"files": {},}diff --git a/jiuwenswarm/server/runtime/session/git_diff_watcher.py b/jiuwenswarm/server/runtime/session/git_diff_watcher.pyindex c711635b70..ce043cafe9 100644--- a/jiuwenswarm/server/runtime/session/git_diff_watcher.py+++ b/jiuwenswarm/server/runtime/session/git_diff_watcher.py@@ -990,14 +990,14 @@ class GitDiffWatcherRegistry:files_fp = _files_fingerprint(files_dict)if files_fp != watch.last_files_fingerprint:watch.last_files_fingerprint = files_fp- await self._push_files_changed(watch, files_dict, files_fp)+ await self._push_files_changed(watch, status_dict, files_dict, files_fp)if watch.detail_source and watch.detail_files:files_dict = self._extract_files(status_dict, watch.detail_source)detail_fp = _detail_fingerprint(files_dict, watch.detail_files)if detail_fp != watch.last_detail_fingerprint:watch.last_detail_fingerprint = detail_fp- await self._push_detail_changed(watch, files_dict, detail_fp)+ await self._push_detail_changed(watch, status_dict, files_dict, detail_fp)@staticmethoddef _extract_files(@@ -1086,6 +1086,7 @@ class GitDiffWatcherRegistry:async def _push_files_changed(self,watch: GitDiffWatch,+ status_dict: dict[str, Any],files_dict: dict[str, Any] | None,fingerprint: str,) -> None:@@ -1105,6 +1106,8 @@ class GitDiffWatcherRegistry:"revision": _build_revision("gitdiff", fingerprint),"files": files_no_hunks,}+ if watch.files_source == "last_turn":+ payload.update(self._last_turn_event_metadata(status_dict))try:await self._channel.send_event(watch.ws, "project.git.diff_files_changed", payload,@@ -1120,6 +1123,7 @@ class GitDiffWatcherRegistry:async def _push_detail_changed(self,watch: GitDiffWatch,+ status_dict: dict[str, Any],files_dict: dict[str, Any] | None,fingerprint: str,) -> None:@@ -1143,6 +1147,8 @@ class GitDiffWatcherRegistry:"revision": _build_revision("gitdiff", fingerprint),"files": detail_files,}+ if watch.detail_source == "last_turn":+ payload.update(self._last_turn_event_metadata(status_dict))try:await self._channel.send_event(watch.ws, "project.git.diff_detail_changed", payload,@@ -1155,6 +1161,21 @@ class GitDiffWatcherRegistry:)await self._on_push_failure(watch)+ @staticmethod+ def _last_turn_event_metadata(status_dict: dict[str, Any]) -> dict[str, Any]:+ """提取 last_turn 的稳定绑定元数据。"""+ last_turn = status_dict.get("last_turn")+ if not isinstance(last_turn, dict):+ return {}+ return {+ "change_set_id": last_turn.get("change_set_id", ""),+ "turn_index": last_turn.get("turn_index", 0),+ "assistant_message_id": last_turn.get("assistant_message_id", ""),+ "user_message_id": last_turn.get("user_message_id", ""),+ "request_id": last_turn.get("request_id", ""),+ "status": last_turn.get("status", "completed"),+ }+async def _on_push_failure(self, watch: GitDiffWatch) -> None:"""推送失败计数;连续失败达到阈值后回收 watcher。diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.pyindex 9ab4d753b1..2a1330a887 100644--- a/jiuwenswarm/server/utils/diff_service.py+++ b/jiuwenswarm/server/utils/diff_service.py@@ -5,8 +5,11 @@from __future__ import annotationsimport difflib+import copyimport jsonimport logging+import threading+import uuidfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any@@ -23,6 +26,13 @@ MAX_DIFF_SIZE_BYTES = 1_000_000MAX_LINES_PER_FILE = 400MAX_FILES_FOR_DETAILS = 500+# change_sets.json 写入锁:保证同一进程内多线程惰性回填时不互相覆盖。+_CHANGE_SET_LOCK = threading.Lock()+++class DiffHistoryExpiredError(RuntimeError):+ """历史 diff 索引仍存在但详情已无法重建。"""+class DiffService:"""提供 turn-based diff 查询服务."""@@ -30,7 +40,12 @@ class DiffService:def __init__(self) -> None:self._agent_id = "jiuwenswarm"- def get_turn_diffs(self, session_id: str, project_dir: str | None = None) -> list[dict[str, Any]]:+ def get_turn_diffs(+ self,+ session_id: str,+ project_dir: str | None = None,+ repo_context: dict[str, Any] | None = None,+ ) -> list[dict[str, Any]]:"""获取 session 的所有 turn diff(完整信息).Args:@@ -41,8 +56,106 @@ class DiffService:turn diff 列表,按时间倒序排列(most recent first)"""turns = self._compute_turn_diffs(session_id, project_dir)+ self._enrich_with_change_sets(session_id, turns, repo_context=repo_context)return list(reversed(turns))+ def get_turn_diff_summaries(+ self,+ session_id: str,+ project_dir: str | None = None,+ repo_context: dict[str, Any] | None = None,+ ) -> list[dict[str, Any]]:+ """获取 session 的历史 turn diff 摘要,包含已持久化快照。++ 与 ``get_turn_diffs`` 不同,此方法会把当前 file_ops 已经无法重建、+ 但仍存在于 change_sets/snapshot 中的历史轮次也返回出来(例如已撤销+ 的 turn)。+ """+ turns = self._compute_turn_diffs(session_id, project_dir)+ self._enrich_with_change_sets(session_id, turns, repo_context=repo_context)+ by_turn = {int(t.get("turnIndex", 0) or 0): t for t in turns}+ for entry in self._load_change_sets(session_id):+ try:+ turn_index = int(entry.get("turn_index", 0) or 0)+ except (TypeError, ValueError):+ continue+ if turn_index <= 0 or turn_index in by_turn:+ continue+ snapshot = self._load_turn_snapshot(session_id, str(entry.get("change_set_id") or ""))+ if snapshot is None:+ snapshot = self._turn_from_change_set_entry(entry)+ by_turn[turn_index] = snapshot+ return sorted(+ by_turn.values(),+ key=lambda t: int(t.get("turnIndex", 0) or 0),+ reverse=True,+ )++ def get_turn_diff(+ self,+ session_id: str,+ *,+ turn_index: int | None = None,+ change_set_id: str | None = None,+ project_dir: str | None = None,+ repo_context: dict[str, Any] | None = None,+ ) -> dict[str, Any] | None:+ """获取指定轮次的 turn diff。++ 优先按 ``change_set_id`` 查询;未提供时按 ``turn_index`` 查询。+ 两者均不提供时返回 None。++ Args:+ session_id: 会话 ID+ turn_index: 轮次序号(1-based,与 get_turn_diffs 返回的 turnIndex 对齐)+ change_set_id: 变更集 ID(优先于 turn_index)+ project_dir: 项目目录路径(可选,若不提供则从 session metadata 读取)++ Returns:+ 匹配轮次的 turn diff dict;未命中时返回 None。+ """+ if change_set_id is None and turn_index is None:+ return None+ if change_set_id is not None:+ entries = self._load_change_sets(session_id)+ indexed_entry = None+ for entry in entries:+ if str(entry.get("change_set_id") or "") == change_set_id:+ indexed_entry = entry+ break+ if indexed_entry is None:+ if self._load_turn_snapshot(session_id, change_set_id) is not None:+ raise DiffHistoryExpiredError(+ f"diff history expired for change_set_id={change_set_id}"+ )+ return None+ snapshot = self._load_turn_snapshot(session_id, change_set_id)+ if snapshot is not None:+ return snapshot+ turns = self.get_turn_diffs(session_id, project_dir, repo_context=repo_context)+ for turn in turns:+ if turn.get("change_set_id") == change_set_id:+ return turn+ raise DiffHistoryExpiredError(+ f"diff history expired for change_set_id={change_set_id}"+ )+ turns = self.get_turn_diffs(session_id, project_dir, repo_context=repo_context)+ for turn in turns:+ if int(turn.get("turnIndex", 0) or 0) == turn_index:+ return turn+ if turn_index is not None:+ for entry in self._load_change_sets(session_id):+ if int(entry.get("turn_index", 0) or 0) == turn_index:+ snapshot = self._load_turn_snapshot(+ session_id, str(entry.get("change_set_id") or "")+ )+ if snapshot is not None:+ return snapshot+ raise DiffHistoryExpiredError(+ f"diff history expired for turn_index={turn_index}"+ )+ return None+def _compute_turn_diffs(self, session_id: str, project_dir: str | None = None) -> list[dict[str, Any]]:"""计算 turn-based diffs."""history = self._read_history(session_id)@@ -72,6 +185,9 @@ class DiffService:"timestamp": self._timestamp_to_iso(record["timestamp"]),"start_timestamp": turn_start,"end_timestamp": turn_end,+ "request_id": record.get("request_id", ""),+ "user_message_id": record.get("id", ""),+ "assistant_message_id": self._find_assistant_message_id(history, i),"files": {},"stats": {"filesChanged": 0,@@ -95,6 +211,7 @@ class DiffService:"filePath": file_path,"hunks": [],"isNewFile": False,+ "isDeletedFile": False,"isBinary": False,"isLargeFile": False,"isTruncated": False,@@ -116,6 +233,8 @@ class DiffService:if op["action"] == "write" and op["old_content"] is None:turn["files"][file_path]["isNewFile"] = True+ if op["new_content"] is None and op["old_content"] is not None:+ turn["files"][file_path]["isDeletedFile"] = Truefor hunk in hunks:for line in hunk["lines"]:@@ -138,6 +257,231 @@ class DiffService:# map stats by the actual turn position.return turns_with_files+ @staticmethod+ def _change_sets_path(session_id: str) -> Path:+ return get_agent_sessions_dir() / session_id / "change_sets.json"++ @staticmethod+ def _change_set_snapshots_dir(session_id: str) -> Path:+ return get_agent_sessions_dir() / session_id / "change_sets"++ @classmethod+ def _change_set_snapshot_path(cls, session_id: str, change_set_id: str) -> Path:+ safe_id = "".join(ch if ch.isalnum() or ch in ("-", "_") else "_" for ch in change_set_id)+ return cls._change_set_snapshots_dir(session_id) / f"{safe_id}.json"++ def _load_change_sets(self, session_id: str) -> list[dict[str, Any]]:+ path = self._change_sets_path(session_id)+ if not path.exists():+ return []+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ if isinstance(data, list):+ return data+ except (json.JSONDecodeError, OSError) as exc:+ logger.warning("Failed to read change_sets.json (%s): %s", path, exc)+ return []++ def _save_change_sets(self, session_id: str, change_sets: list[dict[str, Any]]) -> None:+ path = self._change_sets_path(session_id)+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")+ tmp_path.write_text(+ json.dumps(change_sets, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ tmp_path.replace(path)+ except OSError as exc:+ logger.warning("Failed to write change_sets.json (%s): %s", path, exc)+ try:+ if "tmp_path" in locals() and tmp_path.exists():+ tmp_path.unlink()+ except OSError:+ pass++ def _load_turn_snapshot(self, session_id: str, change_set_id: str) -> dict[str, Any] | None:+ if not change_set_id:+ return None+ path = self._change_set_snapshot_path(session_id, change_set_id)+ if not path.exists():+ return None+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ if isinstance(data, dict):+ return data+ except (json.JSONDecodeError, OSError) as exc:+ logger.warning("Failed to read change_set snapshot (%s): %s", path, exc)+ return None++ def _save_turn_snapshot(self, session_id: str, turn: dict[str, Any]) -> None:+ change_set_id = str(turn.get("change_set_id") or "")+ if not change_set_id:+ return+ path = self._change_set_snapshot_path(session_id, change_set_id)+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")+ tmp_path.write_text(+ json.dumps(turn, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ tmp_path.replace(path)+ except OSError as exc:+ logger.warning("Failed to write change_set snapshot (%s): %s", path, exc)+ try:+ if "tmp_path" in locals() and tmp_path.exists():+ tmp_path.unlink()+ except OSError:+ pass++ @staticmethod+ def _entry_matches_turn(entry: dict[str, Any], turn: dict[str, Any]) -> bool:+ """校验 change_set entry 是否仍属于当前 turn。"""+ entry_rid = str(entry.get("request_id", "") or "")+ turn_rid = str(turn.get("request_id", "") or "")+ entry_ts = str(entry.get("timestamp", "") or "")+ turn_ts = str(turn.get("timestamp", "") or "")+ if not entry_ts or entry_ts != turn_ts:+ return False+ if entry_rid or turn_rid:+ return bool(entry_rid and turn_rid and entry_rid == turn_rid)+ return True++ @staticmethod+ def _turn_from_change_set_entry(entry: dict[str, Any]) -> dict[str, Any]:+ return {+ "turnIndex": int(entry.get("turn_index", 0) or 0),+ "timestamp": str(entry.get("timestamp", "") or ""),+ "start_timestamp": entry.get("start_timestamp"),+ "end_timestamp": entry.get("end_timestamp"),+ "userPromptPreview": str(entry.get("user_prompt_preview", "") or ""),+ "request_id": str(entry.get("request_id", "") or ""),+ "change_set_id": str(entry.get("change_set_id", "") or ""),+ "assistant_message_id": str(entry.get("assistant_message_id", "") or ""),+ "user_message_id": str(entry.get("user_message_id", "") or ""),+ "status": str(entry.get("status", "completed") or "completed"),+ "repo_root": entry.get("repo_root"),+ "branch": entry.get("branch"),+ "base_head": entry.get("base_head"),+ "stats": entry.get("stats") if isinstance(entry.get("stats"), dict) else {+ "filesChanged": 0,+ "linesAdded": 0,+ "linesRemoved": 0,+ },+ "files": {},+ }++ @staticmethod+ def _apply_change_set_entry(turn: dict[str, Any], entry: dict[str, Any]) -> None:+ turn["change_set_id"] = entry.get("change_set_id", "")+ turn["request_id"] = entry.get("request_id", "") or turn.get("request_id", "")+ turn["assistant_message_id"] = entry.get("assistant_message_id", "")+ turn["user_message_id"] = entry.get("user_message_id", "")+ turn["status"] = entry.get("status", "completed")+ turn["repo_root"] = entry.get("repo_root")+ turn["branch"] = entry.get("branch")+ turn["base_head"] = entry.get("base_head")++ @staticmethod+ def _new_change_set_entry(+ session_id: str,+ turn: dict[str, Any],+ turn_index: int,+ repo_context: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ request_id = str(turn.get("request_id", "") or "")+ cs_id = f"cs_{session_id}_{turn_index}_{uuid.uuid4().hex[:8]}"+ user_msg_id = str(turn.get("user_message_id", "") or "")+ assistant_msg_id = str(turn.get("assistant_message_id", "") or "")+ if request_id:+ user_msg_id = user_msg_id or f"{request_id}:user"+ assistant_msg_id = assistant_msg_id or f"{request_id}:assistant"+ repo_context = repo_context or {}+ return {+ "change_set_id": cs_id,+ "turn_index": turn_index,+ "request_id": request_id,+ "assistant_message_id": assistant_msg_id,+ "user_message_id": user_msg_id,+ "timestamp": turn.get("timestamp", ""),+ "start_timestamp": turn.get("start_timestamp"),+ "end_timestamp": turn.get("end_timestamp"),+ "user_prompt_preview": turn.get("userPromptPreview", ""),+ "status": "completed",+ "repo_root": repo_context.get("repo_root") or turn.get("repo_root"),+ "branch": repo_context.get("branch") or turn.get("branch"),+ "base_head": repo_context.get("base_head") or turn.get("base_head"),+ "stats": copy.deepcopy(turn.get("stats", {})),+ }++ def mark_turn_discarded(+ self, session_id: str, turn_index: int, project_dir: str | None = None+ ) -> str | None:+ """将指定 turn 的 change_set 状态标记为 discarded。"""+ if turn_index <= 0:+ return None+ target = self.get_turn_diff(+ session_id, turn_index=turn_index, project_dir=project_dir,+ )+ change_set_id = str((target or {}).get("change_set_id") or "")+ if not change_set_id:+ return None+ with _CHANGE_SET_LOCK:+ entries = self._load_change_sets(session_id)+ changed = False+ for entry in entries:+ if entry.get("change_set_id") == change_set_id:+ entry["status"] = "discarded"+ changed = True+ break+ if changed:+ self._save_change_sets(session_id, entries)+ snapshot = self._load_turn_snapshot(session_id, change_set_id) or target+ if snapshot is not None:+ snapshot["status"] = "discarded"+ self._save_turn_snapshot(session_id, snapshot)+ return change_set_id++ def _enrich_with_change_sets(+ self,+ session_id: str,+ turns: list[dict[str, Any]],+ repo_context: dict[str, Any] | None = None,+ ) -> None:+ """惰性回填 change_set 索引并合并元数据到每轮 turn。"""+ if not turns:+ return+ with _CHANGE_SET_LOCK:+ existing = self._load_change_sets(session_id)+ index_by_turn: dict[int, dict[str, Any]] = {}+ for entry in existing:+ ti = entry.get("turn_index")+ if isinstance(ti, int):+ index_by_turn[ti] = entry++ new_entries: list[dict[str, Any]] = []+ for turn in turns:+ turn_index = int(turn.get("turnIndex", 0) or 0)+ entry = index_by_turn.get(turn_index)+ if entry is not None and self._entry_matches_turn(entry, turn):+ self._apply_change_set_entry(turn, entry)+ else:+ entry = self._new_change_set_entry(+ session_id, turn, turn_index, repo_context=repo_context,+ )+ self._apply_change_set_entry(turn, entry)+ new_entries.append(entry)+ index_by_turn[turn_index] = entry+ self._save_turn_snapshot(session_id, turn)++ if new_entries:+ all_entries = sorted(+ list(index_by_turn.values()),+ key=lambda e: e.get("turn_index", 0),+ )+ self._save_change_sets(session_id, all_entries)+@staticmethoddef _is_turn_end(record: dict[str, Any]) -> bool:"""判断一条记录是否是 turn 的结束."""@@ -158,6 +502,25 @@ class DiffService:return history[j]["timestamp"]return None+ @staticmethod+ def _find_assistant_message_id(+ history: list[dict[str, Any]], user_index: int+ ) -> str:+ """查找当前 user turn 后第一条 assistant 消息 ID。"""+ request_id = str(history[user_index].get("request_id", "") or "")+ for j in range(user_index + 1, len(history)):+ record = history[j]+ if record.get("role") == "user":+ break+ if record.get("role") != "assistant":+ continue+ if request_id:+ assistant_request_id = str(record.get("request_id", "") or "")+ if assistant_request_id and assistant_request_id != request_id:+ continue+ return str(record.get("id", "") or "")+ return ""+@staticmethoddef _read_history(session_id: str) -> list[dict[str, Any]]:"""读取 session history."""@@ -715,6 +1078,67 @@ class DiffService:}return result+ @staticmethod+ def _parse_git_name_status(output: str) -> dict[str, str]:+ """解析 git diff --name-status 输出为路径到状态的映射。"""+ result: dict[str, str] = {}+ for line in (output or "").splitlines():+ if not line.strip():+ continue+ parts = line.split("\t")+ if len(parts) < 2:+ continue+ code = parts[0].strip()+ status_letter = code[0] if code else "M"+ if status_letter == "R" and len(parts) >= 3:+ path = "\t".join(parts[2:])+ else:+ path = "\t".join(parts[1:])+ path = DiffService._unquote_git_path(path)+ status = {+ "A": "added",+ "D": "deleted",+ "R": "renamed",+ "C": "added",+ "T": "modified",+ "M": "modified",+ }.get(status_letter, "modified")+ result[path] = status+ return result++ @staticmethod+ def _parse_git_porcelain_status(output: str) -> dict[str, str]:+ """解析 git status --porcelain=v1 输出为路径到状态的映射。"""+ result: dict[str, str] = {}+ for line in (output or "").splitlines():+ if len(line) < 4:+ continue+ x_status = line[0]+ y_status = line[1]+ raw_path = line[3:]+ if raw_path.startswith('"'):+ path = DiffService._unquote_git_path(raw_path)+ elif " -> " in raw_path:+ path = raw_path.rsplit(" -> ", 1)[-1]+ else:+ path = raw_path+ path = DiffService._unquote_git_path(path.strip())++ if x_status == "?" and y_status == "?":+ status = "added"+ elif "R" in (x_status, y_status):+ status = "renamed"+ elif y_status == "D" and x_status != "D":+ status = "missing"+ elif x_status == "D" or y_status == "D":+ status = "deleted"+ elif x_status == "A" or y_status == "A":+ status = "added"+ else:+ status = "modified"+ result[path] = status+ return result+@staticmethoddef _parse_shortstat(output: str) -> dict[str, int] | None:"""解析 git diff --shortstat 输出.@@ -954,9 +1378,17 @@ class DiffService:if has_tracked_changes:numstat_output = self._run_git_command(repo_dir, ["diff", "HEAD", "--numstat"])+ name_status_output = self._run_git_command(repo_dir, ["diff", "HEAD", "--name-status"])+ porcelain_status_output = self._run_git_command(+ repo_dir, ["-c", "core.quotepath=false", "status", "--porcelain=v1"]+ )diff_output = self._run_git_command(repo_dir, ["diff", "HEAD"])if numstat_output and diff_output:per_file_stats = self._parse_git_numstat(numstat_output)+ per_file_status = self._parse_git_name_status(name_status_output or "")+ per_file_status.update(+ self._parse_git_porcelain_status(porcelain_status_output or "")+ )total_files_changed += len(per_file_stats)total_added += sum(int(stats["added"]) for stats in per_file_stats.values())total_removed += sum(int(stats["removed"]) for stats in per_file_stats.values())@@ -977,8 +1409,10 @@ class DiffService:files[abs_path] = {"filePath": abs_path,+ "status": per_file_status.get(rel_path, "modified"),"hunks": hunks,- "isNewFile": False,+ "isNewFile": per_file_status.get(rel_path) == "added",+ "isDeletedFile": per_file_status.get(rel_path) == "deleted","isBinary": is_binary,"isLargeFile": is_large,"isTruncated": is_truncated,@@ -988,6 +1422,12 @@ class DiffService:"lastEditTime": None,}+ untracked_files = self._get_untracked_files(repo_dir, max_files=max(0, MAX_FILES - len(files)))+ for file_path, entry in untracked_files.items():+ entry["status"] = "added"+ files[file_path] = entry+ total_files_changed += len(untracked_files)+if not files:return Nonediff --git a/tests/unit_tests/server/test_diff_service.py b/tests/unit_tests/server/test_diff_service.pyindex d779c791cc..2cf398281b 100644--- a/tests/unit_tests/server/test_diff_service.py+++ b/tests/unit_tests/server/test_diff_service.py@@ -1,4 +1,5 @@import json+import osimport subprocessfrom pathlib import Path@@ -11,7 +12,7 @@ def _git(repo: Path, *args: str) -> None:subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True)-def test_git_diff_from_subdir_excludes_untracked_files(tmp_path):+def test_git_diff_from_subdir_includes_untracked_files(tmp_path):repo = tmp_path / "repo"repo.mkdir()_git(repo, "init")@@ -33,8 +34,13 @@ def test_git_diff_from_subdir_excludes_untracked_files(tmp_path):assert diff is not Noneassert str(tracked) in diff["files"]- assert str(untracked) not in diff["files"]- assert diff["stats"]["filesChanged"] == 1+ assert str(untracked) in diff["files"]+ untracked_info = diff["files"][str(untracked)]+ assert untracked_info["status"] == "added"+ assert untracked_info["isNewFile"] is True+ assert untracked_info["isUntracked"] is True+ assert untracked_info["hunks"] == []+ assert diff["stats"]["filesChanged"] == 2assert diff["stats"]["linesAdded"] == 1assert diff["stats"]["linesRemoved"] == 1@@ -66,6 +72,7 @@ def test_git_diff_stats_include_tracked_files_beyond_detail_cap(tmp_path):assert diff["stats"]["linesRemoved"] == 60[email protected](os.name == "nt", reason="Windows paths cannot contain tab characters")def test_git_diff_preserves_tabs_in_file_paths(tmp_path):repo = tmp_path / "repo"repo.mkdir()diff --git a/tests/unit_tests/server/test_turn_diff_history.py b/tests/unit_tests/server/test_turn_diff_history.pynew file mode 100644index 0000000000..8779615a26--- /dev/null+++ b/tests/unit_tests/server/test_turn_diff_history.py@@ -0,0 +1,655 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""逐轮 Diff 历史查询测试。"""++from __future__ import annotations++from datetime import datetime, timezone+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from jiuwenswarm.server.runtime.session.git_diff_status import (+ DiffFileEntry,+ DiffStatusService,+)+from jiuwenswarm.server.runtime.session.project_git import GitError, GitOperationError+from jiuwenswarm.server.utils.diff_service import DiffHistoryExpiredError, DiffService++[email protected](autouse=True)+def _avoid_snapshot_disk_io(monkeypatch):+ monkeypatch.setattr(DiffService, "_load_turn_snapshot", lambda self, session_id, change_set_id: None)+ monkeypatch.setattr(DiffService, "_save_turn_snapshot", lambda self, session_id, turn: None)++[email protected](autouse=True)+def _default_git_service(monkeypatch):+ service = SimpleNamespace(+ status=lambda project: SimpleNamespace(+ error=None,+ repo_root="/proj",+ branch="main",+ head="abc123",+ transient=False,+ ),+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.project_git.get_project_git_service",+ lambda: service,+ )+++def _ts(epoch: float) -> str:+ return datetime.fromtimestamp(epoch, tz=timezone.utc).isoformat()+++_HISTORY: list[dict] = [+ {"role": "user", "timestamp": 1784542845.0, "content": "first prompt",+ "request_id": "req-001", "id": "req-001:user"},+ {"role": "assistant", "timestamp": 1784542850.0, "content": "response1",+ "request_id": "req-001", "id": "req-001:assistant"},+ {"role": "user", "timestamp": 1784542900.0, "content": "second prompt",+ "request_id": "req-002", "id": "req-002:user"},+ {"role": "assistant", "timestamp": 1784542905.0, "content": "response2",+ "request_id": "req-002", "id": "req-002:assistant"},+]++_FILE_OPS: dict[str, list[dict]] = {+ "/proj/file_a.py": [+ {+ "action": "write",+ "timestamp": _ts(1784542850.0),+ "old_content": "line1\nline2\n",+ "new_content": "line1\nline2\nline3\n",+ },+ ],+ "/proj/file_b.py": [+ {+ "action": "write",+ "timestamp": _ts(1784542905.0),+ "old_content": "old\n",+ "new_content": "new\n",+ },+ ],+}++_PROJECT = SimpleNamespace(+ project_id="proj-1",+ project_dir="/proj",+ work_mode="code",+ name="test-project",+)+++def _patch_diff_service():+ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pa = patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS)+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)+ return ph, pa, pl, ps+++def _patch_diff_service_with_persistence():+ saved: list[dict] = []++ def _load(session_id):+ return list(saved)++ def _save(session_id, change_sets):+ saved.clear()+ saved.extend(change_sets)++ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pa = patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS)+ pl = patch.object(DiffService, "_load_change_sets", side_effect=_load)+ ps = patch.object(DiffService, "_save_change_sets", side_effect=_save)+ return ph, pa, pl, ps+++def test_get_turn_diff_returns_matching_turn():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff("sess-1", turn_index=1, project_dir="/proj")+ assert turn is not None+ assert turn["turnIndex"] == 1+ assert "/proj/file_a.py" in turn["files"]+ assert "change_set_id" in turn+ assert turn["request_id"] == "req-001"+ assert turn["user_message_id"] == "req-001:user"+ assert turn["assistant_message_id"] == "req-001:assistant"+ assert turn["status"] == "completed"+++def test_get_turn_diff_returns_none_for_missing_turn():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff("sess-1", turn_index=99, project_dir="/proj")+ assert turn is None+++def test_get_turn_diff_finds_second_turn():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff("sess-1", turn_index=2, project_dir="/proj")+ assert turn is not None+ assert turn["turnIndex"] == 2+ assert "/proj/file_b.py" in turn["files"]+ assert turn["request_id"] == "req-002"+++def test_get_turn_diff_by_change_set_id():+ ph, pa, pl, ps = _patch_diff_service_with_persistence()+ with ph, pa, pl, ps:+ service = DiffService()+ turns = service.get_turn_diffs("sess-1", "/proj")+ cs_id = turns[-1]["change_set_id"]+ turn = service.get_turn_diff(+ "sess-1", change_set_id=cs_id, project_dir="/proj",+ )+ assert turn is not None+ assert turn["turnIndex"] == 1+ assert turn["change_set_id"] == cs_id+++def test_get_turn_diff_change_set_id_not_found():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff(+ "sess-1", change_set_id="cs_nonexistent", project_dir="/proj",+ )+ assert turn is None+++def test_get_turn_diff_neither_specified():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff("sess-1", project_dir="/proj")+ assert turn is None+++def test_change_set_id_format():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff("sess-1", turn_index=1, project_dir="/proj")+ assert turn is not None+ cs_id = turn["change_set_id"]+ assert cs_id.startswith("cs_sess-1_1_")+ suffix = cs_id.split("_", 3)[-1]+ assert len(suffix) == 8+ int(suffix, 16)+++def test_change_set_id_is_stable():+ ph, pa, pl, ps = _patch_diff_service_with_persistence()+ with ph, pa, pl, ps:+ service = DiffService()+ turn1 = service.get_turn_diff("sess-1", turn_index=1, project_dir="/proj")+ assert turn1 is not None+ cs_id_1 = turn1["change_set_id"]+ turn2 = service.get_turn_diff("sess-1", turn_index=1, project_dir="/proj")+ assert turn2 is not None+ assert turn2["change_set_id"] == cs_id_1+++def test_change_set_id_is_stable_without_request_id():+ legacy_history = [+ {"role": "user", "timestamp": 1784542845.0, "content": "legacy prompt"},+ {"role": "assistant", "timestamp": 1784542850.0, "content": "response"},+ ]+ saved: list[dict] = []++ def _load(session_id):+ return list(saved)++ def _save(session_id, change_sets):+ saved.clear()+ saved.extend(change_sets)++ ph = patch.object(DiffService, "_read_history", return_value=legacy_history)+ pa = patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS)+ pl = patch.object(DiffService, "_load_change_sets", side_effect=_load)+ ps = patch.object(DiffService, "_save_change_sets", side_effect=_save)+ with ph, pa, pl, ps:+ service = DiffService()+ turn1 = service.get_turn_diff("legacy", turn_index=1, project_dir="/proj")+ assert turn1 is not None+ cs_id = turn1["change_set_id"]+ turn2 = service.get_turn_diff("legacy", turn_index=1, project_dir="/proj")+ assert turn2 is not None+ assert turn2["change_set_id"] == cs_id+++def test_change_set_id_new_after_rewind():+ saved: list[dict] = []+ history_holder: list[list[dict]] = [list(_HISTORY)]++ def _load(session_id):+ return list(saved)++ def _save(session_id, change_sets):+ saved.clear()+ saved.extend(change_sets)++ def _read_history(session_id):+ return history_holder[0]++ ph = patch.object(DiffService, "_read_history", side_effect=_read_history)+ pa = patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS)+ pl = patch.object(DiffService, "_load_change_sets", side_effect=_load)+ ps = patch.object(DiffService, "_save_change_sets", side_effect=_save)+ with ph, pa, pl, ps:+ service = DiffService()+ turn1 = service.get_turn_diff("sess-1", turn_index=1, project_dir="/proj")+ assert turn1 is not None+ old_cs_id = turn1["change_set_id"]+ assert turn1["request_id"] == "req-001"++ history_holder[0] = [+ {"role": "user", "timestamp": 1784542846.0, "content": "rewritten prompt",+ "request_id": "req-new", "id": "req-new:user"},+ {"role": "assistant", "timestamp": 1784542850.0, "content": "response",+ "request_id": "req-new", "id": "req-new:assistant"},+ {"role": "user", "timestamp": 1784542900.0, "content": "second prompt",+ "request_id": "req-002", "id": "req-002:user"},+ {"role": "assistant", "timestamp": 1784542905.0, "content": "response2",+ "request_id": "req-002", "id": "req-002:assistant"},+ ]++ turn2 = service.get_turn_diff("sess-1", turn_index=1, project_dir="/proj")+ assert turn2 is not None+ new_cs_id = turn2["change_set_id"]++ assert old_cs_id != new_cs_id+ assert turn2["request_id"] == "req-new"+ assert turn2["user_message_id"] == "req-new:user"+++def test_mark_turn_discarded_preserves_snapshot():+ saved: list[dict] = []+ snapshots: dict[str, dict] = {}++ def _load(session_id):+ return list(saved)++ def _save(session_id, change_sets):+ saved.clear()+ saved.extend(change_sets)++ def _load_snapshot(self, session_id, change_set_id):+ return snapshots.get(change_set_id)++ def _save_snapshot(self, session_id, turn):+ snapshots[turn["change_set_id"]] = dict(turn)++ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pa = patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS)+ pl = patch.object(DiffService, "_load_change_sets", side_effect=_load)+ ps = patch.object(DiffService, "_save_change_sets", side_effect=_save)+ pls = patch.object(DiffService, "_load_turn_snapshot", _load_snapshot)+ pss = patch.object(DiffService, "_save_turn_snapshot", _save_snapshot)+ with ph, pa, pl, ps, pls, pss:+ service = DiffService()+ cs_id = service.mark_turn_discarded("sess-1", 1, project_dir="/proj")+ assert cs_id is not None+ turn = service.get_turn_diff("sess-1", change_set_id=cs_id, project_dir="/proj")+ assert turn is not None+ assert turn["status"] == "discarded"+ assert "/proj/file_a.py" in turn["files"]+++def test_turn_diff_list_returns_summaries_with_files_without_hunks():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1", limit=50,+ )+ assert result["project_id"] == "proj-1"+ assert result["session_id"] == "sess-1"+ assert result["repo_root"] == "/proj"+ assert result["branch"] == "main"+ assert result["base_head"] == "abc123"+ assert result["total"] == 2+ assert result["limit"] == 50+ assert result["cursor"] == 0+ assert result["next_cursor"] == 2+ assert result["has_more"] is False+ assert result["turns"][0]["turn_index"] == 2+ assert result["turns"][1]["turn_index"] == 1+ for summary in result["turns"]:+ assert "files" in summary+ assert "kind" in summary+ assert "timestamp" in summary+ assert "user_prompt_preview" in summary+ assert "stats" in summary+ for file_entry in summary["files"].values():+ assert file_entry["hunks"] == []+ assert "change_type" in file_entry+ assert "is_deleted_file" in file_entry+ assert "file_b.py" in result["turns"][0]["files"]+ assert "file_a.py" in result["turns"][1]["files"]+++def test_turn_diff_list_includes_change_set_metadata():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1", limit=50,+ )+ for summary in result["turns"]:+ assert "change_set_id" in summary+ assert summary["change_set_id"].startswith("cs_sess-1_")+ assert "request_id" in summary+ assert "assistant_message_id" in summary+ assert "user_message_id" in summary+ assert summary["status"] == "completed"+ assert result["turns"][0]["request_id"] == "req-002"+ assert result["turns"][0]["user_message_id"] == "req-002:user"+ assert result["turns"][1]["request_id"] == "req-001"+ assert result["turns"][1]["assistant_message_id"] == "req-001:assistant"+++def test_turn_diff_list_respects_limit():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1", limit=1,+ )+ assert result["total"] == 2+ assert len(result["turns"]) == 1+ assert result["turns"][0]["turn_index"] == 2+ assert result["next_cursor"] == 1+ assert result["has_more"] is True+++def test_turn_diff_list_respects_cursor():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1", limit=1, cursor=1,+ )+ assert result["total"] == 2+ assert result["cursor"] == 1+ assert result["next_cursor"] == 2+ assert result["has_more"] is False+ assert len(result["turns"]) == 1+ assert result["turns"][0]["turn_index"] == 1+++def test_turn_diff_list_empty_session():+ ph = patch.object(DiffService, "_read_history", return_value=[])+ pa = patch.object(DiffService, "_read_agent_history", return_value={})+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="empty", limit=50,+ )+ assert result["total"] == 0+ assert result["turns"] == []+++def test_turn_diff_list_limit_zero_returns_all():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1", limit=0,+ )+ assert result["limit"] == 0+ assert result["total"] == 2+ assert len(result["turns"]) == 2+++def _fake_git_service(repo_root="/proj", error=None):+ return SimpleNamespace(+ status=lambda project: SimpleNamespace(+ error=error,+ repo_root=repo_root,+ branch="main",+ head="abc123",+ transient=False,+ ),+ )+++def test_turn_diff_detail_returns_files_and_hunks():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps, patch(+ "jiuwenswarm.server.runtime.session.project_git.get_project_git_service",+ return_value=_fake_git_service(),+ ):+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", turn_index=1,+ )+ assert result is not None+ assert result["turn_index"] == 1+ assert result["project_id"] == "proj-1"+ assert result["session_id"] == "sess-1"+ assert result["repo_root"] == "/proj"+ assert result["branch"] == "main"+ assert result["base_head"] == "abc123"+ assert "files" in result+ assert "file_a.py" in result["files"]+ file_entry = result["files"]["file_a.py"]+ assert file_entry["status"] == "modified"+ assert file_entry["change_type"] == "modified"+ assert file_entry["is_deleted_file"] is False+ assert file_entry["lines_added"] == 1+ assert file_entry["lines_removed"] == 0+ assert len(file_entry["hunks"]) > 0+ assert "change_set_id" in result+ assert result["request_id"] == "req-001"+++def test_turn_diff_detail_returns_none_for_missing_turn():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps, patch(+ "jiuwenswarm.server.runtime.session.project_git.get_project_git_service",+ return_value=_fake_git_service(),+ ):+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", turn_index=99,+ )+ assert result is None+++def test_turn_diff_detail_by_change_set_id():+ ph, pa, pl, ps = _patch_diff_service_with_persistence()+ with ph, pa, pl, ps, patch(+ "jiuwenswarm.server.runtime.session.project_git.get_project_git_service",+ return_value=_fake_git_service(),+ ):+ list_result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1", limit=50,+ )+ cs_id = list_result["turns"][-1]["change_set_id"]+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", change_set_id=cs_id,+ )+ assert result is not None+ assert result["turn_index"] == 1+ assert result["change_set_id"] == cs_id+ assert "file_a.py" in result["files"]+++def test_turn_diff_detail_returns_not_git_repository():+ ph, pa, pl, ps = _patch_diff_service()+ git_error = GitError("NOT_GIT_REPOSITORY", "not a git repository")+ with ph, pa, pl, ps, patch(+ "jiuwenswarm.server.runtime.session.project_git.get_project_git_service",+ return_value=_fake_git_service(repo_root=None, error=git_error),+ ):+ with pytest.raises(GitOperationError) as excinfo:+ DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", turn_index=1,+ )+ assert excinfo.value.git_error.code == "NOT_GIT_REPOSITORY"+++def test_turn_diff_detail_respects_include_flags():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT,+ session_id="sess-1",+ turn_index=1,+ include_files=True,+ include_hunks=False,+ )+ assert result is not None+ assert "file_a.py" in result["files"]+ assert result["files"]["file_a.py"]["hunks"] == []+++def test_turn_diff_detail_can_omit_files():+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT,+ session_id="sess-1",+ turn_index=1,+ include_files=False,+ include_hunks=False,+ )+ assert result is not None+ assert result["files"] == {}+++def test_turn_diff_detail_rejects_transient_git_state(monkeypatch):+ service = SimpleNamespace(+ status=lambda project: SimpleNamespace(+ error=None,+ repo_root="/proj",+ branch="main",+ head="abc123",+ transient=True,+ ),+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.project_git.get_project_git_service",+ lambda: service,+ )+ ph, pa, pl, ps = _patch_diff_service()+ with ph, pa, pl, ps:+ with pytest.raises(GitOperationError) as excinfo:+ DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", turn_index=1,+ )+ assert excinfo.value.git_error.code == "GIT_TRANSIENT_STATE"+++def test_get_turn_diff_change_set_orphan_snapshot_is_expired(monkeypatch):+ snapshots = {+ "cs_old": {+ "turnIndex": 1,+ "change_set_id": "cs_old",+ "request_id": "req-old",+ "files": {},+ "stats": {"filesChanged": 0, "linesAdded": 0, "linesRemoved": 0},+ }+ }+ monkeypatch.setattr(+ DiffService,+ "_load_turn_snapshot",+ lambda self, session_id, change_set_id: snapshots.get(change_set_id),+ )+ ph, pa = (+ patch.object(DiffService, "_read_history", return_value=_HISTORY),+ patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS),+ )+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)+ with ph, pa, pl, ps:+ service = DiffService()+ with pytest.raises(DiffHistoryExpiredError):+ service.get_turn_diff("sess-1", change_set_id="cs_old", project_dir="/proj")+++def test_diff_file_entry_serializes_is_untracked():+ entry = DiffFileEntry(file_path="new.txt", is_untracked=True, is_new_file=True)+ assert entry.to_dict()["is_untracked"] is True+ assert entry.to_dict()["change_type"] == "modified"+++def test_diff_file_entry_serializes_deleted_contract_fields():+ entry = DiffFileEntry(+ file_path="old.txt", status="deleted", is_deleted_file=True,+ )+ data = entry.to_dict()+ assert data["status"] == "deleted"+ assert data["change_type"] == "deleted"+ assert data["is_deleted_file"] is True+++def test_turn_diff_persists_historical_repo_context():+ saved: list[dict] = []++ def _load(session_id):+ return list(saved)++ def _save(session_id, change_sets):+ saved.clear()+ saved.extend(change_sets)++ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pa = patch.object(DiffService, "_read_agent_history", return_value=_FILE_OPS)+ pl = patch.object(DiffService, "_load_change_sets", side_effect=_load)+ ps = patch.object(DiffService, "_save_change_sets", side_effect=_save)+ with ph, pa, pl, ps:+ service = DiffService()+ turn = service.get_turn_diff(+ "sess-1",+ turn_index=1,+ project_dir="/proj",+ repo_context={+ "repo_root": "/proj",+ "branch": "feature/a",+ "base_head": "old-head",+ },+ )+ assert turn is not None+ cs_id = turn["change_set_id"]++ turn_after_branch_switch = service.get_turn_diff(+ "sess-1",+ change_set_id=cs_id,+ project_dir="/proj",+ repo_context={+ "repo_root": "/proj",+ "branch": "main",+ "base_head": "new-head",+ },+ )++ assert turn_after_branch_switch is not None+ assert turn_after_branch_switch["branch"] == "feature/a"+ assert turn_after_branch_switch["base_head"] == "old-head"+++def test_parse_git_porcelain_status_maps_file_states():+ output = "\n".join(+ [+ " M modified.py",+ "A added.py",+ "D deleted.py",+ " D missing.py",+ "R old.py -> renamed.py",+ "?? untracked.py",+ ]+ )++ assert DiffService._parse_git_porcelain_status(output) == {+ "modified.py": "modified",+ "added.py": "added",+ "deleted.py": "deleted",+ "missing.py": "missing",+ "renamed.py": "renamed",+ "untracked.py": "added",+ }diff --git a/tests/unit_tests/test_discard_turn_changes.py b/tests/unit_tests/test_discard_turn_changes.pyindex 6668cbbf09..31cbeca791 100644--- a/tests/unit_tests/test_discard_turn_changes.py+++ b/tests/unit_tests/test_discard_turn_changes.py@@ -169,6 +169,16 @@ async def test_successful_discard_restores_files_and_marks_dirty():"project_dir": project_dir,})+ mark_discarded_calls: list[dict] = []++ def fake_mark_discarded(session_id, turn_index, project_dir=None):+ mark_discarded_calls.append({+ "session_id": session_id,+ "turn_index": turn_index,+ "project_dir": project_dir,+ })+ return "cs_sess-1_2_test1234"+def fake_restore(*, session_id, turn_index, project_dir=None):restore_calls.append({"session_id": session_id,@@ -178,6 +188,7 @@ async def test_successful_discard_restores_files_and_marks_dirty():return fake_restore_resultfake_diff_service = SimpleNamespace(+ mark_turn_discarded=fake_mark_discarded,truncate_file_ops_by_timestamp=fake_truncate,)@@ -224,6 +235,7 @@ async def test_successful_discard_restores_files_and_marks_dirty():payload = resp["payload"]assert payload["file_ops_truncated"] is Trueassert payload["global_file_ops_truncated"] is False+ assert payload["change_set_id"] == "cs_sess-1_2_test1234"# P2 修复:用 get_session_metadata(enable_writeback=False) 保留推断、避免写盘assert len(meta_calls) == 1@@ -231,6 +243,7 @@ async def test_successful_discard_restores_files_and_marks_dirty():# P1 修复:handler 显式传入 proj.project_dir 到 restore / truncateassert restore_calls[0]["project_dir"] == "/tmp/proj-A"+ assert mark_discarded_calls[0]["project_dir"] == "/tmp/proj-A"assert truncate_calls[0]["project_dir"] == "/tmp/proj-A"# watcher 标脏正确项目