Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(aipc): git状态监控性能优化

kdgmpw988da8c58666
diff --git a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py
index 2cc3de67af..a95e4d3daa 100644
--- a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py
+++ b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py
@@ -400,6 +400,7 @@ class GitDiffWebSocketHandler:
session_id=session_id_for_status or None,
include_files=True,
include_hunks=True,
+ hunk_paths=detail_files if source == "current" else None,
)
status_dict = status.to_dict(include_hunks=True)
files_dict = self._extract_files(status_dict, source) or {}
diff --git a/jiuwenswarm/server/runtime/session/git_diff_status.py b/jiuwenswarm/server/runtime/session/git_diff_status.py
index afb659566c..c08ec2dff5 100644
--- a/jiuwenswarm/server/runtime/session/git_diff_status.py
+++ b/jiuwenswarm/server/runtime/session/git_diff_status.py
@@ -691,6 +691,7 @@ class DiffStatusService:
session_id: str | None = None,
include_files: bool = False,
include_hunks: bool = False,
+ hunk_paths: list[str] | set[str] | tuple[str, ...] | None = None,
) -> ProjectGitDiffStatus:
"""聚合当前工作区 diff 和上一轮对话 diff(设计文档 §4.1.16)。
@@ -750,7 +751,12 @@ class DiffStatusService:
if repo_is_git and not repo_is_transient:
diff_service = get_diff_service()
try:
- raw_diff = diff_service.get_git_diff(project_dir)
+ raw_diff = diff_service.get_git_diff(
+ project_dir,
+ include_files=effective_include_files,
+ include_hunks=include_hunks,
+ hunk_paths=hunk_paths,
+ )
except Exception as exc: # noqa: BLE001
logger.warning(
"[DiffStatus] get_git_diff failed (project=%s dir=%s): %s",
diff --git a/jiuwenswarm/server/runtime/session/git_diff_watcher.py b/jiuwenswarm/server/runtime/session/git_diff_watcher.py
index cce44bd83f..11b63d650c 100644
--- a/jiuwenswarm/server/runtime/session/git_diff_watcher.py
+++ b/jiuwenswarm/server/runtime/session/git_diff_watcher.py
@@ -908,14 +908,18 @@ class GitDiffWatcherRegistry:
diff_service = get_diff_service()
# 项目级 ``current``(工作区 diff)与 session_id 无关,使用所有 watcher 的
- # include_files/include_hunks 并集计算一次,跨 session 复用。并集确保任意
- # watcher 需要的文件/hunk 数据都已包含(设计文档 §2.5)。
- union_need_files = any(w.files_source for w in watches)
- union_need_hunks = any(
- w.detail_source and w.detail_files for w in watches
+ # current 订阅需求并集计算一次,跨 session 复用。summary 只取统计,
+ # files 只取元数据,detail 仅为已展开文件计算 hunk。
+ current_need_files = any(
+ w.files_source == "current"
+ or (w.detail_source == "current" and w.detail_files)
+ for w in watches
)
- union_include_files = union_need_files or union_need_hunks
- union_include_hunks = union_need_hunks
+ current_detail_files: set[str] = set()
+ for watch in watches:
+ if watch.detail_source == "current" and watch.detail_files:
+ current_detail_files.update(watch.detail_files)
+ current_need_hunks = bool(current_detail_files)
# 用 asyncio.to_thread 包裹同步 Git 命令,避免阻塞事件循环。
# 所有错误(结构性 + 临时性)都向上抛出,由 _poll_loop 统一推送
@@ -928,8 +932,13 @@ class GitDiffWatcherRegistry:
service.get_project_diff_status,
project=proj,
session_id=None,
- include_files=union_include_files,
- include_hunks=union_include_hunks,
+ include_files=current_need_files,
+ include_hunks=current_need_hunks,
+ hunk_paths=current_detail_files or None,
+ )
+ revision = _build_revision(
+ "gitdiff",
+ _fingerprint(project_id, base_status.generated_at),
)
repo_root = base_status.repo.repo_root
@@ -941,13 +950,19 @@ class GitDiffWatcherRegistry:
session_groups.setdefault(watch.session_id, []).append(watch)
for session_id, group_watches in session_groups.items():
- # 该 session 组的 include_files/include_hunks(可能是并集的子集)
- need_files = any(w.files_source for w in group_watches)
- need_hunks = any(
- w.detail_source and w.detail_files for w in group_watches
+ # 该 session 组的 last_turn include_files/include_hunks 需求。
+ # current 已在项目级分层计算;last_turn 暂时保持现有 file_ops 路径,
+ # 但不把 current detail 需求错误扩大到 last_turn。
+ last_turn_need_files = any(
+ w.files_source == "last_turn"
+ or (w.detail_source == "last_turn" and w.detail_files)
+ for w in group_watches
+ )
+ last_turn_need_hunks = any(
+ w.detail_source == "last_turn" and w.detail_files
+ for w in group_watches
)
- include_files = need_files or need_hunks
- include_hunks = need_hunks
+ serialize_hunks = current_need_hunks or last_turn_need_hunks
# 计算 session 级 ``last_turn`` diff(不复用跨 session)。
# 直接调 ``get_turn_diff_summaries`` + ``_convert_turn_diff``,避免再次调
@@ -987,8 +1002,8 @@ class GitDiffWatcherRegistry:
last_turn = _convert_turn_diff(
turns[0],
repo_root=repo_root,
- include_files=include_files,
- include_hunks=include_hunks,
+ include_files=last_turn_need_files,
+ include_hunks=last_turn_need_hunks,
)
# 合并:复用项目级 ``current`` + session 级 ``last_turn``。
@@ -1004,7 +1019,7 @@ class GitDiffWatcherRegistry:
last_turn=last_turn,
generated_at=base_status.generated_at,
)
- status_dict = merged_status.to_dict(include_hunks=include_hunks)
+ status_dict = merged_status.to_dict(include_hunks=serialize_hunks)
for watch in group_watches:
summary_fp = _summary_fingerprint(
@@ -1012,21 +1027,27 @@ class GitDiffWatcherRegistry:
)
if summary_fp != watch.last_summary_fingerprint:
watch.last_summary_fingerprint = summary_fp
- await self._push_diff_changed(watch, status_dict, summary_fp)
+ await self._push_diff_changed(
+ watch, status_dict, summary_fp, revision,
+ )
if watch.files_source:
files_dict = self._extract_files(status_dict, watch.files_source)
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, status_dict, files_dict, files_fp)
+ await self._push_files_changed(
+ watch, status_dict, files_dict, files_fp, revision,
+ )
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, status_dict, files_dict, detail_fp)
+ await self._push_detail_changed(
+ watch, status_dict, files_dict, detail_fp, revision,
+ )
@staticmethod
def _extract_files(
@@ -1048,6 +1069,7 @@ class GitDiffWatcherRegistry:
watch: GitDiffWatch,
status_dict: dict[str, Any],
fingerprint: str,
+ revision: str | None = None,
) -> None:
"""推送 ``project.git.diff_changed`` 事件(设计文档 §3.6)。
@@ -1065,7 +1087,7 @@ class GitDiffWatcherRegistry:
"session_id": watch.session_id,
"scope": "summary",
"change_type": "summary",
- "revision": _build_revision("gitdiff", fingerprint),
+ "revision": revision or _build_revision("gitdiff", fingerprint),
"repo": {
"is_git": repo.get("is_git", False),
"repo_root": repo.get("repo_root"),
@@ -1120,6 +1142,7 @@ class GitDiffWatcherRegistry:
status_dict: dict[str, Any],
files_dict: dict[str, Any] | None,
fingerprint: str,
+ revision: str | None = None,
) -> None:
"""推送 ``project.git.diff_files_changed`` 事件(设计文档 §3.6)。"""
if self._channel is None:
@@ -1134,7 +1157,7 @@ class GitDiffWatcherRegistry:
"session_id": watch.session_id,
"source": watch.files_source,
"change_type": "files",
- "revision": _build_revision("gitdiff", fingerprint),
+ "revision": revision or _build_revision("gitdiff", fingerprint),
"files": files_no_hunks,
}
if watch.files_source == "last_turn":
@@ -1157,6 +1180,7 @@ class GitDiffWatcherRegistry:
status_dict: dict[str, Any],
files_dict: dict[str, Any] | None,
fingerprint: str,
+ revision: str | None = None,
) -> None:
"""推送 ``project.git.diff_detail_changed`` 事件(设计文档 §3.6)。"""
if self._channel is None:
@@ -1175,7 +1199,7 @@ class GitDiffWatcherRegistry:
"session_id": watch.session_id,
"source": watch.detail_source,
"change_type": "detail",
- "revision": _build_revision("gitdiff", fingerprint),
+ "revision": revision or _build_revision("gitdiff", fingerprint),
"files": detail_files,
}
if watch.detail_source == "last_turn":
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index 330a14a2cd..cb852cfdd4 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -1666,7 +1666,12 @@ class DiffService:
return "".join(kept), large_files
def _get_untracked_files(
- self, project_dir: str, max_files: int = MAX_FILES
+ self,
+ project_dir: str,
+ max_files: int = MAX_FILES,
+ *,
+ include_hunks: bool = True,
+ hunk_paths: set[str] | None = None,
) -> dict[str, dict[str, Any]]:
"""获取未跟踪文件列表,并读取内容计算行数与 hunk.
@@ -1737,28 +1742,32 @@ class DiffService:
continue
# 流式逐行读取:完整行数计入 stats(与 tracked 文件 git numstat
- # 口径一致),但 hunk lines 只保留前 MAX_LINES_PER_FILE 行用于展示,
- # 避免大文件爆内存。
+ # 口径一致)。仅在 detail 层需要该文件时保留 hunk lines,避免
+ # summary/files 层为未展开文件构造整文件 hunk。
hunk_lines: list[str] = []
total_lines = 0
+ wants_hunks = include_hunks and (
+ hunk_paths is None or rel_path in hunk_paths or abs_path in hunk_paths
+ )
try:
with open(abs_path, "r", encoding="utf-8", errors="replace", newline="") as f:
for line in f:
total_lines += 1
- if total_lines <= MAX_LINES_PER_FILE:
+ if wants_hunks and total_lines <= MAX_LINES_PER_FILE:
hunk_lines.append(line.rstrip("\r\n"))
except OSError:
files[abs_path] = entry
continue
truncated = total_lines > MAX_LINES_PER_FILE
- entry["hunks"] = [{
- "oldStart": 0,
- "oldLines": 0,
- "newStart": 1,
- "newLines": len(hunk_lines),
- "lines": [f"+{line}" for line in hunk_lines],
- }]
+ if wants_hunks:
+ entry["hunks"] = [{
+ "oldStart": 0,
+ "oldLines": 0,
+ "newStart": 1,
+ "newLines": len(hunk_lines),
+ "lines": [f"+{line}" for line in hunk_lines],
+ }]
entry["isTruncated"] = truncated
entry["linesAdded"] = total_lines
files[abs_path] = entry
@@ -1770,7 +1779,38 @@ class DiffService:
parts = Path(rel_path).parts
return any(part in INTERNAL_UNTRACKED_DIRS for part in parts)
- def get_git_diff(self, project_dir: str | None) -> dict[str, Any] | None:
+ @staticmethod
+ def _normalize_hunk_paths(
+ repo_dir: str,
+ hunk_paths: list[str] | set[str] | tuple[str, ...] | None,
+ ) -> set[str] | None:
+ """Normalize requested detail paths to repo-relative POSIX-style paths."""
+ if not hunk_paths:
+ return None
+ result: set[str] = set()
+ for raw in hunk_paths:
+ text = str(raw or "").strip()
+ if not text:
+ continue
+ candidate = Path(text)
+ rel = text
+ if candidate.is_absolute():
+ try:
+ rel = os.path.relpath(str(candidate), repo_dir)
+ except ValueError:
+ rel = text
+ rel = rel.replace("\\", "/").lstrip("/")
+ result.add(rel)
+ return result or None
+
+ def get_git_diff(
+ self,
+ project_dir: str | None,
+ *,
+ include_files: bool = True,
+ include_hunks: bool = True,
+ hunk_paths: list[str] | set[str] | tuple[str, ...] | None = None,
+ ) -> dict[str, Any] | None:
"""获取工作区相对于 HEAD 的 git diff,含未跟踪文件行数.
已跟踪文件走 ``git diff HEAD``;untracked 文件(含 unborn HEAD
@@ -1796,6 +1836,8 @@ class DiffService:
return None
if self._is_in_transient_git_state(repo_dir):
return None
+ effective_include_files = include_files or include_hunks
+ requested_hunk_paths = self._normalize_hunk_paths(repo_dir, hunk_paths)
files: dict[str, dict[str, Any]] = {}
total_files_changed = 0
@@ -1820,25 +1862,49 @@ class DiffService:
"files": {},
}
- if has_tracked_changes:
+ if has_tracked_changes and not effective_include_files and shortstat_stats:
+ total_files_changed += shortstat_stats["filesChanged"]
+ total_added += shortstat_stats["linesAdded"]
+ total_removed += shortstat_stats["linesRemoved"]
+ elif 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:
+ if numstat_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())
- filtered_output, large_files = self._split_large_file_diffs(diff_output)
- all_hunks, truncated_files = self._parse_git_diff_hunks(filtered_output)
+ if effective_include_files:
+ 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"]
+ )
+ 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 "")
+ )
+ else:
+ per_file_status = {}
+
+ all_hunks: dict[str, list[dict[str, Any]]] = {}
+ large_files: set[str] = set()
+ truncated_files: set[str] = set()
+ if include_hunks:
+ diff_args = ["--literal-pathspecs", "diff", "HEAD"]
+ if requested_hunk_paths is not None:
+ rel_paths = sorted(
+ p for p in requested_hunk_paths
+ if not Path(p).is_absolute()
+ )
+ if rel_paths:
+ diff_args.extend(["--", *rel_paths])
+ diff_output = self._run_git_command(repo_dir, diff_args)
+ if diff_output:
+ filtered_output, large_files = self._split_large_file_diffs(diff_output)
+ all_hunks, truncated_files = self._parse_git_diff_hunks(filtered_output)
+
+ if not effective_include_files:
+ per_file_stats = {}
for rel_path, stats in list(per_file_stats.items())[:MAX_FILES]:
abs_path = str(Path(repo_dir) / rel_path)
is_binary = bool(stats.get("isBinary", False))
@@ -1866,17 +1932,27 @@ class DiffService:
"lastEditTime": None,
}
- untracked_files = self._get_untracked_files(repo_dir, max_files=max(0, MAX_FILES - len(files)))
+ untracked_files = self._get_untracked_files(
+ repo_dir,
+ max_files=max(0, MAX_FILES - len(files)) if effective_include_files else MAX_FILES,
+ include_hunks=include_hunks,
+ hunk_paths=requested_hunk_paths,
+ )
+ if not effective_include_files:
+ untracked_stats_files = untracked_files
+ untracked_files = {}
+ else:
+ untracked_stats_files = untracked_files
for file_path, entry in untracked_files.items():
entry["status"] = "added"
files[file_path] = entry
- total_files_changed += len(untracked_files)
+ total_files_changed += len(untracked_stats_files)
# untracked 文件无 git diff 可统计,_get_untracked_files 已按文件内容
# 计算行数;此处补回 stats,避免 unborn HEAD 等场景下 lines_added 恒为 0。
- total_added += sum(int(f.get("linesAdded", 0) or 0) for f in untracked_files.values())
- total_removed += sum(int(f.get("linesRemoved", 0) or 0) for f in untracked_files.values())
+ total_added += sum(int(f.get("linesAdded", 0) or 0) for f in untracked_stats_files.values())
+ total_removed += sum(int(f.get("linesRemoved", 0) or 0) for f in untracked_stats_files.values())
- if not files:
+ if total_files_changed <= 0 and not files:
return None
return {
diff --git a/tests/unit_tests/server/test_diff_service.py b/tests/unit_tests/server/test_diff_service.py
index 5625ed2a61..3d49a875cb 100644
--- a/tests/unit_tests/server/test_diff_service.py
+++ b/tests/unit_tests/server/test_diff_service.py
@@ -165,6 +165,117 @@ def test_git_diff_staged_rename_brace_form_keeps_hunks(tmp_path):
assert file_info["hunks"][0]["lines"] # 非空
+def test_git_diff_summary_does_not_run_full_patch(monkeypatch):
+ from jiuwenswarm.server.utils import diff_service as ds_mod
+
+ calls: list[tuple[str, ...]] = []
+
+ def fake_run_git_command(project_dir, args):
+ calls.append(tuple(args))
+ if args == ["diff", "HEAD", "--shortstat"]:
+ return " 1 file changed, 2 insertions(+), 1 deletion(-)\n"
+ if args == ["-c", "core.quotepath=false", "ls-files", "--others", "--exclude-standard"]:
+ return ""
+ raise AssertionError(f"unexpected git command: {args}")
+
+ monkeypatch.setattr(ds_mod.DiffService, "_get_git_toplevel", staticmethod(lambda p: "/repo"))
+ monkeypatch.setattr(ds_mod.DiffService, "_is_in_transient_git_state", staticmethod(lambda p: False))
+ monkeypatch.setattr(ds_mod.DiffService, "_run_git_command", staticmethod(fake_run_git_command))
+
+ diff = ds_mod.DiffService().get_git_diff(
+ "/repo",
+ include_files=False,
+ include_hunks=False,
+ )
+
+ assert diff == {
+ "stats": {"filesChanged": 1, "linesAdded": 2, "linesRemoved": 1},
+ "files": {},
+ }
+ assert ("diff", "HEAD") not in calls
+ assert ("diff", "HEAD", "--numstat") not in calls
+
+
+def test_git_diff_files_layer_does_not_run_full_patch(monkeypatch):
+ from jiuwenswarm.server.utils import diff_service as ds_mod
+
+ calls: list[tuple[str, ...]] = []
+
+ def fake_run_git_command(project_dir, args):
+ calls.append(tuple(args))
+ if args == ["diff", "HEAD", "--shortstat"]:
+ return " 1 file changed, 2 insertions(+), 1 deletion(-)\n"
+ if args == ["diff", "HEAD", "--numstat"]:
+ return "2\t1\ta.txt\n"
+ if args == ["diff", "HEAD", "--name-status"]:
+ return "M\ta.txt\n"
+ if args == ["-c", "core.quotepath=false", "status", "--porcelain=v1"]:
+ return " M a.txt\n"
+ if args == ["-c", "core.quotepath=false", "ls-files", "--others", "--exclude-standard"]:
+ return ""
+ raise AssertionError(f"unexpected git command: {args}")
+
+ monkeypatch.setattr(ds_mod.DiffService, "_get_git_toplevel", staticmethod(lambda p: "/repo"))
+ monkeypatch.setattr(ds_mod.DiffService, "_is_in_transient_git_state", staticmethod(lambda p: False))
+ monkeypatch.setattr(ds_mod.DiffService, "_run_git_command", staticmethod(fake_run_git_command))
+
+ diff = ds_mod.DiffService().get_git_diff(
+ "/repo",
+ include_files=True,
+ include_hunks=False,
+ )
+
+ assert diff is not None
+ assert diff["files"][str(Path("/repo") / "a.txt")]["hunks"] == []
+ assert ("diff", "HEAD") not in calls
+
+
+def test_git_diff_detail_layer_limits_patch_to_requested_paths(monkeypatch):
+ from jiuwenswarm.server.utils import diff_service as ds_mod
+
+ calls: list[tuple[str, ...]] = []
+
+ def fake_run_git_command(project_dir, args):
+ calls.append(tuple(args))
+ if args == ["diff", "HEAD", "--shortstat"]:
+ return " 2 files changed, 2 insertions(+), 2 deletions(-)\n"
+ if args == ["diff", "HEAD", "--numstat"]:
+ return "1\t1\ta.txt\n1\t1\tb.txt\n"
+ if args == ["diff", "HEAD", "--name-status"]:
+ return "M\ta.txt\nM\tb.txt\n"
+ if args == ["-c", "core.quotepath=false", "status", "--porcelain=v1"]:
+ return " M a.txt\n M b.txt\n"
+ if args == ["--literal-pathspecs", "diff", "HEAD", "--", "a.txt"]:
+ return (
+ "diff --git a/a.txt b/a.txt\n"
+ "--- a/a.txt\n"
+ "+++ b/a.txt\n"
+ "@@ -1 +1 @@\n"
+ "-old\n"
+ "+new\n"
+ )
+ if args == ["-c", "core.quotepath=false", "ls-files", "--others", "--exclude-standard"]:
+ return ""
+ raise AssertionError(f"unexpected git command: {args}")
+
+ monkeypatch.setattr(ds_mod.DiffService, "_get_git_toplevel", staticmethod(lambda p: "/repo"))
+ monkeypatch.setattr(ds_mod.DiffService, "_is_in_transient_git_state", staticmethod(lambda p: False))
+ monkeypatch.setattr(ds_mod.DiffService, "_run_git_command", staticmethod(fake_run_git_command))
+
+ diff = ds_mod.DiffService().get_git_diff(
+ "/repo",
+ include_files=True,
+ include_hunks=True,
+ hunk_paths=["a.txt"],
+ )
+
+ assert diff is not None
+ assert diff["files"][str(Path("/repo") / "a.txt")]["hunks"]
+ assert diff["files"][str(Path("/repo") / "b.txt")]["hunks"] == []
+ assert ("diff", "HEAD") not in calls
+ assert ("--literal-pathspecs", "diff", "HEAD", "--", "a.txt") in calls
+
+
@pytest.fixture
def _sessions_dir(tmp_path, monkeypatch):
"""Mock get_agent_sessions_dir 返回 tmp_path/sessions。"""
diff --git a/tests/unit_tests/server/test_git_diff_watcher.py b/tests/unit_tests/server/test_git_diff_watcher.py
index ee322edc89..6751a12c10 100644
--- a/tests/unit_tests/server/test_git_diff_watcher.py
+++ b/tests/unit_tests/server/test_git_diff_watcher.py
@@ -143,3 +143,107 @@ async def test_empty_session_id_forces_include_last_turn_false(monkeypatch):
# 应被强制关闭
assert watch.include_last_turn is False
assert watch.session_id == ""
+
+
+async def test_current_layers_share_snapshot_revision_and_limit_hunk_paths(monkeypatch):
+ from jiuwenswarm.server.runtime.session import git_diff_watcher
+ from jiuwenswarm.server.runtime.session.git_diff_status import (
+ DiffFileEntry,
+ DiffHunk,
+ DiffRepoInfo,
+ DiffStats,
+ DiffSummary,
+ ProjectGitDiffStatus,
+ )
+
+ channel = _FakeChannel()
+ registry = git_diff_watcher.GitDiffWatcherRegistry(channel=channel)
+ watch = await registry.add_watch(
+ object(), "proj-A", "sess-1", include_last_turn=False,
+ )
+ await registry.update_files(watch.watch_id, "current")
+ await registry.update_detail(watch.watch_id, "current", ["a.py"])
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.project_store.get_project_by_id",
+ lambda project_id: _project(project_id),
+ )
+
+ status_calls: list[dict] = []
+
+ class _DiffStatusService:
+ def get_project_diff_status(self, **kwargs):
+ status_calls.append(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=True,
+ stats=DiffStats(files_changed=2, lines_added=2, lines_removed=1),
+ files={
+ "a.py": DiffFileEntry(
+ file_path="a.py",
+ status="modified",
+ lines_added=1,
+ lines_removed=1,
+ hunks=[
+ DiffHunk(
+ old_start=1,
+ old_lines=1,
+ new_start=1,
+ new_lines=1,
+ lines=["-old", "+new"],
+ )
+ ],
+ ),
+ "b.py": DiffFileEntry(
+ file_path="b.py",
+ status="modified",
+ lines_added=1,
+ lines_removed=0,
+ hunks=[],
+ ),
+ },
+ ),
+ generated_at=123.456,
+ )
+
+ 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 len(status_calls) == 1
+ assert status_calls[0]["include_files"] is True
+ assert status_calls[0]["include_hunks"] is True
+ assert status_calls[0]["hunk_paths"] == {"a.py"}
+ events_by_name = {event["event"]: event for event in channel.events}
+ assert set(events_by_name) == {
+ "project.git.diff_changed",
+ "project.git.diff_files_changed",
+ "project.git.diff_detail_changed",
+ }
+ revisions = {event["payload"]["revision"] for event in channel.events}
+ assert len(revisions) == 1
+ detail_files = events_by_name["project.git.diff_detail_changed"]["payload"]["files"]
+ assert detail_files["a.py"]["hunks"]
+ assert "b.py" not in detail_files
diff --git a/tests/unit_tests/test_diff_watch_session_id_propagation.py b/tests/unit_tests/test_diff_watch_session_id_propagation.py
index 3fe31b9b47..5f15771003 100644
--- a/tests/unit_tests/test_diff_watch_session_id_propagation.py
+++ b/tests/unit_tests/test_diff_watch_session_id_propagation.py
@@ -154,13 +154,14 @@ def _make_fake_status_factory():
status_calls: list[dict] = []
def fake_get_project_diff_status(
- *, project, session_id, include_files, include_hunks,
+ *, project, session_id, include_files, include_hunks, hunk_paths=None,
):
status_calls.append({
"project_id": project.project_id,
"session_id": session_id,
"include_files": include_files,
"include_hunks": include_hunks,
+ "hunk_paths": hunk_paths,
})
return SimpleNamespace(
to_dict=lambda include_hunks=False: {
@@ -291,6 +292,7 @@ async def test_files_source_current_passes_no_session_id():
assert len(status_calls) == 1
# 修复后:source="current" 不传 session_id
assert status_calls[0]["session_id"] is None
+ assert status_calls[0]["hunk_paths"] is None
resp = channel.responses[0]
assert resp["ok"] is True
@@ -323,6 +325,7 @@ async def test_files_source_last_turn_passes_session_id():
assert len(status_calls) == 1
assert status_calls[0]["session_id"] == "sess-1"
+ assert status_calls[0]["hunk_paths"] is None
# ---------------------------------------------------------------------------
@@ -359,6 +362,7 @@ async def test_detail_source_current_passes_no_session_id():
assert len(status_calls) == 1
# 修复后:source="current" 不传 session_id
assert status_calls[0]["session_id"] is None
+ assert status_calls[0]["hunk_paths"] == ["a.py"]
resp = channel.responses[0]
assert resp["ok"] is True
@@ -414,7 +418,7 @@ async def test_current_only_subscription_survives_file_ops_failure():
handler = _make_handler(channel, registry)
def fake_get_project_diff_status(
- *, project, session_id, include_files, include_hunks,
+ *, project, session_id, include_files, include_hunks, hunk_paths=None,
):
if session_id is not None:
# 模拟 file_ops 历史读取失败