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): 修复code工作模型下team.agent的文件追踪
kdgmpwe381a3f08a2d
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 04830a57cb..fa6ce5fcf7 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -8,6 +8,7 @@"prebuild": "cd ../../../.. && node ./jiuwenswarm/scripts/generate-agent-folders.js","dev": "vite","build": "tsc && vite build",+ "test:code-turn-diff-binding": "tsc src/features/code-mode/codeTurnDiffBinding.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/code-turn-diff-binding --skipLibCheck --noEmitOnError && node --test tests/codeTurnDiffBinding.test.mjs","test:openai-account-model-state": "tsc src/components/ConfigPanel/openaiAccountModelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/openai-account-model-state --skipLibCheck && node --test tests/openaiAccountModelState.test.mjs","test:tool-result-lifecycle": "tsc src/stores/toolResultLifecycle.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/tool-result-lifecycle --skipLibCheck --noEmitOnError && node --test tests/toolResultLifecycle.test.mjs","lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/teamEventUtils.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/teamEventUtils.tsindex 19d5f4c92c..9a5255b486 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/teamEventUtils.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/teamEventUtils.ts@@ -28,7 +28,7 @@ export function parseTeamEventMessage(message: Message): ParsedTeamEvent | nullreturn null;}- const [, jsonStr] = content.split('team.event:');+ const jsonStr = content.slice('team.event:'.length);try {const payload = JSON.parse(jsonStr);const event = payload.event || payload.payload?.event;diff --git a/jiuwenswarm/channels/web/frontend/src/features/code-mode/codeTurnDiffBinding.ts b/jiuwenswarm/channels/web/frontend/src/features/code-mode/codeTurnDiffBinding.tsnew file mode 100644index 0000000000..6b29d40753--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/code-mode/codeTurnDiffBinding.ts@@ -0,0 +1,97 @@+import type { Message } from '../../types';+import type { GitTurnDiff } from './types';++function isUserFacingTeamEvent(message: Message): boolean {+ if (message.role !== 'system' || !message.content.startsWith('team.event:')) {+ return false;+ }+ const jsonStr = message.content.slice('team.event:'.length);+ try {+ const payload = JSON.parse(jsonStr) as { event?: Record<string, unknown>; payload?: { event?: Record<string, unknown> } };+ const event = payload.event || payload.payload?.event;+ if (!event) return false;+ const type = typeof event.type === 'string' ? event.type : '';+ const fromMember = typeof event.from_member === 'string' ? event.from_member : '';+ const toMember = typeof event.to_member === 'string' ? event.to_member : '';+ const isP2PToUser = type === 'team.message.p2p' && toMember === 'user';+ const isLeaderToUser = fromMember === 'team_leader' && !type.endsWith('.p2p') && !type.endsWith('.broadcast');+ return isP2PToUser || isLeaderToUser;+ } catch {+ return false;+ }+}++function isAssistantTurnAnchor(message: Message): boolean {+ return (+ message.role === 'assistant' ||+ (+ message.role === 'system' &&+ (+ message.id.startsWith('team-leader-') ||+ message.content.startsWith('team.leader:') ||+ isUserFacingTeamEvent(message)+ )+ )+ );+}++function findDirectMessageId(messageIds: Set<string>, turn: GitTurnDiff): string | null {+ const candidates = [+ turn.assistant_message_id,+ turn.request_id,+ turn.assistant_message_id ? `team-leader-${turn.assistant_message_id}` : '',+ turn.request_id ? `team-leader-${turn.request_id}` : '',+ ];+ return candidates.find(candidate => candidate && messageIds.has(candidate)) ?? null;+}++/** Bind backend user-turn indexes to the assistant bubble rendered for that turn. */+export function bindTurnDiffsToMessages(messages: Message[], turns: GitTurnDiff[]): Map<string, GitTurnDiff[]> {+ const messageIds = new Set(messages.map(message => message.id));+ const assistantByTurnIndex = new Map<number, string>();+ const localTurnIndexByAssistantId = new Map<string, number>();+ const assistantByUserMessageId = new Map<string, string>();+ let currentTurnIndex = 0;+ let currentUserMessageId = '';++ messages.forEach(message => {+ if (message.role === 'user') {+ currentTurnIndex += 1;+ currentUserMessageId = message.id;+ return;+ }+ if (!currentTurnIndex || !isAssistantTurnAnchor(message)) return;+ // Keep the last assistant output before the next user message as the turn result.+ assistantByTurnIndex.set(currentTurnIndex, message.id);+ localTurnIndexByAssistantId.set(message.id, currentTurnIndex);+ if (currentUserMessageId) assistantByUserMessageId.set(currentUserMessageId, message.id);+ });++ // History pagination normally provides the newest contiguous message window.+ // Prefer an exact message-id anchor; otherwise align the latest local and backend turns.+ const latestBackendTurn = turns.reduce((latest, turn) => Math.max(latest, turn.turn_index), 0);+ let turnIndexOffset = Math.max(0, latestBackendTurn - currentTurnIndex);+ let latestAnchoredTurn = 0;+ turns.forEach(turn => {+ const directMessageId = findDirectMessageId(messageIds, turn) || (turn.user_message_id ? assistantByUserMessageId.get(turn.user_message_id) : undefined);+ const localTurnIndex = directMessageId ? localTurnIndexByAssistantId.get(directMessageId) : undefined;+ if (localTurnIndex && turn.turn_index >= latestAnchoredTurn) {+ latestAnchoredTurn = turn.turn_index;+ turnIndexOffset = turn.turn_index - localTurnIndex;+ }+ });++ const result = new Map<string, GitTurnDiff[]>();+ turns.forEach(turn => {+ const messageId =+ findDirectMessageId(messageIds, turn) ||+ (turn.user_message_id ? assistantByUserMessageId.get(turn.user_message_id) : undefined) ||+ assistantByTurnIndex.get(turn.turn_index - turnIndexOffset);+ if (!messageId) return;+ const boundTurns = result.get(messageId) ?? [];+ boundTurns.push(turn);+ boundTurns.sort((left, right) => left.turn_index - right.turn_index);+ result.set(messageId, boundTurns);+ });+ return result;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/code-mode/useCodeTurnDiffHistory.ts b/jiuwenswarm/channels/web/frontend/src/features/code-mode/useCodeTurnDiffHistory.tsindex a9abdf92be..662df94b64 100644--- a/jiuwenswarm/channels/web/frontend/src/features/code-mode/useCodeTurnDiffHistory.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/code-mode/useCodeTurnDiffHistory.ts@@ -2,71 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import type { Message, ProjectInfo } from '../../types';import { gitClient } from './gitClient';import type { GitTurnDiff } from './types';--function isAssistantTurnAnchor(message: Message): boolean {- return message.role === 'assistant' || (message.role === 'system' && (message.id.startsWith('team-leader-') || message.content.startsWith('team.leader:')));-}--function findDirectMessageId(messageIds: Set<string>, turn: GitTurnDiff): string | null {- const candidates = [- turn.assistant_message_id,- turn.request_id,- turn.assistant_message_id ? `team-leader-${turn.assistant_message_id}` : '',- turn.request_id ? `team-leader-${turn.request_id}` : '',- ];- return candidates.find(candidate => candidate && messageIds.has(candidate)) ?? null;-}--/** Bind backend user-turn indexes to the assistant bubble rendered for that turn. */-export function bindTurnDiffsToMessages(messages: Message[], turns: GitTurnDiff[]): Map<string, GitTurnDiff[]> {- const messageIds = new Set(messages.map(message => message.id));- const assistantByTurnIndex = new Map<number, string>();- const localTurnIndexByAssistantId = new Map<string, number>();- const assistantByUserMessageId = new Map<string, string>();- let currentTurnIndex = 0;- let currentUserMessageId = '';-- messages.forEach(message => {- if (message.role === 'user') {- currentTurnIndex += 1;- currentUserMessageId = message.id;- return;- }- if (!currentTurnIndex || !isAssistantTurnAnchor(message)) return;- // Keep the last assistant output before the next user message as the turn result.- assistantByTurnIndex.set(currentTurnIndex, message.id);- localTurnIndexByAssistantId.set(message.id, currentTurnIndex);- if (currentUserMessageId) assistantByUserMessageId.set(currentUserMessageId, message.id);- });-- // History pagination normally provides the newest contiguous message window.- // Prefer an exact message-id anchor; otherwise align the latest local and backend turns.- const latestBackendTurn = turns.reduce((latest, turn) => Math.max(latest, turn.turn_index), 0);- let turnIndexOffset = Math.max(0, latestBackendTurn - currentTurnIndex);- let latestAnchoredTurn = 0;- turns.forEach(turn => {- const directMessageId = findDirectMessageId(messageIds, turn) || (turn.user_message_id ? assistantByUserMessageId.get(turn.user_message_id) : undefined);- const localTurnIndex = directMessageId ? localTurnIndexByAssistantId.get(directMessageId) : undefined;- if (localTurnIndex && turn.turn_index >= latestAnchoredTurn) {- latestAnchoredTurn = turn.turn_index;- turnIndexOffset = turn.turn_index - localTurnIndex;- }- });-- const result = new Map<string, GitTurnDiff[]>();- turns.forEach(turn => {- const messageId =- findDirectMessageId(messageIds, turn) ||- (turn.user_message_id ? assistantByUserMessageId.get(turn.user_message_id) : undefined) ||- assistantByTurnIndex.get(turn.turn_index - turnIndexOffset);- if (!messageId) return;- const boundTurns = result.get(messageId) ?? [];- boundTurns.push(turn);- boundTurns.sort((left, right) => left.turn_index - right.turn_index);- result.set(messageId, boundTurns);- });- return result;-}+import { bindTurnDiffsToMessages } from './codeTurnDiffBinding';+export { bindTurnDiffsToMessages } from './codeTurnDiffBinding';interface UseCodeTurnDiffHistoryOptions {project: ProjectInfo | null;diff --git a/jiuwenswarm/channels/web/frontend/tests/codeTurnDiffBinding.test.mjs b/jiuwenswarm/channels/web/frontend/tests/codeTurnDiffBinding.test.mjsnew file mode 100644index 0000000000..2925102cf6--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/codeTurnDiffBinding.test.mjs@@ -0,0 +1,102 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { bindTurnDiffsToMessages } from '../node_modules/.cache/code-turn-diff-binding/features/code-mode/codeTurnDiffBinding.js';++const turn = (overrides = {}) => ({+ kind: 'conversation_turn',+ turn_index: 1,+ timestamp: '2026-07-23T10:00:01.000Z',+ user_prompt_preview: 'write code',+ stats: { files_changed: 1, lines_added: 2, lines_removed: 0 },+ files: {},+ change_set_id: 'cs-1',+ request_id: 'req-1',+ assistant_message_id: 'assistant-1',+ user_message_id: 'user-1',+ status: 'completed',+ ...overrides,+});++test('binds team agent p2p output to the turn diff card anchor', () => {+ const teamAgentMessage = {+ id: 'team-message-1',+ role: 'system',+ content: `team.event:${JSON.stringify({+ event: {+ type: 'team.message.p2p',+ from_member: 'code_agent',+ to_member: 'user',+ content: 'done',+ message_id: 'member-msg-1',+ timestamp: Date.now(),+ },+ })}`,+ timestamp: '2026-07-23T10:00:02.000Z',+ };++ const result = bindTurnDiffsToMessages([+ {+ id: 'user-1',+ role: 'user',+ content: 'write code',+ timestamp: '2026-07-23T10:00:00.000Z',+ },+ teamAgentMessage,+ ], [turn()]);++ assert.deepEqual(result.get('team-message-1'), [turn()]);+});++test('binds team event when payload content contains the team event prefix', () => {+ const result = bindTurnDiffsToMessages([+ {+ id: 'user-1',+ role: 'user',+ content: 'write code',+ timestamp: '2026-07-23T10:00:00.000Z',+ },+ {+ id: 'team-message-prefix-content',+ role: 'system',+ content: `team.event:${JSON.stringify({+ event: {+ type: 'team.message.p2p',+ from_member: 'code_agent',+ to_member: 'user',+ content: 'literal marker team.event: should stay inside JSON',+ message_id: 'member-msg-prefix',+ timestamp: Date.now(),+ },+ })}`,+ timestamp: '2026-07-23T10:00:02.000Z',+ },+ ], [turn()]);++ assert.deepEqual(result.get('team-message-prefix-content'), [turn()]);+});++test('does not bind hidden team collaboration broadcasts as visible anchors', () => {+ const result = bindTurnDiffsToMessages([+ {+ id: 'user-1',+ role: 'user',+ content: 'write code',+ timestamp: '2026-07-23T10:00:00.000Z',+ },+ {+ id: 'team-message-hidden',+ role: 'system',+ content: `team.event:${JSON.stringify({+ event: {+ type: 'team.message.broadcast',+ from_member: 'code_agent',+ content: 'internal update',+ },+ })}`,+ timestamp: '2026-07-23T10:00:02.000Z',+ },+ ], [turn()]);++ assert.equal(result.size, 0);+});diff --git a/jiuwenswarm/gateway/channel_manager/channel_manager.py b/jiuwenswarm/gateway/channel_manager/channel_manager.pyindex 8a8bcf1852..28ea40c4e6 100644--- a/jiuwenswarm/gateway/channel_manager/channel_manager.py+++ b/jiuwenswarm/gateway/channel_manager/channel_manager.py@@ -244,7 +244,7 @@ class ChannelManager(ABC):# chat.file / chat.media 默认只投递到发起 channel(msg.channel_id),# team 模式下已 /join 的其他 channel(如飞书)收不到。这里在进入# fan_out 分发前,依据 SessionSharingRegistry 自动补齐 fan_out_targets,- # 使文件能投递到所有已接入 channel(自动模式 godview + mention_all),或 send_file_targets 指定的目标。+ # 使文件按发起者定向投递(自动模式 last-originator 精确到人,无则回退 godview),或 send_file_targets 指定的目标。# helper 会按需写入 msg.metadata["fan_out_targets"],下方既有逻辑随之分发。await self._inject_file_delivery_fanout(msg, _et)@@ -418,9 +418,10 @@ class ChannelManager(ABC):- 若 msg.metadata 含 send_file_targets(工具显式指定目标 channel/席位)→按目标反查 Registry 的 *人类成员* 订阅(排除 GodView,避免 godview 全量广播泄漏到其他 channel),构造 mention 目标;无匹配则回退 godview。- - 否则(自动模式)→ 构造 [godview, mention_all] 双目标:godview 覆盖 web 等已注册- GodView 的 channel;mention_all 覆盖所有 /join 的人类成员席位(飞书/xiaoyi 的- reviewer-N)。dispatch_to_session 按物理容器去重,同一 channel 不会重复收文件。+ - 否则(自动模式)→ 发起者优先定向:按 session_id 反查最近一次人类发起者+ (last-originator) 构造 mention 目标,精确定向到该席位(多 app 不互窜);+ 无发起者(web 发起 / 无人类 /join / 并发覆盖到另一 human)→ 仅 godview+ (不误投 feishu 等 IM channel)。非文件类事件、或 Registry 无订阅时返回 None(回退到单 channel 兜底,避免破坏纯 web 会话)。"""diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 4ce12e5fb7..c1f2bf5f91 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -3767,14 +3767,21 @@ class AgentWebSocketServer:await send_wire_payload(ws, wire)async def _handle_command_diff(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from jiuwenswarm.server.runtime.session.git_diff_status import get_session_extra_history_rootsfrom jiuwenswarm.server.utils.diff_service import get_diff_servicetry:session_id = request.session_id or "default"project_dir = resolve_request_project_dir(request)+ extra_history_roots = get_session_extra_history_roots(session_id)diff_service = get_diff_service()turns, git_diff = await asyncio.gather(- asyncio.to_thread(diff_service.get_turn_diffs, session_id, project_dir),+ asyncio.to_thread(+ diff_service.get_turn_diffs,+ session_id,+ project_dir,+ extra_history_roots=extra_history_roots,+ ),asyncio.to_thread(diff_service.get_git_diff, project_dir),)diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex 8d6ef65b26..4a7ce152bc 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -7,13 +7,18 @@ from __future__ import annotationsimport asyncioimport loggingimport os+import reimport timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, AsyncIteratorfrom openjiuwen.agent_teams.context import reset_session_id, set_session_id-from openjiuwen.agent_teams.paths import get_agent_teams_home, team_home+from openjiuwen.agent_teams.paths import (+ get_agent_teams_home,+ independent_member_workspace,+ team_home,+)from openjiuwen.agent_teams.runtime import RunActionKindfrom openjiuwen.agent_teams.schema.team import TeamRolefrom openjiuwen.agent_teams.monitor import TeamStreamLogger@@ -105,6 +110,13 @@ _FOLLOWUP_INTERACT_BOUNDARY_TIMEOUT_SEC = 10.0_FOLLOWUP_INTERACT_POLL_INTERVAL_SEC = 0.05+def _safe_team_path_segment(value: str, fallback: str = "_") -> str:+ """Sanitize a value into one path segment for team workspace paths."""+ normalized = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "").strip())+ normalized = normalized.strip("._-")+ return normalized[:96] or fallback++def _team_hide_teammate_enabled() -> bool:"""Return whether non-leader teammate frames should be filtered out in team mode."""return os.environ.get(_HIDE_TEAMMATE_ENV_KEY, "").strip().lower() == "true"@@ -1234,7 +1246,7 @@ def _team_spec_skills_dir(team_spec: Any) -> str:return str(team_home(team_name) / "team-workspace" / "skills")-def _team_spec_monitor_roots(team_spec: Any) -> list[str]:+def _team_spec_monitor_roots(team_spec: Any, session_id: str | None = None) -> list[str]:"""Return team/member workspace roots where file-op history may be written."""roots: list[str] = []@@ -1255,6 +1267,13 @@ def _team_spec_monitor_roots(team_spec: Any) -> list[str]:home = team_home(team_name)add_root(root_path or str(home / "team-workspace"))add_root(home / "workspaces")+ if session_id and team_name:+ # 与读取侧 get_session_extra_history_roots / team_session_worktrees_dir 对齐:+ # 对 session_id 做 sanitize,避免含特殊字符时持久化"幽灵路径"+ # (raw sid 未经 sanitize,与实际 worktree 目录不一致)。+ # 此处用已 import 的 team_home(可被测试 patch)而非 team_session_worktrees_dir+ # (后者内部调用 openjiuwen 自身的 team_home,无法被 monkeypatch)。+ add_root(home / "sessions" / _safe_team_path_segment(session_id) / "worktrees")agents = getattr(team_spec, "agents", None)if isinstance(agents, dict):@@ -1262,12 +1281,24 @@ def _team_spec_monitor_roots(team_spec: Any) -> list[str]:member_workspace = getattr(member_spec, "workspace", None)add_root(getattr(member_workspace, "root_path", None))add_root(home / "workspaces" / f"{member_name}_workspace")+ # 兜底: member 可能使用 independent_member_workspace(位于 team_home 之外,+ # get_openjiuwen_home()/{member}_workspace),仅靠上面的 home/workspaces+ # 无法覆盖,需显式补上,否则该 member 的 file_ops 不会被收集。+ try:+ add_root(str(independent_member_workspace(str(member_name))))+ except Exception as exc: # noqa: BLE001+ logger.debug(+ "[TeamHelpers] failed to resolve independent member workspace: "+ "member=%s error=%s",+ member_name,+ exc,+ )return rootsdef _persist_team_file_monitor_roots(session_id: str, team_spec: Any) -> None:- roots = _team_spec_monitor_roots(team_spec)+ roots = _team_spec_monitor_roots(team_spec, session_id=session_id)if not roots:returntry:@@ -1278,6 +1309,14 @@ def _persist_team_file_monitor_roots(session_id: str, team_spec: Any) -> None:metadata = _read_metadata(session_id, cache_bust=True)if not metadata:+ # metadata.json 尚未初始化: 此时无法持久化 team_file_monitor_roots。+ # 读取侧 get_session_extra_history_roots 会基于 team_name 兜底推断标准+ # 布局路径,功能不丢失,但记录 warning 便于排查 metadata 初始化时序问题。+ logger.warning(+ "[TeamHelpers] cannot persist team_file_monitor_roots: "+ "metadata not initialized, session=%s",+ session_id,+ )returnexisting = metadata.get("team_file_monitor_roots")# 直接替换而非合并: team_spec 是当前 team 组成的权威来源,@@ -1287,7 +1326,10 @@ def _persist_team_file_monitor_roots(session_id: str, team_spec: Any) -> None:metadata["team_file_monitor_roots"] = roots_enqueue_write(session_id, metadata, preserve_pin_fields=True)except Exception as exc: # noqa: BLE001- logger.debug(+ # 写盘失败会影响 last_turn 文件追踪(读取侧只能靠 team_name 兜底推断,+ # 无法覆盖 independent_member_workspace 等非标准布局),升级为 warning+ # 以便在日志中及时发现。+ logger.warning("[TeamHelpers] failed to persist team file monitor roots: session=%s error=%s",session_id,exc,diff --git a/jiuwenswarm/server/runtime/session/git_diff_status.py b/jiuwenswarm/server/runtime/session/git_diff_status.pyindex 2c47445f73..b42edae3ff 100644--- a/jiuwenswarm/server/runtime/session/git_diff_status.py+++ b/jiuwenswarm/server/runtime/session/git_diff_status.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport loggingimport os+import reimport timefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -21,6 +22,13 @@ from jiuwenswarm.server.utils.diff_service import get_diff_servicelogger = logging.getLogger(__name__)+def _safe_team_path_segment(value: str, fallback: str = "_") -> str:+ """Sanitize a value into one path segment for team workspace paths."""+ normalized = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "").strip())+ normalized = normalized.strip("._-")+ return normalized[:96] or fallback++@dataclass(slots=True)class DiffStats:"""Diff 变更统计,``DiffSummary`` 和 ``DiffTurnSummary`` 共用。"""@@ -245,6 +253,7 @@ def get_session_extra_history_roots(session_id: str | None) -> list[str]:sid = str(session_id or "").strip()if not sid:return []+ safe_sid = _safe_team_path_segment(sid)try:from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata@@ -302,14 +311,16 @@ def get_session_extra_history_roots(session_id: str | None) -> list[str]:home = Path(*parts[: idx + 1])add_root(str(home / "team-workspace"))add_root(str(home / "workspaces"))+ add_root(str(home / "sessions" / safe_sid / "worktrees"))except Exception: # noqa: BLE001continuetry:- from openjiuwen.agent_teams.paths import team_home+ from openjiuwen.agent_teams.paths import team_home, team_session_worktrees_dirhome = team_home(team_name)add_root(str(home / "team-workspace"))add_root(str(home / "workspaces"))+ add_root(str(team_session_worktrees_dir(team_name, sid)))except Exception: # noqa: BLE001passreturn rootsdiff --git a/jiuwenswarm/server/runtime/session/git_diff_watcher.py b/jiuwenswarm/server/runtime/session/git_diff_watcher.pyindex ce043cafe9..0e88edd8a4 100644--- a/jiuwenswarm/server/runtime/session/git_diff_watcher.py+++ b/jiuwenswarm/server/runtime/session/git_diff_watcher.py@@ -891,6 +891,7 @@ class GitDiffWatcherRegistry:ProjectGitDiffStatus,_convert_turn_diff,get_diff_status_service,+ get_session_extra_history_roots,)from jiuwenswarm.server.utils.diff_service import get_diff_serviceservice = get_diff_status_service()@@ -945,8 +946,15 @@ class GitDiffWatcherRegistry:last_turn = Noneif session_id:try:+ # 与首次快照路径(DiffStatusService.get_project_diff_status)对齐:+ # 传入 extra_history_roots 以收集 team/member workspace 与+ # session worktree 下的 file_ops,否则多 member 在 git worktree+ # 工作时的改动会被漏读,导致实时轮询推送的 last_turn 数据残缺。+ extra_roots = get_session_extra_history_roots(session_id)turns = await asyncio.to_thread(- diff_service.get_turn_diffs, session_id, project_dir,+ diff_service.get_turn_diffs,+ session_id, project_dir,+ extra_history_roots=extra_roots,)except Exception as exc: # noqa: BLE001logger.warning(diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.pyindex 9a95d21007..67a2777899 100644--- a/jiuwenswarm/server/utils/diff_service.py+++ b/jiuwenswarm/server/utils/diff_service.py@@ -8,6 +8,7 @@ import difflibimport copyimport jsonimport logging+import osimport threadingimport uuidfrom datetime import datetime, timezone@@ -27,6 +28,14 @@ MAX_FILES = 50MAX_DIFF_SIZE_BYTES = 1_000_000MAX_LINES_PER_FILE = 400MAX_FILES_FOR_DETAILS = 500+HISTORY_PRIORITY_PROJECT_ROOT = 0+HISTORY_PRIORITY_SHARED_WORKSPACE = 10+HISTORY_PRIORITY_EXTRA_ROOT = 20+HISTORY_PRIORITY_UNKNOWN = 50+WORKTREE_HISTORY_CONTAINERS: tuple[tuple[str, ...], ...] = (+ (".worktrees",),+ (".jiuwen", "worktrees"),+)# change_sets.json 写入锁:保证同一进程内多线程惰性回填时不互相覆盖。_CHANGE_SET_LOCK = threading.Lock()@@ -654,6 +663,98 @@ class DiffService:add_history_dir(child / ".agent_history")return result+ @staticmethod+ def _default_worktree_history_roots(project_dir: str | None) -> list[str]:+ """Return known local worktree container dirs under the project root."""+ if not project_dir:+ return []+ root = Path(project_dir)+ return [str(root.joinpath(*parts)) for parts in WORKTREE_HISTORY_CONTAINERS]++ @classmethod+ def _history_roots_with_worktree_containers(+ cls,+ project_dir: str | None,+ extra_history_roots: list[str] | None = None,+ ) -> list[str]:+ """Return explicit roots plus known worktree containers below each root."""+ roots: list[str] = []+ seen: set[str] = set()++ def add_root(value: str | None) -> None:+ raw = str(value or "").strip()+ if not raw:+ return+ try:+ key = os.path.normcase(str(Path(raw).expanduser().resolve()))+ except Exception:+ key = os.path.normcase(raw)+ if key in seen:+ return+ seen.add(key)+ roots.append(raw)++ for root in cls._default_worktree_history_roots(project_dir):+ add_root(root)+ for root in extra_history_roots or []:+ if not isinstance(root, str):+ continue+ raw = root.strip()+ if not raw:+ continue+ add_root(raw)+ for child_root in cls._default_worktree_history_roots(raw):+ add_root(child_root)+ return roots++ @staticmethod+ def _get_git_common_worktree_root(worktree_root: Path) -> Path | None:+ """Return the canonical repo root for a linked git worktree, if known."""+ if not worktree_root.is_dir():+ return None+ common_dir = DiffService._run_git_command(+ str(worktree_root),+ ["rev-parse", "--git-common-dir"],+ )+ if not common_dir or not common_dir.strip():+ return None+ common_path = Path(common_dir.strip())+ if not common_path.is_absolute():+ common_path = worktree_root / common_path+ try:+ common_path = common_path.resolve()+ except OSError:+ pass+ if common_path.name != ".git":+ return None+ canonical_root = common_path.parent+ try:+ worktree_resolved = worktree_root.resolve()+ canonical_resolved = canonical_root.resolve()+ except OSError:+ return None+ if worktree_resolved == canonical_resolved:+ return None+ return canonical_resolved++ @staticmethod+ def _map_worktree_file_path(+ file_path: str,+ *,+ source_root: Path,+ target_root: Path | None,+ ) -> str:+ """Map a file-op path from a linked worktree back to the canonical repo."""+ if target_root is None:+ return file_path+ try:+ path = Path(file_path).expanduser().resolve()+ source = source_root.expanduser().resolve()+ rel = path.relative_to(source)+ except Exception:+ return file_path+ return str(target_root / rel)+@staticmethoddef _is_internal_team_workspace_file(file_path: str) -> bool:"""Return whether an edited file is an internal team workspace artifact."""@@ -675,12 +776,28 @@ class DiffService:extra_history_roots: 额外写入根目录,例如 team/member workspace。"""result: dict[str, Any] = {}+ history_file_priorities: dict[str, int] = {}++ def path_key(path: Path) -> str:+ try:+ return os.path.normcase(str(path.resolve()))+ except OSError:+ return os.path.normcase(str(path))++ def add_history_file(path: Path, priority: int) -> None:+ paths.append(path)+ history_file_priorities.setdefault(path_key(path), priority)# 1. 从 Agent Workspace 和 User Workspace 读取(公共位置)- paths = [+ paths: list[Path] = []+ add_history_file(get_agent_workspace_dir() / ".agent_history" / f"file_ops_{self._agent_id}.json",+ HISTORY_PRIORITY_SHARED_WORKSPACE,+ )+ add_history_file(get_user_workspace_dir() / ".agent_history" / f"file_ops_{self._agent_id}.json",- ]+ HISTORY_PRIORITY_SHARED_WORKSPACE,+ )# 2. session-specific file_ops(如 file_ops_jiuwenswarm_tui_xxx.json)if session_id:@@ -691,7 +808,7 @@ class DiffService:for f in hist_dir.iterdir():name = f.nameif self._is_valid_file_ops_file(name, session_id, require_session=True):- paths.append(f)+ add_history_file(f, HISTORY_PRIORITY_SHARED_WORKSPACE)# 3. 从项目目录读取(实际写入位置)# 如果未传入 project_dir,尝试从 session metadata 获取@@ -703,17 +820,14 @@ class DiffService:for f in project_hist_dir.iterdir():name = f.nameif self._is_valid_file_ops_file(name, session_id):- paths.append(f)+ add_history_file(f, HISTORY_PRIORITY_PROJECT_ROOT)global_file = project_hist_dir / f"file_ops_{self._agent_id}.json"if global_file.exists():- paths.append(global_file)- extra_roots: list[str] = []- if extra_history_roots:- extra_roots.extend(- str(root).strip()- for root in extra_history_roots- if isinstance(root, str) and str(root).strip()- )+ add_history_file(global_file, HISTORY_PRIORITY_PROJECT_ROOT)+ extra_roots = self._history_roots_with_worktree_containers(+ project_dir,+ extra_history_roots,+ )for project_hist_dir in self._agent_history_dirs_for_roots(extra_roots,@@ -724,11 +838,27 @@ class DiffService:for f in project_hist_dir.iterdir():name = f.nameif self._is_valid_file_ops_file(name, session_id):- paths.append(f)+ add_history_file(f, HISTORY_PRIORITY_EXTRA_ROOT)# 也读取全局 file_ops 文件(不带 session_id 后缀的)global_file = project_hist_dir / f"file_ops_{self._agent_id}.json"if global_file.exists():- paths.append(global_file)+ add_history_file(global_file, HISTORY_PRIORITY_EXTRA_ROOT)++ worktree_root_cache: dict[Path, Path | None] = {}++ def mapped_file_path_for_history(file_path: str, history_file: Path) -> str:+ source_root = history_file.parent.parent+ try:+ source_key = source_root.resolve()+ except OSError:+ source_key = source_root+ if source_key not in worktree_root_cache:+ worktree_root_cache[source_key] = self._get_git_common_worktree_root(source_root)+ return self._map_worktree_file_path(+ file_path,+ source_root=source_root,+ target_root=worktree_root_cache[source_key],+ )# 用于规范化路径,避免大小写差异导致的重复def normalize_path(p: str) -> str:@@ -736,44 +866,77 @@ class DiffService:# 使用 pathlib.Path 规范化路径try:return str(Path(p).resolve())- except Exception:+ except OSError:return p.replace("\\", "/").lower()+ def comparable_path_key(p: str) -> str:+ return p.lower()++ result_entry_priorities: dict[str, list[int]] = {}+ result_path_by_comparable_key: dict[str, str] = {}+for history_file in paths:if history_file.exists():try:data = json.loads(history_file.read_text(encoding="utf-8"))+ history_priority = history_file_priorities.get(+ path_key(history_file),+ HISTORY_PRIORITY_UNKNOWN,+ )for file_path, entries in data.items():- if self._is_internal_team_workspace_file(file_path):+ mapped_file_path = mapped_file_path_for_history(file_path, history_file)+ if self._is_internal_team_workspace_file(mapped_file_path):continue# 规范化路径,避免大小写差异导致的重复- normalized_path = normalize_path(file_path)+ normalized_path = normalize_path(mapped_file_path)+ comparable_key = comparable_path_key(normalized_path)+ normalized_path = result_path_by_comparable_key.setdefault(+ comparable_key,+ normalized_path,+ )if normalized_path not in result:result[normalized_path] = []+ result_entry_priorities[normalized_path] = []# 合并条目,避免时间戳相近的重复记录for entry in entries:# 检查是否已存在相同时间戳(±1秒)的相同操作ts = entry.get("timestamp", "")action = entry.get("action", "")is_duplicate = False- for existing in result[normalized_path]:+ duplicate_index: int | None = None+ for idx, existing in enumerate(result[normalized_path]):existing_ts = existing.get("timestamp", "")existing_action = existing.get("action", "")- if action == existing_action:+ same_content = (+ entry.get("old_content") == existing.get("old_content")+ and entry.get("new_content") == existing.get("new_content")+ )+ if action == existing_action and same_content:# 比较时间戳是否相近(同一秒内)try:t1 = datetime.fromisoformat(ts.replace("Z", "+00:00"))t2 = datetime.fromisoformat(existing_ts.replace("Z", "+00:00"))if abs((t1 - t2).total_seconds()) < 2:is_duplicate = True+ duplicate_index = idxbreakexcept (ValueError, TypeError):# 时间戳格式无效,无法比较,跳过此条目比较continue- if not is_duplicate:+ if is_duplicate:+ priorities = result_entry_priorities[normalized_path]+ if (+ duplicate_index is not None+ and duplicate_index < len(priorities)+ and history_priority < priorities[duplicate_index]+ ):+ result[normalized_path][duplicate_index] = entry+ priorities[duplicate_index] = history_priority+ else:result[normalized_path].append(entry)- except Exception as e:- logger.warning(f"Failed to read agent history file {history_file}: {e}")+ result_entry_priorities[normalized_path].append(history_priority)+ except (json.JSONDecodeError, OSError) as e:+ logger.warning("Failed to read agent history file %s: %s", history_file, e)return result@@ -1756,13 +1919,10 @@ class DiffService:if self._is_valid_file_ops_file(f.name, session_id, require_session=True):if f not in file_ops_paths:file_ops_paths.append(f)- extra_roots: list[str] = []- if extra_history_roots:- extra_roots.extend(- str(root).strip()- for root in extra_history_roots- if isinstance(root, str) and str(root).strip()- )+ extra_roots = self._history_roots_with_worktree_containers(+ resolved_project_dir,+ extra_history_roots,+ )for project_hist_dir in self._agent_history_dirs_for_roots(extra_roots,diff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.pyindex 2b7f0bf539..96af152cac 100644--- a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py@@ -294,6 +294,63 @@ async def test_handle_command_diff_returns_summary_payload(server, fake_ws):]+async def test_handle_command_diff_includes_session_extra_history_roots(+ server, fake_ws, monkeypatch+):+ captured = {}++ class FakeDiffService:+ def get_turn_diffs(self, session_id, project_dir, **kwargs):+ captured["turns"] = {+ "session_id": session_id,+ "project_dir": project_dir,+ "kwargs": kwargs,+ }+ return []++ def get_git_diff(self, project_dir):+ captured["git_diff_project_dir"] = project_dir+ return None++ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_diff_service",+ lambda: FakeDiffService(),+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.git_diff_status.get_session_extra_history_roots",+ lambda session_id: [f"/history/{session_id}/worktrees"],+ )+ request = AgentRequest(+ request_id="req-diff-extra-roots",+ channel_id="tui",+ session_id="sess-1",+ req_method=ReqMethod.COMMAND_DIFF,+ params={"project_dir": "/repo"},+ )++ await server.handle_command_diff_for_test(fake_ws, request, asyncio.Lock())++ assert captured["turns"] == {+ "session_id": "sess-1",+ "project_dir": "/repo",+ "kwargs": {+ "extra_history_roots": ["/history/sess-1/worktrees"],+ },+ }+ assert captured["git_diff_project_dir"] == "/repo"+ assert fake_ws.sent == [+ {+ "response_id": "req-diff-extra-roots",+ "payload": {+ "type": "list",+ "turns": [],+ },+ "ok": True,+ }+ ]++@pytest.mark.asyncioasync def test_handle_command_simplify_returns_prompt(server, fake_ws):""" /simplify 无 target 时返回包含三阶段审查结构的 prompt。"""diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex 632b6fc967..2c4edfa4f2 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -3966,6 +3966,12 @@ def test_persist_team_file_monitor_roots_replaces_stale_roots(monkeypatch: pytes"jiuwenswarm.server.runtime.agent_adapter.team_helpers.team_home",lambda name: fake_home,)+ # independent_member_workspace 内部调用 openjiuwen 的 get_openjiuwen_home(),+ # 无法被 team_home patch 覆盖,这里显式 patch 以保持测试路径稳定。+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_adapter.team_helpers.independent_member_workspace",+ lambda name: fake_home / f"{name}_workspace",+ )team_spec = SimpleNamespace(team_name="unit-team",@@ -3986,7 +3992,11 @@ def test_persist_team_file_monitor_roots_replaces_stale_roots(monkeypatch: pyteshome = fake_home.resolve()assert str(home / "team-workspace") in persisted_rootsassert str(home / "workspaces") in persisted_roots+ # session_id 经 _safe_segment sanitize(此处 "sess-1" 无特殊字符,保持原样)+ assert str(home / "sessions" / "sess-1" / "worktrees") in persisted_rootsassert str(home / "workspaces" / "worker_workspace") in persisted_roots+ # 漏洞4修复: independent_member_workspace 路径也应被收集+ assert str(home / "worker_workspace") in persisted_rootsdef test_persist_team_file_monitor_roots_noop_when_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:@@ -3997,7 +4007,10 @@ def test_persist_team_file_monitor_roots_noop_when_unchanged(monkeypatch: pytestexpected_roots = [str(fake_home.resolve() / "team-workspace"),str(fake_home.resolve() / "workspaces"),+ str(fake_home.resolve() / "sessions" / "sess-1" / "worktrees"),str(fake_home.resolve() / "workspaces" / "worker_workspace"),+ # 漏洞4修复: independent_member_workspace 路径+ str(fake_home.resolve() / "worker_workspace"),]def _fake_read_metadata(session_id: str, cache_bust: bool = False) -> dict[str, Any]:@@ -4023,6 +4036,10 @@ def test_persist_team_file_monitor_roots_noop_when_unchanged(monkeypatch: pytest"jiuwenswarm.server.runtime.agent_adapter.team_helpers.team_home",lambda name: fake_home,)+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_adapter.team_helpers.independent_member_workspace",+ lambda name: fake_home / f"{name}_workspace",+ )team_spec = SimpleNamespace(team_name="unit-team",diff --git a/tests/unit_tests/server/test_turn_diff_history.py b/tests/unit_tests/server/test_turn_diff_history.pyindex e49fea82d4..1a85fdd7c2 100644--- a/tests/unit_tests/server/test_turn_diff_history.py+++ b/tests/unit_tests/server/test_turn_diff_history.py@@ -207,6 +207,293 @@ def test_get_turn_diffs_reads_extra_history_roots(tmp_path, monkeypatch):assert turns[0]["files"][expected_path]["linesAdded"] == 1+def test_get_turn_diffs_maps_project_worktree_file_ops_to_repo_root(tmp_path, monkeypatch):+ """成员在 project/.worktrees 中写入的 file_ops 应按主项目路径统计。"""+ agent_ws = tmp_path / "agent-ws"+ user_ws = tmp_path / "user-ws"+ project_root = tmp_path / "project"+ worktree_root = project_root / ".worktrees" / "worker"+ worktree_hist = worktree_root / ".agent_history"+ worktree_hist.mkdir(parents=True)+ worktree_file = worktree_root / "src" / "feature.py"+ canonical_file = project_root / "src" / "feature.py"+ (worktree_hist / "file_ops_worker_sess-1.json").write_text(+ json.dumps(+ {+ str(worktree_file): [+ {+ "action": "write",+ "timestamp": _ts(1784542850.0),+ "old_content": "old\n",+ "new_content": "old\nnew\n",+ },+ ],+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",+ lambda: agent_ws,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",+ lambda: user_ws,+ )+ monkeypatch.setattr(+ DiffService,+ "_get_git_common_worktree_root",+ staticmethod(lambda root: project_root.resolve() if root.resolve() == worktree_root.resolve() else None),+ )+ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)++ with ph, pl, ps:+ service = DiffService()+ turns = service.get_turn_diffs("sess-1", str(project_root))++ assert len(turns) == 1+ expected_path = str(canonical_file.resolve())+ worktree_path = str(worktree_file.resolve())+ assert expected_path in turns[0]["files"]+ assert worktree_path not in turns[0]["files"]+ assert turns[0]["files"][expected_path]["linesAdded"] == 1+++def test_get_turn_diffs_keeps_nearby_distinct_member_edits(tmp_path, monkeypatch):+ """不同成员几乎同时改同一文件时,内容不同不应被去重吞掉。"""+ agent_ws = tmp_path / "agent-ws"+ user_ws = tmp_path / "user-ws"+ project_root = tmp_path / "project"+ worktrees_root = project_root / ".worktrees"+ first_root = worktrees_root / "first"+ second_root = worktrees_root / "second"+ (first_root / ".agent_history").mkdir(parents=True)+ (second_root / ".agent_history").mkdir(parents=True)+ canonical_file = project_root / "src" / "feature.py"+ first_file = first_root / "src" / "feature.py"+ second_file = second_root / "src" / "feature.py"+ entry_ts = _ts(1784542850.0)+ (first_root / ".agent_history" / "file_ops_first_sess-1.json").write_text(+ json.dumps({+ str(first_file): [{+ "action": "write",+ "timestamp": entry_ts,+ "old_content": "base\n",+ "new_content": "base\nfirst\n",+ }],+ }),+ encoding="utf-8",+ )+ (second_root / ".agent_history" / "file_ops_second_sess-1.json").write_text(+ json.dumps({+ str(second_file): [{+ "action": "write",+ "timestamp": entry_ts,+ "old_content": "base\n",+ "new_content": "base\nsecond\n",+ }],+ }),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",+ lambda: agent_ws,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",+ lambda: user_ws,+ )++ def _fake_common_root(root):+ resolved = root.resolve()+ if resolved in {first_root.resolve(), second_root.resolve()}:+ return project_root.resolve()+ return None++ monkeypatch.setattr(+ DiffService,+ "_get_git_common_worktree_root",+ staticmethod(_fake_common_root),+ )+ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)++ with ph, pl, ps:+ service = DiffService()+ turns = service.get_turn_diffs("sess-1", str(project_root))++ assert len(turns) == 1+ expected_path = str(canonical_file.resolve())+ assert list(turns[0]["files"]) == [expected_path]+ assert turns[0]["files"][expected_path]["linesAdded"] == 2+++def test_get_turn_diffs_keeps_distinct_project_and_worktree_edits(tmp_path, monkeypatch):+ """project 与 worktree 同改 canonical 文件时,低优先级来源不应整文件跳过。"""+ agent_ws = tmp_path / "agent-ws"+ user_ws = tmp_path / "user-ws"+ project_root = tmp_path / "project"+ project_hist = project_root / ".agent_history"+ worktree_root = project_root / ".worktrees" / "worker"+ worktree_hist = worktree_root / ".agent_history"+ project_hist.mkdir(parents=True)+ worktree_hist.mkdir(parents=True)+ canonical_file = project_root / "src" / "feature.py"+ worktree_file = worktree_root / "src" / "feature.py"++ (project_hist / "file_ops_project_sess-1.json").write_text(+ json.dumps({+ str(canonical_file): [{+ "action": "write",+ "timestamp": _ts(1784542850.0),+ "old_content": "base\n",+ "new_content": "base\nproject\n",+ }],+ }),+ encoding="utf-8",+ )+ (worktree_hist / "file_ops_worker_sess-1.json").write_text(+ json.dumps({+ str(worktree_file): [{+ "action": "write",+ "timestamp": _ts(1784542852.0),+ "old_content": "base\nproject\n",+ "new_content": "base\nproject\nworker\n",+ }],+ }),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",+ lambda: agent_ws,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",+ lambda: user_ws,+ )+ monkeypatch.setattr(+ DiffService,+ "_get_git_common_worktree_root",+ staticmethod(lambda root: project_root.resolve() if root.resolve() == worktree_root.resolve() else None),+ )+ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)++ with ph, pl, ps:+ service = DiffService()+ turns = service.get_turn_diffs("sess-1", str(project_root))++ expected_path = str(canonical_file.resolve())+ assert len(turns) == 1+ assert list(turns[0]["files"]) == [expected_path]+ assert turns[0]["files"][expected_path]["linesAdded"] == 2+++def test_get_turn_diffs_merges_case_variant_paths(tmp_path, monkeypatch):+ """Windows 上同一路径大小写不同也应归并为同一文件历史。"""+ agent_ws = tmp_path / "agent-ws"+ user_ws = tmp_path / "user-ws"+ project_root = tmp_path / "project"+ project_hist = project_root / ".agent_history"+ project_hist.mkdir(parents=True)+ target_file = project_root / "src" / "feature.py"+ variant_path = str(target_file).upper()++ (project_hist / "file_ops_project_sess-1.json").write_text(+ json.dumps({+ str(target_file): [{+ "action": "write",+ "timestamp": _ts(1784542850.0),+ "old_content": "base\n",+ "new_content": "base\nlower\n",+ }],+ variant_path: [{+ "action": "write",+ "timestamp": _ts(1784542852.0),+ "old_content": "base\nlower\n",+ "new_content": "base\nlower\nupper\n",+ }],+ }),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",+ lambda: agent_ws,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",+ lambda: user_ws,+ )+ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)++ with ph, pl, ps:+ service = DiffService()+ turns = service.get_turn_diffs("sess-1", str(project_root))++ assert len(turns) == 1+ assert len(turns[0]["files"]) == 1+ entry = next(iter(turns[0]["files"].values()))+ assert entry["linesAdded"] == 2+++def test_get_turn_diffs_reads_member_workspace_worktree_file_ops(tmp_path, monkeypatch):+ """显式 member workspace 下的 .worktrees 也应纳入 last_turn。"""+ agent_ws = tmp_path / "agent-ws"+ user_ws = tmp_path / "user-ws"+ project_root = tmp_path / "project"+ member_root = tmp_path / "member-workspace"+ worktree_root = member_root / ".worktrees" / "worker"+ (worktree_root / ".agent_history").mkdir(parents=True)+ worktree_file = worktree_root / "src" / "feature.py"+ canonical_file = project_root / "src" / "feature.py"+ (worktree_root / ".agent_history" / "file_ops_worker_sess-1.json").write_text(+ json.dumps({+ str(worktree_file): [{+ "action": "write",+ "timestamp": _ts(1784542850.0),+ "old_content": "old\n",+ "new_content": "old\nnew\n",+ }],+ }),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",+ lambda: agent_ws,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",+ lambda: user_ws,+ )+ monkeypatch.setattr(+ DiffService,+ "_get_git_common_worktree_root",+ staticmethod(lambda root: project_root.resolve() if root.resolve() == worktree_root.resolve() else None),+ )+ ph = patch.object(DiffService, "_read_history", return_value=_HISTORY)+ pl = patch.object(DiffService, "_load_change_sets", return_value=[])+ ps = patch.object(DiffService, "_save_change_sets", return_value=None)++ with ph, pl, ps:+ service = DiffService()+ turns = service.get_turn_diffs(+ "sess-1",+ str(project_root),+ extra_history_roots=[str(member_root)],+ )++ expected_path = str(canonical_file.resolve())+ assert len(turns) == 1+ assert expected_path in turns[0]["files"]+ assert turns[0]["files"][expected_path]["linesAdded"] == 1++def test_get_turn_diffs_does_not_scan_project_child_history_dirs(tmp_path, monkeypatch):"""普通 project_dir 不应扫描一级子目录中的 .agent_history。"""agent_ws = tmp_path / "agent-ws"@@ -485,6 +772,58 @@ def test_truncate_file_ops_reads_extra_history_roots(tmp_path, monkeypatch):assert entries[0]["new_content"] == "middle\n"+def test_truncate_file_ops_reads_worktree_history_roots(tmp_path, monkeypatch):+ """撤销本轮修改时也应截断 worktree 容器中的 session-specific file_ops。"""+ agent_ws = tmp_path / "agent-ws"+ user_ws = tmp_path / "user-ws"+ project_root = tmp_path / "project"+ worktree_root = project_root / ".worktrees" / "worker"+ worktree_hist = worktree_root / ".agent_history"+ worktree_hist.mkdir(parents=True)+ history_file = worktree_hist / "file_ops_worker_sess-1.json"+ history_file.write_text(+ json.dumps(+ {+ str(worktree_root / "src" / "feature.py"): [+ {+ "action": "write",+ "timestamp": _ts(1784542855.0),+ "old_content": "old",+ "new_content": "before",+ },+ {+ "action": "write",+ "timestamp": _ts(1784542865.0),+ "old_content": "before",+ "new_content": "after",+ },+ ],+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_agent_workspace_dir",+ lambda: agent_ws,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.utils.diff_service.get_user_workspace_dir",+ lambda: user_ws,+ )++ service = DiffService()+ service.truncate_file_ops_by_timestamp(+ "sess-1",+ 1784542860.0,+ project_dir=str(project_root),+ )++ data = json.loads(history_file.read_text(encoding="utf-8"))+ remaining = data[str(worktree_root / "src" / "feature.py")]+ assert len(remaining) == 1+ assert remaining[0]["timestamp"] == _ts(1784542855.0)++def test_turn_diff_list_returns_summaries_with_files_without_hunks():ph, pa, pl, ps = _patch_diff_service()with ph, pa, pl, ps:@@ -560,8 +899,37 @@ def test_get_session_extra_history_roots_infers_team_workspaces(tmp_path):assert str(tmp_path / ".agent_teams" / "unit-team" / "team-workspace") in rootsassert str(tmp_path / ".agent_teams" / "unit-team" / "workspaces") in roots+ assert str(tmp_path / ".agent_teams" / "unit-team" / "sessions" / "sess-1" / "worktrees") in rootsassert str(tmp_path / "team-home" / "team-workspace") in rootsassert str(tmp_path / "team-home" / "workspaces") in roots+ assert str(tmp_path / "team-home" / "sessions" / "sess-1" / "worktrees") in roots+++def test_get_session_extra_history_roots_sanitizes_manual_session_worktree(tmp_path):+ with (+ patch(+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",+ return_value={+ "team_name": "unit-team",+ "team_file_monitor_roots": [+ str(tmp_path / ".agent_teams" / "unit-team" / "team-workspace"),+ ],+ },+ ),+ patch(+ "openjiuwen.agent_teams.paths.team_home",+ return_value=tmp_path / "team-home",+ ),+ ):+ from jiuwenswarm.server.runtime.session.git_diff_status import (+ get_session_extra_history_roots,+ )++ roots = get_session_extra_history_roots("sess/1:bad")++ assert str(tmp_path / ".agent_teams" / "unit-team" / "sessions" / "sess_1_bad" / "worktrees") in roots+ assert str(tmp_path / ".agent_teams" / "unit-team" / "sessions" / "sess" / "1:bad" / "worktrees") not in roots+ assert str(tmp_path / "team-home" / "sessions" / "sess_1_bad" / "worktrees") in rootsdef test_is_valid_file_ops_file_uses_suffix_match():@@ -585,8 +953,8 @@ def test_is_valid_file_ops_file_uses_suffix_match():assert service._is_valid_file_ops_file("file_ops_agent.json", None, require_session=False)-def test_multi_history_root_first_wins_priority(tmp_path, monkeypatch):- """project_dir 的 file_ops 应优先于 extra_history_roots(first-wins)。"""+def test_multi_history_root_first_wins_for_duplicate_entries(tmp_path, monkeypatch):+ """project_dir 的 file_ops 仅在重复 entry 冲突时优先。"""agent_ws = tmp_path / "agent-ws"user_ws = tmp_path / "user-ws"project_root = tmp_path / "project"@@ -604,10 +972,10 @@ def test_multi_history_root_first_wins_priority(tmp_path, monkeypatch):"old_content": "proj-old\n", "new_content": "proj-new\n"}]}),encoding="utf-8",)- # extra_root 记录了不同的 old_content,不应覆盖 project_dir+ # extra_root 记录了同一条重复 entry,不应让统计翻倍(extra_hist / "file_ops_agent_sess-1.json").write_text(json.dumps({target_file: [{"action": "write", "timestamp": _ts(1784542850.0),- "old_content": "extra-old\n", "new_content": "extra-new\n"}]}),+ "old_content": "proj-old\n", "new_content": "proj-new\n"}]}),encoding="utf-8",)monkeypatch.setattr(@@ -626,7 +994,7 @@ def test_multi_history_root_first_wins_priority(tmp_path, monkeypatch):)assert len(turns) == 1entry = turns[0]["files"][target_file]- # project_dir 优先, old_content 应为 proj-old+ # project_dir 优先去重,重复 entry 不应被统计两次。assert entry["linesAdded"] == 1assert entry["linesRemoved"] == 1