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 监控与撤销功能
kdgmpwab241e3ec756
diff --git a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.pyindex 126afa3e70..4ef6dc124c 100644--- a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py+++ b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py@@ -172,10 +172,15 @@ class GitDiffWebSocketHandler:get_diff_status_service,)service = get_diff_status_service()+ # 与轮询路径(_compute_and_push)对齐:只在 include_last_turn 时+ # 传 session_id,避免 current-only 订阅因 file_ops 历史读取异常+ # 而首次订阅失败。get_project_diff_status 内只要有 session_id+ # 就会调 get_turn_diff_summaries 且异常向上抛,破坏订阅。+ session_id_for_status = session_id if include_last_turn else Nonestatus = await asyncio.to_thread(service.get_project_diff_status,project=proj,- session_id=session_id or None,+ session_id=session_id_for_status or None,include_files=False,include_hunks=False,)@@ -236,6 +241,8 @@ class GitDiffWebSocketHandler:"project_id": status_dict.get("project_id", ""),"session_id": status_dict.get("session_id"),"repo": {+ "is_git": repo.get("is_git", False),+ "repo_root": repo.get("repo_root"),"branch": repo.get("branch"),"head": repo.get("head"),"transient": repo.get("transient", False),@@ -284,10 +291,14 @@ class GitDiffWebSocketHandler:get_diff_status_service,)service = get_diff_status_service()+ # 与轮询路径(_compute_and_push)对齐:只在 source="last_turn"+ # 时传 session_id;source="current" 不需要 last_turn,传 session_id+ # 会因 file_ops 历史读取异常导致首次订阅失败。+ session_id_for_status = session_id if source == "last_turn" else Nonestatus = await asyncio.to_thread(service.get_project_diff_status,project=proj,- session_id=session_id or None,+ session_id=session_id_for_status or None,include_files=True,include_hunks=False,)@@ -377,10 +388,14 @@ class GitDiffWebSocketHandler:get_diff_status_service,)service = get_diff_status_service()+ # 与轮询路径(_compute_and_push)对齐:只在 source="last_turn"+ # 时传 session_id;source="current" 不需要 last_turn,传 session_id+ # 会因 file_ops 历史读取异常导致首次订阅失败。+ session_id_for_status = session_id if source == "last_turn" else Nonestatus = await asyncio.to_thread(service.get_project_diff_status,project=proj,- session_id=session_id or None,+ session_id=session_id_for_status or None,include_files=True,include_hunks=True,)@@ -576,13 +591,26 @@ class GitDiffWebSocketHandler:get_session_extra_history_roots,)extra_history_roots = get_session_extra_history_roots(session_id)- restore_result = await asyncio.to_thread(- restore_session_files,- session_id=session_id,- turn_index=turn_index,- project_dir=proj.project_dir,- extra_history_roots=extra_history_roots,- )+ try:+ restore_result = await asyncio.to_thread(+ restore_session_files,+ session_id=session_id,+ turn_index=turn_index,+ project_dir=proj.project_dir,+ extra_history_roots=extra_history_roots,+ )+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "[GitWS] discard_turn_changes: restore failed "+ "(session=%s project=%s): %s",+ session_id, project_id, exc,+ )+ await self._channel.send_response(+ ws, req_id, ok=False,+ error=f"failed to restore session files: {exc}",+ code="INTERNAL_ERROR",+ )+ return# 清理本轮的 file_ops 日志,使 git 监控的 last_turn diff 与实际工作区一致。# 注意 1:仅清理 session-specific file_ops;全局 file_ops 缺少 session 归属字段,diff --git a/jiuwenswarm/server/runtime/session/git_diff_status.py b/jiuwenswarm/server/runtime/session/git_diff_status.pyindex bc3d3cb041..48183bf6e4 100644--- a/jiuwenswarm/server/runtime/session/git_diff_status.py+++ b/jiuwenswarm/server/runtime/session/git_diff_status.py@@ -618,6 +618,31 @@ def _repo_context_from_status(project: Any, *, reject_transient: bool = False) -}+def _repo_context_for_history(project: Any) -> dict[str, Any]:+ """历史轮次回放专用:读取 Git 上下文,失败时降级为 project_dir 兜底。++ 与 ``_repo_context_from_status`` 的区别:+ - 不抛 ``GIT_TRANSIENT_STATE``:历史轮次回放基于 file_ops + change_set+ snapshot,不执行 git 命令,transient 状态不应阻断历史预览。+ - 不抛其他 Git 错误:timeout/command_failed 等与历史 snapshot 无关。+ - 失败时返回 ``{"repo_root": project_dir, "branch": None, "base_head": None}``,+ 让历史 turn 的 ``_historical_repo_context`` 仍可用(优先级高于 fallback)。++ 设计原则:历史轮次的 repo 上下文已持久化在 change_set entry,当前 git 状态+ 只是 fallback。fallback 失败时用 project_dir 兜底,而非阻断整个请求。+ """+ try:+ return _repo_context_from_status(project, reject_transient=False)+ except GitOperationError:+ # transient / timeout / command_failed 等:用 project_dir 兜底+ project_dir = str(getattr(project, "project_dir", "") or "") or None+ return {+ "repo_root": project_dir,+ "branch": None,+ "base_head": None,+ }++class DiffStatusService:"""面向 Web 的 diff 状态聚合服务(设计文档 §2.4 / §4.1.16)。@@ -760,7 +785,9 @@ class DiffStatusService:"""返回历史轮次摘要列表。"""project_id = getattr(project, "project_id", "")project_dir = getattr(project, "project_dir", "")- repo_context = _repo_context_from_status(project, reject_transient=True)+ # 历史轮次回放不依赖当前 git 状态:用 _repo_context_for_history 兜底,+ # 避免 transient/timeout 等错误阻断 file_ops 历史预览。+ repo_context = _repo_context_for_history(project)diff_service = get_diff_service()extra_history_roots = get_session_extra_history_roots(session_id)turns = diff_service.get_turn_diff_summaries(@@ -806,7 +833,9 @@ class DiffStatusService:"""返回指定轮次详情,优先按 ``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)+ # 历史轮次回放不依赖当前 git 状态:用 _repo_context_for_history 兜底,+ # 避免 transient/timeout 等错误阻断 file_ops 历史预览。+ repo_context = _repo_context_for_history(project)repo_root = repo_context.get("repo_root")diff_service = get_diff_service()diff --git a/jiuwenswarm/server/runtime/session/git_diff_watcher.py b/jiuwenswarm/server/runtime/session/git_diff_watcher.pyindex f08f01cf7e..cce44bd83f 100644--- a/jiuwenswarm/server/runtime/session/git_diff_watcher.py+++ b/jiuwenswarm/server/runtime/session/git_diff_watcher.py@@ -125,6 +125,8 @@ def _summary_fingerprint(else None)return _fingerprint(+ repo.get("is_git"),+ repo.get("repo_root"),repo.get("branch"),repo.get("head"),repo.get("transient"),@@ -229,14 +231,21 @@ class GitDiffWatcherRegistry:抛错则触发自动 ``remove_watch``。返回值用于 seed fingerprint。若为 ``None``,保持旧行为(调用方自行 ``commit_initial_summary``)。"""- watch_id = f"gitdiff_{project_id}_{session_id}_{uuid.uuid4().hex[:12]}"+ # session_id 为空串时强制关闭 include_last_turn。+ # 原因:``_compute_and_push`` 用 ``if session_id:`` 判定是否计算 last_turn,+ # 空串会被判定为 False 而静默跳过 last_turn 计算。若 ``include_last_turn``+ # 仍为 True,summary fingerprint 会包含 ``last_turn.stats=None``,+ # 且事件 payload 的 ``last_turn`` 字段语义不一致(前端误以为有 last_turn)。+ # 此处显式关闭,让 watcher 语义自洽:无 session 即不监控 last_turn。+ effective_include_last_turn = bool(include_last_turn) and bool(session_id)+ watch_id = f"gitdiff_{project_id}_{session_id or 'noss'}_{uuid.uuid4().hex[:12]}"watch = GitDiffWatch(watch_id=watch_id,project_id=project_id,session_id=session_id,ws=ws,scope=scope,- include_last_turn=include_last_turn,+ include_last_turn=effective_include_last_turn,)async with self._lock:self._watches[watch_id] = watch@@ -839,6 +848,7 @@ class GitDiffWatcherRegistry:if isinstance(exc, GitOperationError):err_code = getattr(exc.git_error, "code", "")if err_code in _STRUCTURAL_ERROR_CODES:+ await self._push_error_event(project_id, exc)logger.info("[GitDiffWatcher] structural error (%s), pausing poll loop ""for project=%s (watches kept, will resume on mark_dirty)",@@ -943,8 +953,14 @@ class GitDiffWatcherRegistry:# 直接调 ``get_turn_diff_summaries`` + ``_convert_turn_diff``,避免再次调# ``get_project_diff_status``(会重复计算项目级 ``current``)。# 异常处理与 ``get_project_diff_status`` 内部一致:捕获后 last_turn=None。+ group_needs_last_turn = any(+ w.include_last_turn+ or w.files_source == "last_turn"+ or w.detail_source == "last_turn"+ for w in group_watches+ )last_turn = None- if session_id:+ if session_id and group_needs_last_turn:try:# 与首次快照路径(DiffStatusService.get_project_diff_status)对齐:# 传入 extra_history_roots 以收集 team/member workspace 与@@ -1051,6 +1067,8 @@ class GitDiffWatcherRegistry:"change_type": "summary","revision": _build_revision("gitdiff", fingerprint),"repo": {+ "is_git": repo.get("is_git", False),+ "repo_root": repo.get("repo_root"),"branch": repo.get("branch"),"head": repo.get("head"),"transient": repo.get("transient", False),diff --git a/jiuwenswarm/server/runtime/session/project_git.py b/jiuwenswarm/server/runtime/session/project_git.pyindex ff13974700..fc62301b40 100644--- a/jiuwenswarm/server/runtime/session/project_git.py+++ b/jiuwenswarm/server/runtime/session/project_git.py@@ -264,7 +264,10 @@ def _is_transient_state(project_dir: str) -> tuple[bool, str]:content = dot_git.read_text(encoding="utf-8").strip()if content.startswith("gitdir:"):git_dir = Path(project_dir) / content.split("gitdir:", 1)[1].strip()- git_dir = git_dir.resolve()+ # 使用 absolute() 而非 resolve():不解析 symlink,避免通过 symlink+ # 访问的 worktree gitdir 与 git 内部管理的真实路径不一致,导致+ # transient 状态(merge/rebase 等)检测失败。+ git_dir = git_dir.absolute()except Exception: # noqa: BLE001return False, ""if git_dir is None or not git_dir.exists():@@ -608,9 +611,9 @@ def _git_to_repo_status(elif xy[0] == "?":untracked += 1else:- if xy[0] in ("A", "M", "D", "R", "C"):+ if xy[0] in ("A", "M", "D", "R", "C", "T"):staged += 1- if xy[1] in ("M", "D"):+ if xy[1] in ("M", "D", "T"):unstaged += 1is_dirty = staged > 0 or unstaged > 0 or untracked > 0 or conflicted > 0except (FileNotFoundError, subprocess.TimeoutExpired):@@ -1182,9 +1185,7 @@ class ProjectGitService:# worktree dirs were rmtree'd without `git worktree remove`)# make `git checkout <branch>` fail with "already used by# worktree" even though the worktree no longer exists. Prune- # stale admin and retry once; if it still fails the worktree- # is live (a team is still running) and the user must dissolve- # it first.+ # stale admin and retry once; live worktrees remain user-managed.prune_co = Noneif _is_branch_held_by_worktree(cp_co.stderr):logger.info(@@ -1232,101 +1233,37 @@ class ProjectGitService:repo_status=post_status,previous_branch=previous_branch,)- # LIVE worktree(团队未解散)占用目标分支:对占用者执行- # ``git checkout --detach`` 释放分支 ref 后重试 checkout。- # 工作树内容不变,agent 之后可重新 checkout 该分支继续工作。- detach_failed: list[str] = []- detach_attempted = False+ # LIVE worktree(团队未解散)占用目标分支时不再自动 detach 占用者。+ # 自动修改其他 worktree 的 HEAD 会破坏正在运行的团队/agent 上下文;+ # 保留 stale worktree prune,但 live 占用交由用户显式解散或手动处理。+ holding: list[str] = []if _is_branch_held_by_worktree(cp_co.stderr):holding = _find_worktrees_holding_branch(project.project_dir, branch,)if holding:- detach_attempted = Truelogger.info("[ProjectGit] checkout %s blocked by live worktree(s) "- "%s; detaching HEAD to release branch (cwd=%s)",+ "%s; refusing automatic detach (cwd=%s)",branch, holding, project.project_dir,)- for wt_path in holding:- try:- wt_co = _run_git(- ["checkout", "--detach"], cwd=wt_path,- )- if wt_co.returncode != 0:- detach_failed.append(- f"{wt_path}: rc={wt_co.returncode}, "- f"stderr={(wt_co.stderr or '')[:200]}"- )- except FileNotFoundError:- detach_failed.append(- f"{wt_path}: git executable not found"- )- except subprocess.TimeoutExpired:- detach_failed.append(f"{wt_path}: timeout")- if not detach_failed:- try:- cp_co = _run_git(- ["checkout", branch],- cwd=project.project_dir,- )- except FileNotFoundError:- err = _file_not_found_error(- project, project.project_dir,- branch=previous_branch,- command=f"git checkout {branch}",- )- return GitOperationResult(- success=False,- repo_status=pre_status,- previous_branch=previous_branch,- error=err,- )- except subprocess.TimeoutExpired:- err = _make_repo_error(- "GIT_COMMAND_TIMEOUT",- "git command timed out",- project,- command=f"git checkout {branch}",- branch=previous_branch,- retryable=True,- )- return GitOperationResult(- success=False,- repo_status=pre_status,- previous_branch=previous_branch,- error=err,- )- if cp_co.returncode == 0:- logger.info(- "[ProjectGit] checkout %s succeeded after "- "detaching %d worktree(s)",- branch, len(holding),- )- post_status = _git_to_repo_status(project, persist=True)- return GitOperationResult(- success=True,- repo_status=post_status,- previous_branch=previous_branch,- )held = _is_branch_held_by_worktree(cp_co.stderr)if held and prune_co is not None and prune_co.returncode != 0:msg = "清理 stale worktree 失败,无法切换分支"hint = ("git worktree prune 执行失败(rc={rc}): {stderr}。""请手动在仓库目录执行: git -c safe.directory=* worktree prune").format(rc=prune_co.returncode, stderr=(prune_co.stderr or "")[:300])- elif held and detach_attempted and detach_failed:- msg = "自动 detach 占用分支的 worktree 失败,无法切换分支"- hint = ("对占用 {branch} 的 worktree 执行 git checkout --detach 失败:\n"- "{failures}\n请手动 detach 这些 worktree 或解散团队后重试").format(- branch=branch, failures="\n".join(detach_failed[:5]))- elif held and detach_attempted:- msg = "分支仍被 worktree 占用"- hint = ("已尝试 detach 占用 {branch} 的 worktree 并重试,但分支仍被占用。"- "请检查 git worktree list,或解散团队后重试").format(branch=branch)+ elif held and holding:+ msg = "分支被其他 worktree 占用"+ hint = ("占用 {branch} 的 worktree: {paths}。"+ "请先解散对应团队,或手动在占用 worktree 执行 "+ "git checkout --detach 后重试").format(+ branch=branch,+ paths=", ".join(holding[:3]),+ )elif held:msg = "分支被其他 worktree 占用"- hint = "请先解散占用该分支的团队或移除对应 worktree 后重试"+ hint = "请先解散占用该分支的团队,或手动处理对应 worktree 后重试"elif "would be overwritten" in cp_co.stderr:msg = "切换分支失败:本地改动阻止切换"hint = "请先提交或 stash 改动后重试"@@ -1518,6 +1455,10 @@ class ProjectGitService:cwd=project.project_dir,)except FileNotFoundError:+ # git 可执行文件消失:无法重新探测,且 ``_git_to_repo_status`` 内部+ # 会再次抛 ``FileNotFoundError`` 被 ``_file_not_found_error`` 捕获,+ # 多一次失败探测无意义。返回 pre_status,但分支已在仓库中创建,+ # 下次 status/probe 会反映新分支。err = _file_not_found_error(project, project.project_dir,branch=previous_branch,@@ -1530,6 +1471,8 @@ class ProjectGitService:error=err,)except subprocess.TimeoutExpired:+ # git 卡住:重新探测可能再次 timeout,延长错误响应时间。+ # 返回 pre_status 避免延长等待;分支已创建,下次 probe 会反映。err = _make_repo_error("GIT_COMMAND_TIMEOUT","git command timed out",@@ -1545,6 +1488,9 @@ class ProjectGitService:error=err,)if cp_co.returncode != 0:+ # git 仍可用但 checkout 失败(如本地改动阻止切换):重新探测以让+ # ``local_branches`` 包含新创建的分支,前端列表即时更新。+ post_status = _git_to_repo_status(project, persist=True)err = _make_repo_error("GIT_COMMAND_FAILED","git command failed",@@ -1559,7 +1505,7 @@ class ProjectGitService:)return GitOperationResult(success=False,- repo_status=pre_status,+ repo_status=post_status,previous_branch=previous_branch,error=err,)diff --git a/tests/unit_tests/server/test_git_diff_watcher.py b/tests/unit_tests/server/test_git_diff_watcher.pynew file mode 100644index 0000000000..ee322edc89--- /dev/null+++ b/tests/unit_tests/server/test_git_diff_watcher.py@@ -0,0 +1,145 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest+++class _FakeChannel:+ def __init__(self) -> None:+ self.events: list[dict] = []++ async def send_event(self, ws, event, payload):+ self.events.append({"ws": ws, "event": event, "payload": payload})+++def _project(project_id: str = "proj-A"):+ return SimpleNamespace(+ project_id=project_id,+ project_dir="/tmp/proj-A",+ hidden=False,+ work_mode="code",+ )+++async def test_structural_error_pushes_error_event_before_pausing(monkeypatch):+ from jiuwenswarm.server.runtime.session import git_diff_watcher+ from jiuwenswarm.server.runtime.session.project_git import GitError, GitOperationError++ channel = _FakeChannel()+ registry = git_diff_watcher.GitDiffWatcherRegistry(channel=channel)+ watch = await registry.add_watch(+ object(), "proj-A", "sess-1", include_last_turn=True,+ )++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.project_store.get_project_by_id",+ lambda project_id: _project(project_id),+ )++ class _DiffStatusService:+ def get_project_diff_status(self, **kwargs):+ raise GitOperationError(+ GitError(+ "NOT_GIT_REPOSITORY",+ "not a git repository",+ retryable=False,+ )+ )++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.git_diff_status.get_diff_status_service",+ lambda: _DiffStatusService(),+ )++ await registry._poll_loop("proj-A")++ assert channel.events+ assert channel.events[0]["event"] == "project.git.error"+ assert channel.events[0]["payload"]["watch_id"] == watch.watch_id+ assert channel.events[0]["payload"]["detail"]["code"] == "NOT_GIT_REPOSITORY"+++async def test_current_only_watch_does_not_read_last_turn(monkeypatch):+ from jiuwenswarm.server.runtime.session import git_diff_watcher+ from jiuwenswarm.server.runtime.session.git_diff_status import (+ DiffRepoInfo,+ DiffStats,+ DiffSummary,+ ProjectGitDiffStatus,+ )++ channel = _FakeChannel()+ registry = git_diff_watcher.GitDiffWatcherRegistry(channel=channel)+ await registry.add_watch(+ object(), "proj-A", "sess-1", include_last_turn=False,+ )++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.project_store.get_project_by_id",+ lambda project_id: _project(project_id),+ )++ class _DiffStatusService:+ def get_project_diff_status(self, **kwargs):+ return ProjectGitDiffStatus(+ project_id="proj-A",+ session_id=None,+ work_mode="code",+ repo=DiffRepoInfo(+ is_git=True,+ repo_root="/tmp/proj-A",+ branch="main",+ head="abc123",+ transient=False,+ ),+ current=DiffSummary(+ is_dirty=False,+ stats=DiffStats(),+ files={},+ ),+ )++ class _DiffService:+ def get_turn_diff_summaries(self, *args, **kwargs):+ raise AssertionError("last_turn should not be read")++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.git_diff_status.get_diff_status_service",+ lambda: _DiffStatusService(),+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_diff_service",+ lambda: _DiffService(),+ )++ await registry._compute_and_push("proj-A", registry._get_watches_for_project("proj-A"))++ assert channel.events+ assert channel.events[0]["event"] == "project.git.diff_changed"+ assert channel.events[0]["payload"]["last_turn"] is None+++async def test_empty_session_id_forces_include_last_turn_false(monkeypatch):+ """Bug 修复:``session_id=""`` 时强制关闭 ``include_last_turn``。++ 原因:``_compute_and_push`` 用 ``if session_id:`` 判定是否计算 last_turn,+ 空串会被判定为 False 而静默跳过 last_turn 计算。若 ``include_last_turn``+ 仍为 True,语义不一致——前端误以为有 last_turn 数据。+ """+ from jiuwenswarm.server.runtime.session import git_diff_watcher++ channel = _FakeChannel()+ registry = git_diff_watcher.GitDiffWatcherRegistry(channel=channel)++ # 传入 session_id="" 且 include_last_turn=True+ watch = await registry.add_watch(+ object(), "proj-A", "", include_last_turn=True,+ )++ # 应被强制关闭+ assert watch.include_last_turn is False+ assert watch.session_id == ""diff --git a/tests/unit_tests/server/test_project_git_safe_directory.py b/tests/unit_tests/server/test_project_git_safe_directory.pyindex 8c8efb088b..e632550b13 100644--- a/tests/unit_tests/server/test_project_git_safe_directory.py+++ b/tests/unit_tests/server/test_project_git_safe_directory.py@@ -2,6 +2,8 @@ from __future__ import annotationsimport subprocess+import pytest+from jiuwenswarm.server.runtime.session.project_store import Project@@ -140,3 +142,328 @@ def test_dubious_ownership_status_maps_to_specific_snapshot_status():)assert project_git._map_status_string(status) == "dubious_ownership"+++def test_git_status_counts_type_change_as_dirty(monkeypatch, tmp_path):+ from jiuwenswarm.server.runtime.session import project_git++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ project = Project(+ project_id="proj_test",+ name="test",+ project_dir=str(project_dir),+ work_mode="code",+ )++ def fake_run_git(args, *, cwd, timeout=project_git.GIT_COMMAND_TIMEOUT_SEC):+ if args == ["rev-parse", "--show-toplevel"]:+ return _cp(["git", *args], 0, stdout=str(project_dir))+ if args == ["symbolic-ref", "--short", "HEAD"]:+ return _cp(["git", *args], 0, stdout="main\n")+ if args == ["rev-parse", "--abbrev-ref", "main@{upstream}"]:+ return _cp(["git", *args], 1)+ if args == ["rev-parse", "--short", "HEAD"]:+ return _cp(["git", *args], 0, stdout="abc123\n")+ if args == ["status", "--porcelain", "--no-renames"]:+ return _cp(["git", *args], 0, stdout=" T link.txt\n")+ if args == ["for-each-ref", "--format=%(refname:short)", "refs/heads/"]:+ return _cp(["git", *args], 0, stdout="main\n")+ if args == ["for-each-ref", "--format=%(refname:short)", "refs/remotes/"]:+ return _cp(["git", *args], 0)+ return _cp(["git", *args], 0)++ monkeypatch.setattr(project_git, "_run_git", fake_run_git)+ monkeypatch.setattr(project_git, "_find_git_executable", lambda: "git")++ status = project_git._git_to_repo_status(project)++ assert status.is_dirty is True+ assert status.unstaged == 1+++def test_create_branch_checkout_failure_returns_post_create_status(monkeypatch, tmp_path):+ from jiuwenswarm.server.runtime.session import project_git++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ project = Project(+ project_id="proj_test",+ name="test",+ project_dir=str(project_dir),+ work_mode="code",+ )+ calls: list[list[str]] = []++ def fake_run_git(args, *, cwd, timeout=project_git.GIT_COMMAND_TIMEOUT_SEC):+ calls.append(args)+ if args == ["check-ref-format", "--branch", "feature"]:+ return _cp(["git", *args], 0, stdout="feature\n")+ if args == ["show-ref", "--verify", "refs/heads/feature"]:+ return _cp(["git", *args], 1)+ if args == ["branch", "feature"]:+ return _cp(["git", *args], 0)+ if args == ["checkout", "feature"]:+ return _cp(["git", *args], 1, stderr="checkout failed")+ return _cp(["git", *args], 0)++ pre_status = project_git.GitRepoStatus(+ is_git=True,+ repo_root=str(project_dir),+ branch="main",+ local_branches=["main"],+ )+ post_status = project_git.GitRepoStatus(+ is_git=True,+ repo_root=str(project_dir),+ branch="main",+ local_branches=["feature", "main"],+ )+ status_calls: list[bool] = []++ def fake_git_to_repo_status(project, *, persist=False):+ status_calls.append(persist)+ return pre_status if len(status_calls) == 1 else post_status++ monkeypatch.setattr(project_git, "_run_git", fake_run_git)+ monkeypatch.setattr(project_git, "_git_to_repo_status", fake_git_to_repo_status)++ result = project_git.ProjectGitService.create_branch(project, "feature")++ assert result.success is False+ assert result.error is not None+ assert result.repo_status is post_status+ assert "feature" in result.repo_status.local_branches+ assert status_calls == [False, True]+ assert ["checkout", "feature"] in calls+++def test_switch_branch_refuses_live_worktree_without_detach(monkeypatch, tmp_path):+ from jiuwenswarm.server.runtime.session import project_git++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ project = Project(+ project_id="proj_test",+ name="test",+ project_dir=str(project_dir),+ work_mode="code",+ )+ calls: list[list[str]] = []+ held_stderr = (+ "fatal: 'feature' is already used by worktree at "+ f"'{tmp_path / 'worktree'}'"+ )++ def fake_run_git(args, *, cwd, timeout=project_git.GIT_COMMAND_TIMEOUT_SEC):+ calls.append(args)+ if args == ["check-ref-format", "--branch", "feature"]:+ return _cp(["git", *args], 0, stdout="feature\n")+ if args == ["show-ref", "--verify", "refs/heads/feature"]:+ return _cp(["git", *args], 0)+ if args == ["checkout", "feature"]:+ return _cp(["git", *args], 1, stderr=held_stderr)+ if args == ["-c", "safe.directory=*", "worktree", "prune"]:+ return _cp(["git", *args], 0)+ return _cp(["git", *args], 0)++ pre_status = project_git.GitRepoStatus(+ is_git=True,+ repo_root=str(project_dir),+ branch="main",+ local_branches=["feature", "main"],+ )++ monkeypatch.setattr(project_git, "_run_git", fake_run_git)+ monkeypatch.setattr(project_git, "_git_to_repo_status", lambda project, *, persist=False: pre_status)+ monkeypatch.setattr(+ project_git,+ "_find_worktrees_holding_branch",+ lambda project_dir, branch: [str(tmp_path / "worktree")],+ )++ result = project_git.ProjectGitService.switch_branch(project, "feature")++ assert result.success is False+ assert result.error is not None+ assert "worktree" in result.error.message+ assert ["checkout", "--detach"] not in calls+++def test_switch_branch_hint_includes_holding_worktree_path(monkeypatch, tmp_path):+ """Bug 修复:holding 调用结果应进入 hint,让用户看到具体占用 worktree 路径。"""+ from jiuwenswarm.server.runtime.session import project_git++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ project = Project(+ project_id="proj_test",+ name="test",+ project_dir=str(project_dir),+ work_mode="code",+ )+ holding_path = str(tmp_path / "team_wt")+ held_stderr = (+ f"fatal: 'feature' is already used by worktree at '{holding_path}'"+ )++ def fake_run_git(args, *, cwd, timeout=project_git.GIT_COMMAND_TIMEOUT_SEC):+ if args == ["check-ref-format", "--branch", "feature"]:+ return _cp(["git", *args], 0, stdout="feature\n")+ if args == ["show-ref", "--verify", "refs/heads/feature"]:+ return _cp(["git", *args], 0)+ if args == ["checkout", "feature"]:+ return _cp(["git", *args], 1, stderr=held_stderr)+ if args == ["-c", "safe.directory=*", "worktree", "prune"]:+ return _cp(["git", *args], 0)+ return _cp(["git", *args], 0)++ pre_status = project_git.GitRepoStatus(+ is_git=True,+ repo_root=str(project_dir),+ branch="main",+ local_branches=["feature", "main"],+ )+ monkeypatch.setattr(project_git, "_run_git", fake_run_git)+ monkeypatch.setattr(+ project_git, "_git_to_repo_status",+ lambda project, *, persist=False: pre_status,+ )+ monkeypatch.setattr(+ project_git, "_find_worktrees_holding_branch",+ lambda project_dir, branch: [holding_path],+ )++ result = project_git.ProjectGitService.switch_branch(project, "feature")++ assert result.success is False+ assert result.error is not None+ # hint 应包含具体占用 worktree 路径,而非仅泛泛提示+ assert holding_path in result.error.hint+++def test_create_branch_checkout_filenotfound_returns_pre_status(monkeypatch, tmp_path):+ """Bug 修复:FileNotFoundError 路径不再二次探测(git 已消失,二次探测必再失败)。"""+ from jiuwenswarm.server.runtime.session import project_git++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ project = Project(+ project_id="proj_test",+ name="test",+ project_dir=str(project_dir),+ work_mode="code",+ )++ def fake_run_git(args, *, cwd, timeout=project_git.GIT_COMMAND_TIMEOUT_SEC):+ if args == ["check-ref-format", "--branch", "feature"]:+ return _cp(["git", *args], 0, stdout="feature\n")+ if args == ["show-ref", "--verify", "refs/heads/feature"]:+ return _cp(["git", *args], 1)+ if args == ["branch", "feature"]:+ return _cp(["git", *args], 0)+ if args == ["checkout", "feature"]:+ raise FileNotFoundError("git executable not found")+ return _cp(["git", *args], 0)++ pre_status = project_git.GitRepoStatus(+ is_git=True,+ repo_root=str(project_dir),+ branch="main",+ local_branches=["main"],+ )+ status_calls: list[bool] = []++ def fake_git_to_repo_status(project, *, persist=False):+ status_calls.append(persist)+ return pre_status++ monkeypatch.setattr(project_git, "_run_git", fake_run_git)+ monkeypatch.setattr(project_git, "_git_to_repo_status", fake_git_to_repo_status)++ result = project_git.ProjectGitService.create_branch(project, "feature")++ assert result.success is False+ assert result.error is not None+ assert result.error.code == "GIT_NOT_FOUND"+ # 仅调用一次 pre_status 探测(persist=False),不再二次探测+ assert status_calls == [False]+++def test_create_branch_checkout_timeout_returns_pre_status(monkeypatch, tmp_path):+ """Bug 修复:TimeoutExpired 路径不再二次探测(避免延长错误响应时间)。"""+ from jiuwenswarm.server.runtime.session import project_git++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ project = Project(+ project_id="proj_test",+ name="test",+ project_dir=str(project_dir),+ work_mode="code",+ )++ def fake_run_git(args, *, cwd, timeout=project_git.GIT_COMMAND_TIMEOUT_SEC):+ if args == ["check-ref-format", "--branch", "feature"]:+ return _cp(["git", *args], 0, stdout="feature\n")+ if args == ["show-ref", "--verify", "refs/heads/feature"]:+ return _cp(["git", *args], 1)+ if args == ["branch", "feature"]:+ return _cp(["git", *args], 0)+ if args == ["checkout", "feature"]:+ raise subprocess.TimeoutExpired(cmd=["git", *args], timeout=10)+ return _cp(["git", *args], 0)++ pre_status = project_git.GitRepoStatus(+ is_git=True,+ repo_root=str(project_dir),+ branch="main",+ local_branches=["main"],+ )+ status_calls: list[bool] = []++ def fake_git_to_repo_status(project, *, persist=False):+ status_calls.append(persist)+ return pre_status++ monkeypatch.setattr(project_git, "_run_git", fake_run_git)+ monkeypatch.setattr(project_git, "_git_to_repo_status", fake_git_to_repo_status)++ result = project_git.ProjectGitService.create_branch(project, "feature")++ assert result.success is False+ assert result.error is not None+ assert result.error.code == "GIT_COMMAND_TIMEOUT"+ assert status_calls == [False]+++def test_is_transient_state_uses_absolute_not_resolve(monkeypatch, tmp_path):+ """Bug 修复:``_is_transient_state`` 用 absolute() 不解析 symlink。++ 场景:``.git`` 文件指向通过 symlink 访问的 worktree gitdir。+ ``resolve()`` 会解析 symlink 得到真实路径,可能与 git 内部管理的路径不一致,+ 导致后续 ``merge``/``rebase`` 目录检测失败。``absolute()`` 保留 symlink。+ """+ from jiuwenswarm.server.runtime.session import project_git++ # 真实 gitdir 在别处,merge 目录在真实路径下+ real_git_dir = tmp_path / "real_git_dir"+ real_git_dir.mkdir()+ (real_git_dir / "merge").mkdir()++ # 通过 symlink 访问真实 gitdir(模拟 worktree 通过 symlink 挂载)+ symlink_git_dir = tmp_path / "symlink_git_dir"+ try:+ symlink_git_dir.symlink_to(real_git_dir)+ except (OSError, NotImplementedError):+ pytest.skip("symlink not supported on this platform")++ project_dir = tmp_path / "project"+ project_dir.mkdir()+ git_file = project_dir / ".git"+ git_file.write_text(f"gitdir: {symlink_git_dir}\n", encoding="utf-8")++ is_transient, kind = project_git._is_transient_state(str(project_dir))++ assert is_transient is True+ assert kind == "merge"diff --git a/tests/unit_tests/server/test_turn_diff_history.py b/tests/unit_tests/server/test_turn_diff_history.pyindex 3ce57c2b42..9de7fa65f9 100644--- a/tests/unit_tests/server/test_turn_diff_history.py+++ b/tests/unit_tests/server/test_turn_diff_history.py@@ -1407,7 +1407,12 @@ def test_turn_diff_detail_can_omit_files():assert result["files"] == {}-def test_turn_diff_detail_rejects_transient_git_state(monkeypatch):+def test_turn_diff_detail_tolerates_transient_git_state(monkeypatch):+ """transient 状态不应阻断历史轮次回放。++ 历史轮次基于 file_ops + change_set snapshot,不执行 git 命令。+ transient 时用 project_dir 兜底 repo_context,历史预览仍可用。+ """service = SimpleNamespace(status=lambda project: SimpleNamespace(error=None,@@ -1423,11 +1428,82 @@ def test_turn_diff_detail_rejects_transient_git_state(monkeypatch):)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"+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", turn_index=1,+ )+ # 应返回历史数据,而非抛 GIT_TRANSIENT_STATE+ assert result is not None+ assert result["turn_index"] == 1+ # repo_root 用 project_dir 兜底(transient 时无法读 git)+ assert result["repo_root"] == "/proj"+ # 历史 turn 的文件应正常返回(路径相对 repo_root)+ assert "file_a.py" in result["files"]+++def test_turn_diff_list_tolerates_transient_git_state(monkeypatch):+ """transient 状态不应阻断历史轮次列表。++ 与 turn_diff_detail 同理:list 接口也基于 file_ops + snapshot,+ transient 时用 project_dir 兜底。+ """+ 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:+ result = DiffStatusService.get_turn_diff_list(+ project=_PROJECT, session_id="sess-1",+ )+ # 应返回历史轮次列表,而非抛 GIT_TRANSIENT_STATE+ assert result["total"] >= 1+ assert result["turns"]+ # repo_root 用 project_dir 兜底+ assert result["repo_root"] == "/proj"+++def test_turn_diff_detail_tolerates_git_command_failed(monkeypatch):+ """非 transient 的 git 错误(如 command_failed)也不应阻断历史预览。++ timeout/command_failed 与 file_ops 历史回放无关,应同样用 project_dir 兜底。+ """+ from jiuwenswarm.server.runtime.session.project_git import GitError+ service = SimpleNamespace(+ status=lambda project: SimpleNamespace(+ error=GitError(+ code="GIT_COMMAND_FAILED",+ message="git command failed",+ retryable=True,+ ),+ repo_root=None,+ branch=None,+ head=None,+ transient=False,+ ),+ )+ 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:+ result = DiffStatusService.get_turn_diff_detail(+ project=_PROJECT, session_id="sess-1", turn_index=1,+ )+ # 应返回历史数据,而非抛 GitOperationError+ assert result is not None+ assert result["turn_index"] == 1+ # repo_root 用 project_dir 兜底+ assert result["repo_root"] == "/proj"def test_get_turn_diff_change_set_orphan_snapshot_is_expired(monkeypatch):diff --git a/tests/unit_tests/test_diff_watch_session_id_propagation.py b/tests/unit_tests/test_diff_watch_session_id_propagation.pynew file mode 100644index 0000000000..3fe31b9b47--- /dev/null+++ b/tests/unit_tests/test_diff_watch_session_id_propagation.py@@ -0,0 +1,464 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for session_id propagation in diff_watch/files/detail first-snapshot.++P2 修复:首次快照路径与轮询路径(``_compute_and_push``)语义对齐。+只在 ``include_last_turn`` 或 ``source == "last_turn"`` 时传 session_id 给+``get_project_diff_status``,避免 current-only 订阅因 file_ops 历史读取异常+而首次订阅失败(异常会向上抛触发 ``remove_watch``)。++覆盖场景:+ - summary + include_last_turn=False → session_id=None+ - summary + include_last_turn=True → session_id="sess-1"+ - files + source="current" → session_id=None+ - files + source="last_turn" → session_id="sess-1"+ - detail + source="current" → session_id=None+ - detail + source="last_turn" → session_id="sess-1"+"""+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import patch++import pytest+++class FakeWebChannel:+ """记录 send_response 的简单 channel stub。"""++ def __init__(self) -> None:+ self.responses: list[dict] = []++ async def send_response(+ self, ws, req_id, *, ok, payload=None, error=None, code=None,+ ):+ self.responses.append(+ {+ "id": req_id,+ "ok": ok,+ "payload": payload,+ "error": error,+ "code": code,+ }+ )+++class FakeRegistry:+ """模拟 GitDiffWatcherRegistry,触发 on_initial/on_snapshot 回调。"""++ def __init__(self) -> None:+ self.add_watch_calls: list[dict] = []+ self.update_files_calls: list[dict] = []+ self.update_detail_calls: list[dict] = []+ self.commit_summary_calls: list[dict] = []+ self.commit_files_calls: list[dict] = []+ self.commit_detail_calls: list[dict] = []++ async def add_watch(+ self, ws, project_id, session_id, scope="summary", *,+ include_last_turn=True, on_initial=None,+ ):+ self.add_watch_calls.append({+ "project_id": project_id,+ "session_id": session_id,+ "include_last_turn": include_last_turn,+ })+ watch = SimpleNamespace(+ watch_id="wid-summary",+ project_id=project_id,+ session_id=session_id,+ ws=ws,+ scope=scope,+ # 与真实 registry 一致:空 session_id 时强制关闭 include_last_turn+ include_last_turn=bool(include_last_turn) and bool(session_id),+ )+ if on_initial is not None:+ status_dict = await on_initial(watch)+ self.commit_initial_summary(watch.watch_id, status_dict)+ return watch++ async def update_files_with_restore(+ self, watch_id, source, *,+ expected_ws=None, expected_project_id=None, on_snapshot=None,+ ):+ self.update_files_calls.append({+ "watch_id": watch_id,+ "source": source,+ "expected_project_id": expected_project_id,+ })+ watch = SimpleNamespace(+ watch_id=watch_id,+ project_id=expected_project_id or "proj-A",+ session_id="sess-1", # 模拟已有 watcher+ ws=expected_ws,+ files_source=source,+ )+ if on_snapshot is not None:+ await on_snapshot(watch)+ return watch++ async def update_detail_with_restore(+ self, watch_id, source, files, *,+ expected_ws=None, expected_project_id=None, on_snapshot=None,+ ):+ self.update_detail_calls.append({+ "watch_id": watch_id,+ "source": source,+ "files": list(files),+ "expected_project_id": expected_project_id,+ })+ watch = SimpleNamespace(+ watch_id=watch_id,+ project_id=expected_project_id or "proj-A",+ session_id="sess-1",+ ws=expected_ws,+ detail_source=source,+ detail_files=list(files),+ )+ if on_snapshot is not None:+ await on_snapshot(watch)+ return watch++ def commit_initial_summary(self, watch_id, status_dict):+ self.commit_summary_calls.append({"watch_id": watch_id})++ def commit_initial_files(self, watch_id, status_dict, source):+ self.commit_files_calls.append({"watch_id": watch_id, "source": source})++ def commit_initial_detail(self, watch_id, status_dict, source, detail_files):+ self.commit_detail_calls.append({"watch_id": watch_id, "source": source})+++def _make_handler(channel, registry):+ from jiuwenswarm.gateway.channel_manager.web.git_ws_handler import (+ GitDiffWebSocketHandler,+ )+ return GitDiffWebSocketHandler(channel=channel, registry=registry)+++def _make_project(project_id="proj-A", project_dir="/tmp/proj"):+ return SimpleNamespace(+ project_id=project_id,+ project_dir=project_dir,+ work_mode="code",+ git=SimpleNamespace(enabled=True),+ )+++def _make_fake_status_factory():+ """构造 fake DiffStatusService.get_project_diff_status,记录调用参数。++ 返回 (service, status_calls)。service 适配 handler 调用签名+ (keyword-only project/session_id/include_files/include_hunks)。+ """+ status_calls: list[dict] = []++ def fake_get_project_diff_status(+ *, project, session_id, include_files, include_hunks,+ ):+ status_calls.append({+ "project_id": project.project_id,+ "session_id": session_id,+ "include_files": include_files,+ "include_hunks": include_hunks,+ })+ return SimpleNamespace(+ to_dict=lambda include_hunks=False: {+ "project_id": project.project_id,+ "session_id": session_id,+ "repo": {+ "is_git": True,+ "repo_root": "/tmp/proj",+ "branch": "main",+ "head": "abc123",+ "transient": False,+ },+ "current": {"files": {"a.py": {"status": "M"}}},+ "last_turn": None,+ }+ )++ service = SimpleNamespace(get_project_diff_status=fake_get_project_diff_status)+ return service, status_calls+++def _patch_get_diff_status_service(service):+ """patch handler 内部 import 的 get_diff_status_service。"""+ return patch(+ "jiuwenswarm.server.runtime.session.git_diff_status.get_diff_status_service",+ return_value=service,+ )+++# ---------------------------------------------------------------------------+# summary 路径:_handle_diff_watch+# ---------------------------------------------------------------------------++async def test_summary_include_last_turn_false_passes_no_session_id():+ """include_last_turn=False 时不应传 session_id 给 get_project_diff_status。++ current-only 订阅场景:file_ops 历史读取异常不应阻断首次订阅。+ """+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)+ fake_service, status_calls = _make_fake_status_factory()++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "session_id": "sess-1",+ "include_last_turn": False,+ },+ )++ assert len(status_calls) == 1+ # 修复后:include_last_turn=False 不传 session_id+ assert status_calls[0]["session_id"] is None+ resp = channel.responses[0]+ assert resp["ok"] is True+++async def test_summary_include_last_turn_true_passes_session_id():+ """include_last_turn=True 时正常传 session_id,语义不变。"""+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)+ fake_service, status_calls = _make_fake_status_factory()++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "session_id": "sess-1",+ "include_last_turn": True,+ },+ )++ assert len(status_calls) == 1+ assert status_calls[0]["session_id"] == "sess-1"+++# ---------------------------------------------------------------------------+# files 路径:_handle_diff_files_watch+# ---------------------------------------------------------------------------++async def test_files_source_current_passes_no_session_id():+ """source="current" 时不应传 session_id 给 get_project_diff_status。"""+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)+ fake_service, status_calls = _make_fake_status_factory()++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_files_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "watch_id": "wid-1",+ "source": "current",+ "session_id": "sess-1",+ },+ )++ assert len(status_calls) == 1+ # 修复后:source="current" 不传 session_id+ assert status_calls[0]["session_id"] is None+ resp = channel.responses[0]+ assert resp["ok"] is True+++async def test_files_source_last_turn_passes_session_id():+ """source="last_turn" 时正常传 session_id,语义不变。"""+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)+ fake_service, status_calls = _make_fake_status_factory()++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_files_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "watch_id": "wid-1",+ "source": "last_turn",+ "session_id": "sess-1",+ },+ )++ assert len(status_calls) == 1+ assert status_calls[0]["session_id"] == "sess-1"+++# ---------------------------------------------------------------------------+# detail 路径:_handle_diff_detail_watch+# ---------------------------------------------------------------------------++async def test_detail_source_current_passes_no_session_id():+ """source="current" 时不应传 session_id 给 get_project_diff_status。"""+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)+ fake_service, status_calls = _make_fake_status_factory()++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_detail_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "watch_id": "wid-1",+ "source": "current",+ "session_id": "sess-1",+ "files": ["a.py"],+ },+ )++ assert len(status_calls) == 1+ # 修复后:source="current" 不传 session_id+ assert status_calls[0]["session_id"] is None+ resp = channel.responses[0]+ assert resp["ok"] is True+++async def test_detail_source_last_turn_passes_session_id():+ """source="last_turn" 时正常传 session_id,语义不变。"""+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)+ fake_service, status_calls = _make_fake_status_factory()++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_detail_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "watch_id": "wid-1",+ "source": "last_turn",+ "session_id": "sess-1",+ "files": ["a.py"],+ },+ )++ assert len(status_calls) == 1+ assert status_calls[0]["session_id"] == "sess-1"+++# ---------------------------------------------------------------------------+# 关键回归:current-only 订阅在 file_ops 历史异常时仍能成功+# ---------------------------------------------------------------------------++async def test_current_only_subscription_survives_file_ops_failure():+ """current-only summary 订阅,file_ops 历史读取异常时不应失败。++ 修复前:``get_project_diff_status(session_id="sess-1")`` 内部会调+ ``get_turn_diff_summaries`` 且异常向上抛,导致 add_watch 失败 →+ watcher 被回滚,前端拿不到 watch_id。++ 修复后:include_last_turn=False 时不传 session_id,绕过 file_ops 读取,+ current-only 订阅不受影响。+ """+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)++ def fake_get_project_diff_status(+ *, project, session_id, include_files, include_hunks,+ ):+ if session_id is not None:+ # 模拟 file_ops 历史读取失败+ raise RuntimeError("broken file_ops / change_set")+ return SimpleNamespace(+ to_dict=lambda include_hunks=False: {+ "project_id": project.project_id,+ "session_id": None,+ "repo": {+ "is_git": True,+ "repo_root": "/tmp/proj",+ "branch": "main",+ "head": "abc123",+ "transient": False,+ },+ "current": None,+ "last_turn": None,+ }+ )++ fake_service = SimpleNamespace(+ get_project_diff_status=fake_get_project_diff_status,+ )++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler."+ "GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project(), None, None),+ ),+ _patch_get_diff_status_service(fake_service),+ ):+ await handler._handle_diff_watch(+ ws=None, req_id="r1",+ params={+ "project_id": "proj-A",+ "session_id": "sess-1",+ "include_last_turn": False,+ },+ )++ # 修复后:ok=True,前端拿到 watch_id+ resp = channel.responses[0]+ assert resp["ok"] is True+ assert resp["payload"]["watch_id"] == "wid-summary"+ # 响应里 last_turn=None(因 include_last_turn=False)+ assert resp["payload"]["snapshot"]["last_turn"] is Nonediff --git a/tests/unit_tests/test_discard_turn_changes.py b/tests/unit_tests/test_discard_turn_changes.pyindex d58719e8fb..71956426af 100644--- a/tests/unit_tests/test_discard_turn_changes.py+++ b/tests/unit_tests/test_discard_turn_changes.py@@ -335,3 +335,40 @@ async def test_partial_failure_keeps_file_ops_for_retry():# 验证 watcher 仍标脏(已恢复的文件需要刷新前端)assert registry.mark_dirty_calls == ["proj-A"]+++async def test_restore_exception_returns_error_response():+ """恢复前置计算抛异常时返回结构化错误,而不是让 WS 连接被关闭。"""+ channel = FakeWebChannel()+ registry = FakeRegistry()+ handler = _make_handler(channel, registry)++ with (+ patch(+ "jiuwenswarm.gateway.channel_manager.web.git_ws_handler.GitDiffWebSocketHandler._resolve_git_project",+ return_value=(_make_project("proj-A"), None, None),+ ),+ patch(+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",+ return_value={"project_id": "proj-A"},+ ),+ patch(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_last_turn_info",+ return_value={"turn_index": 2, "timestamp": 1000.0},+ ),+ patch(+ "jiuwenswarm.agents.harness.common.session_ops_service.restore_session_files",+ side_effect=RuntimeError("broken file_ops"),+ ),+ ):+ await handler._handle_discard_turn_changes(+ ws=None, req_id="r1",+ params={"project_id": "proj-A", "session_id": "sess-1"},+ )++ resp = channel.responses[0]+ assert resp["ok"] is False+ assert resp["code"] == "INTERNAL_ERROR"+ assert "broken file_ops" in resp["error"]+ assert registry.mark_dirty_calls == []