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): code模式适配team.agent

kdgmpwda53a9211dba
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.py
index 6fad373ac1..140643c689 100644
--- a/jiuwenswarm/agents/harness/common/session_ops_service.py
+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py
@@ -536,6 +536,7 @@ def restore_session_files(
session_id: str,
turn_index: int,
project_dir: str | None = None,
+ extra_history_roots: list[str] | None = None,
) -> dict[str, Any]:
"""恢复指定 turn 之后所有被修改的文件到目标 turn 开始前的状态.
@@ -560,7 +561,10 @@ def restore_session_files(
diff_service = get_diff_service()
files_to_restore = diff_service.get_files_to_restore(
- session_id, turn_index, project_dir=project_dir,
+ session_id,
+ turn_index,
+ project_dir=project_dir,
+ extra_history_roots=extra_history_roots,
)
if not files_to_restore:
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index ddce50d3d3..0e2c07de13 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -544,6 +544,24 @@ function buildPersistedMediaFiles(mediaItems: MediaItem[]): Record<string, unkno
};
}
+function getSessionWorkContext(sessionId: string): Record<string, unknown> {
+ const sessionStore = useSessionStore.getState();
+ const workspaceStore = useWorkspaceStore.getState();
+ const session =
+ sessionStore.currentSession?.session_id === sessionId
+ ? sessionStore.currentSession
+ : sessionStore.sessions.find((item) => item.session_id === sessionId);
+ const selectedProject = workspaceStore.selectedProject;
+ const projectId = session?.project_id || selectedProject?.project_id || '';
+ const projectDir = session?.project_dir || selectedProject?.project_dir || '';
+ const workMode = session?.work_mode || selectedProject?.work_mode || workspaceStore.workMode;
+ return {
+ ...(projectId ? { project_id: projectId } : {}),
+ ...(projectDir ? { project_dir: projectDir } : {}),
+ ...(workMode ? { work_mode: workMode } : {}),
+ };
+}
+
interface ContextCompressionStatePayload extends Record<string, unknown> {
status?: string;
summary?: string;
@@ -1227,11 +1245,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
// 正常调用接口
const selectedModel = useSessionStore.getState().getRuntime(sessionId)?.selectedModelName;
- const currentSessionState = useSessionStore.getState();
- const currentSession = currentSessionState.currentSession?.session_id === sessionId
- ? currentSessionState.currentSession
- : currentSessionState.sessions.find((s) => s.session_id === sessionId);
- const projectDir = currentSession?.project_dir || undefined;
+ const workContext = getSessionWorkContext(sessionId);
if (currentMode === 'auto_harness') {
useHarnessStore.getState().reset(sessionId);
}
@@ -1266,7 +1280,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
...(outgoingFiles ? { files: outgoingFiles } : {}),
mode: currentMode,
...(selectedModel ? { model_name: selectedModel } : {}),
- ...(projectDir ? { project_dir: projectDir } : {}),
+ ...workContext,
skills: selectedSkills,
...(inputMode ? { input_mode: inputMode } : {}),
});
@@ -1307,10 +1321,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
useChatStore.getState().setThinking(sessionId, true);
const currentSessionState = useSessionStore.getState();
- const currentSession = currentSessionState.currentSession?.session_id === sessionId
- ? currentSessionState.currentSession
- : currentSessionState.sessions.find((s) => s.session_id === sessionId);
- const projectDir = currentSession?.project_dir || undefined;
+ const workContext = getSessionWorkContext(sessionId);
const currentMode = currentSessionState.getRuntime(sessionId)?.mode;
const selectedModel = currentSessionState.getRuntime(sessionId)?.selectedModelName;
if (currentMode === 'auto_harness') {
@@ -1325,7 +1336,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
content,
mode: currentMode,
...(selectedModel ? { model_name: selectedModel } : {}),
- ...(projectDir ? { project_dir: projectDir } : {}),
+ ...workContext,
});
} catch (error) {
const webError = error as WebError;
@@ -1397,6 +1408,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const params: Record<string, unknown> = {
session_id: sessionId,
intent,
+ ...getSessionWorkContext(sessionId),
};
const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;
if (['pause', 'resume', 'cancel', 'supplement'].includes(intent)) {
@@ -1563,6 +1575,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
session_id: sessionId,
query: '',
mode: resolvedResumeMode,
+ ...getSessionWorkContext(sessionId),
request_id: requestId,
answers: answers,
...sourcePayload,
@@ -1580,6 +1593,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
session_id: sessionId,
content: '',
mode: 'auto_harness',
+ ...getSessionWorkContext(sessionId),
activate_response: {
interaction_id: interactionId,
action,
@@ -1591,6 +1605,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
// 否则发送 chat.user_answer(自进化确认)
await request('chat.user_answer', {
session_id: sessionId,
+ ...getSessionWorkContext(sessionId),
request_id: requestId,
answers,
...sourcePayload,
@@ -1615,6 +1630,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
session_id: sessionId,
content: '',
mode: 'auto_harness',
+ ...getSessionWorkContext(sessionId),
activate_response: {
interaction_id: interactionId,
action,
diff --git a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py
index 0bfc67619a..126afa3e70 100644
--- a/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py
+++ b/jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py
@@ -572,11 +572,16 @@ class GitDiffWebSocketHandler:
from jiuwenswarm.agents.harness.common.session_ops_service import (
restore_session_files,
)
+ from jiuwenswarm.server.runtime.session.git_diff_status import (
+ 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,
)
# 清理本轮的 file_ops 日志,使 git 监控的 last_turn diff 与实际工作区一致。
@@ -597,11 +602,13 @@ class GitDiffWebSocketHandler:
diff_service.mark_turn_discarded,
session_id, turn_index,
project_dir=proj.project_dir,
+ extra_history_roots=extra_history_roots,
)
await asyncio.to_thread(
diff_service.truncate_file_ops_by_timestamp,
session_id, cut_timestamp,
project_dir=proj.project_dir,
+ extra_history_roots=extra_history_roots,
)
file_ops_truncated = True
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 8a2e4dfa7f..b28003ea79 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -1235,6 +1235,66 @@ 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]:
+ """Return team/member workspace roots where file-op history may be written."""
+ roots: list[str] = []
+
+ def add_root(value: Any) -> None:
+ raw = str(value or "").strip()
+ if not raw:
+ return
+ try:
+ root = str(Path(raw).expanduser().resolve())
+ except Exception:
+ root = raw
+ if root not in roots:
+ roots.append(root)
+
+ workspace = getattr(team_spec, "workspace", None)
+ root_path = str(getattr(workspace, "root_path", "") or "").strip()
+ team_name = str(getattr(team_spec, "team_name", "") or "").strip()
+ home = team_home(team_name)
+ add_root(root_path or str(home / "team-workspace"))
+ add_root(home / "workspaces")
+
+ agents = getattr(team_spec, "agents", None)
+ if isinstance(agents, dict):
+ for member_name, member_spec in agents.items():
+ member_workspace = getattr(member_spec, "workspace", None)
+ add_root(getattr(member_workspace, "root_path", None))
+ add_root(home / "workspaces" / f"{member_name}_workspace")
+
+ return roots
+
+
+def _persist_team_file_monitor_roots(session_id: str, team_spec: Any) -> None:
+ roots = _team_spec_monitor_roots(team_spec)
+ if not roots:
+ return
+ try:
+ from jiuwenswarm.server.runtime.session.session_metadata import (
+ _enqueue_write,
+ _read_metadata,
+ )
+
+ metadata = _read_metadata(session_id, cache_bust=True)
+ if not metadata:
+ return
+ existing = metadata.get("team_file_monitor_roots")
+ # 直接替换而非合并: team_spec 是当前 team 组成的权威来源,
+ # 合并旧 root 会导致已移除成员的 workspace 路径累积无法清理。
+ if roots == existing:
+ return
+ metadata["team_file_monitor_roots"] = roots
+ _enqueue_write(session_id, metadata, preserve_pin_fields=True)
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "[TeamHelpers] failed to persist team file monitor roots: session=%s error=%s",
+ session_id,
+ exc,
+ )
+
+
async def _start_team_stream_round(
*,
channel_id: str | None,
@@ -1393,6 +1453,7 @@ async def process_team_message_stream(
request_metadata=request_metadata,
requested_model_name=requested_model_name,
)
+ _persist_team_file_monitor_roots(session_id, team_spec)
except Exception as exc:
logger.exception("[TeamHelpers] TeamAgent create failed: %s", exc)
yield AgentResponseChunk(
diff --git a/jiuwenswarm/server/runtime/session/git_diff_status.py b/jiuwenswarm/server/runtime/session/git_diff_status.py
index edbd1dcf47..2c47445f73 100644
--- a/jiuwenswarm/server/runtime/session/git_diff_status.py
+++ b/jiuwenswarm/server/runtime/session/git_diff_status.py
@@ -240,6 +240,81 @@ def _convert_stats(raw_stats: dict[str, Any] | None) -> DiffStats:
)
+def get_session_extra_history_roots(session_id: str | None) -> list[str]:
+ """Return team/member/worktree roots recorded for file history monitoring."""
+ sid = str(session_id or "").strip()
+ if not sid:
+ return []
+ try:
+ from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata
+
+ # Team roots may be written by a different process; force disk read so
+ # diff/restore sees the latest persisted metadata.
+ metadata = get_session_metadata(sid, cache_bust=True, enable_writeback=False)
+ except Exception: # noqa: BLE001
+ return []
+ raw_roots = metadata.get("team_file_monitor_roots")
+ roots: list[str] = []
+ seen: set[str] = set()
+
+ def add_root(raw: Any) -> None:
+ if not isinstance(raw, str) or not raw.strip():
+ return
+ root = raw.strip()
+ try:
+ key = str(Path(root).expanduser().resolve())
+ except Exception:
+ key = root
+ if key in seen:
+ return
+ seen.add(key)
+ roots.append(root)
+
+ raw_root_values = raw_roots if isinstance(raw_roots, list) else []
+ if isinstance(raw_roots, list):
+ for raw in raw_roots:
+ add_root(raw)
+ if not isinstance(raw, str) or not raw.strip():
+ continue
+ try:
+ raw_path = Path(raw.strip()).expanduser()
+ if raw_path.name == "team-workspace":
+ add_root(str(raw_path.parent / "workspaces"))
+ except Exception: # noqa: BLE001
+ continue
+
+ team_name = str(metadata.get("team_name") or "").strip()
+ if team_name:
+ for raw in raw_root_values:
+ if not isinstance(raw, str) or team_name not in raw:
+ continue
+ try:
+ path = Path(raw.strip()).expanduser()
+ parts = path.parts
+ # 使用最后一次出现的位置,避免路径中 team_name 多次出现时
+ # 定位到错误的层级(深层路径更可能是实际 team 目录)。
+ idx = -1
+ for i in range(len(parts) - 1, -1, -1):
+ if parts[i] == team_name:
+ idx = i
+ break
+ if idx >= 0:
+ home = Path(*parts[: idx + 1])
+ add_root(str(home / "team-workspace"))
+ add_root(str(home / "workspaces"))
+ except Exception: # noqa: BLE001
+ continue
+ try:
+ from openjiuwen.agent_teams.paths import team_home
+
+ home = team_home(team_name)
+ add_root(str(home / "team-workspace"))
+ add_root(str(home / "workspaces"))
+ except Exception: # noqa: BLE001
+ pass
+ return roots
+
+
def _convert_hunks(raw_hunks: list[dict[str, Any]] | None) -> list[DiffHunk]:
"""转换 camelCase hunk 列表 → snake_case DiffHunk 列表。"""
if not raw_hunks or not isinstance(raw_hunks, list):
@@ -570,6 +645,7 @@ class DiffStatusService:
last_turn: DiffTurnSummary | None = None
if session_id:
diff_service = get_diff_service()
+ extra_history_roots = get_session_extra_history_roots(session_id)
try:
turns = diff_service.get_turn_diffs(
session_id,
@@ -579,6 +655,7 @@ class DiffStatusService:
"branch": repo_info.branch,
"base_head": repo_info.head,
},
+ extra_history_roots=extra_history_roots,
)
except Exception as exc: # noqa: BLE001
# 与 get_git_diff 保持对称:错误向上抛,让 handler 感知并触发
@@ -620,8 +697,12 @@ class DiffStatusService:
project_dir = getattr(project, "project_dir", "")
repo_context = _repo_context_from_status(project, reject_transient=True)
diff_service = get_diff_service()
+ extra_history_roots = get_session_extra_history_roots(session_id)
turns = diff_service.get_turn_diff_summaries(
- session_id, project_dir, repo_context=repo_context,
+ session_id,
+ project_dir,
+ repo_context=repo_context,
+ extra_history_roots=extra_history_roots,
)
total = len(turns)
cursor = max(0, int(cursor or 0))
@@ -664,12 +745,14 @@ class DiffStatusService:
repo_root = repo_context.get("repo_root")
diff_service = get_diff_service()
+ extra_history_roots = get_session_extra_history_roots(session_id)
turn = diff_service.get_turn_diff(
session_id,
turn_index=turn_index,
change_set_id=change_set_id,
project_dir=project_dir,
repo_context=repo_context,
+ extra_history_roots=extra_history_roots,
)
if turn is None:
return None
diff --git a/jiuwenswarm/server/utils/diff_service.py b/jiuwenswarm/server/utils/diff_service.py
index 5693ee3587..440649a291 100644
--- a/jiuwenswarm/server/utils/diff_service.py
+++ b/jiuwenswarm/server/utils/diff_service.py
@@ -45,6 +45,7 @@ class DiffService:
session_id: str,
project_dir: str | None = None,
repo_context: dict[str, Any] | None = None,
+ extra_history_roots: list[str] | None = None,
) -> list[dict[str, Any]]:
"""获取 session 的所有 turn diff(完整信息).
@@ -55,7 +56,7 @@ class DiffService:
Returns:
turn diff 列表,按时间倒序排列(most recent first)
"""
- turns = self._compute_turn_diffs(session_id, project_dir)
+ turns = self._compute_turn_diffs(session_id, project_dir, extra_history_roots=extra_history_roots)
self._enrich_with_change_sets(session_id, turns, repo_context=repo_context)
return list(reversed(turns))
@@ -64,6 +65,7 @@ class DiffService:
session_id: str,
project_dir: str | None = None,
repo_context: dict[str, Any] | None = None,
+ extra_history_roots: list[str] | None = None,
) -> list[dict[str, Any]]:
"""获取 session 的历史 turn diff 摘要,包含已持久化快照。
@@ -71,7 +73,7 @@ class DiffService:
但仍存在于 change_sets/snapshot 中的历史轮次也返回出来(例如已撤销
的 turn)。
"""
- turns = self._compute_turn_diffs(session_id, project_dir)
+ turns = self._compute_turn_diffs(session_id, project_dir, extra_history_roots=extra_history_roots)
self._enrich_with_change_sets(session_id, turns, repo_context=repo_context)
by_turn = {int(t.get("turnIndex", 0) or 0): t for t in turns}
for entry in self._load_change_sets(session_id):
@@ -99,6 +101,7 @@ class DiffService:
change_set_id: str | None = None,
project_dir: str | None = None,
repo_context: dict[str, Any] | None = None,
+ extra_history_roots: list[str] | None = None,
) -> dict[str, Any] | None:
"""获取指定轮次的 turn diff。
@@ -132,14 +135,24 @@ class DiffService:
snapshot = self._load_turn_snapshot(session_id, change_set_id)
if snapshot is not None:
return snapshot
- turns = self.get_turn_diffs(session_id, project_dir, repo_context=repo_context)
+ turns = self.get_turn_diffs(
+ session_id,
+ project_dir,
+ repo_context=repo_context,
+ extra_history_roots=extra_history_roots,
+ )
for turn in turns:
if turn.get("change_set_id") == change_set_id:
return turn
raise DiffHistoryExpiredError(
f"diff history expired for change_set_id={change_set_id}"
)
- turns = self.get_turn_diffs(session_id, project_dir, repo_context=repo_context)
+ turns = self.get_turn_diffs(
+ session_id,
+ project_dir,
+ repo_context=repo_context,
+ extra_history_roots=extra_history_roots,
+ )
for turn in turns:
if int(turn.get("turnIndex", 0) or 0) == turn_index:
return turn
@@ -156,14 +169,24 @@ class DiffService:
)
return None
- def _compute_turn_diffs(self, session_id: str, project_dir: str | None = None) -> list[dict[str, Any]]:
+ def _compute_turn_diffs(
+ self,
+ session_id: str,
+ project_dir: str | None = None,
+ *,
+ extra_history_roots: list[str] | None = None,
+ ) -> list[dict[str, Any]]:
"""计算 turn-based diffs."""
history = self._read_history(session_id)
if not history:
return []
- agent_history = self._read_agent_history(session_id, project_dir)
+ agent_history = self._read_agent_history(
+ session_id,
+ project_dir,
+ extra_history_roots=extra_history_roots,
+ )
turns: list[dict[str, Any]] = []
@@ -416,13 +439,19 @@ class DiffService:
}
def mark_turn_discarded(
- self, session_id: str, turn_index: int, project_dir: str | None = None
+ self,
+ session_id: str,
+ turn_index: int,
+ project_dir: str | None = None,
+ *,
+ extra_history_roots: list[str] | None = None,
) -> str | None:
"""将指定 turn 的 change_set 状态标记为 discarded。"""
if turn_index <= 0:
return None
target = self.get_turn_diff(
session_id, turn_index=turn_index, project_dir=project_dir,
+ extra_history_roots=extra_history_roots,
)
change_set_id = str((target or {}).get("change_set_id") or "")
if not change_set_id:
@@ -569,24 +598,79 @@ class DiffService:
logger.debug("Failed to read metadata file %s: %s", metadata_file, e)
return None
+ @staticmethod
def _is_valid_file_ops_file(
- self, name: str, session_id: str | None, require_session: bool = False
+ name: str, session_id: str | None, require_session: bool = False
) -> bool:
- """检查文件名是否是有效的 file_ops 文件."""
- if not name.startswith(f"file_ops_{self._agent_id}_"):
+ """检查文件名是否是有效的 file_ops 文件.
+
+ 文件名约定: ``file_ops_{agent_id}_{session_id}.json``,其中 session_id
+ 始终是 ``.json`` 前的最后一段。使用 ``_{session_id}.json`` 后缀匹配替代
+ 子串匹配,避免短 session_id 误匹配其他 agent 的 file_ops 文件。
+ """
+ if not name.startswith("file_ops_"):
return False
if not name.endswith(".json"):
return False
- if require_session:
- return session_id is not None and session_id in name
- return session_id is None or session_id in name
+ if not session_id:
+ return not require_session
+ return name.endswith(f"_{session_id}.json")
+
+ @staticmethod
+ def _agent_history_dirs_for_roots(
+ history_roots: list[str],
+ *,
+ include_child_workspaces: bool = False,
+ ) -> list[Path]:
+ """Return .agent_history dirs for roots and optional immediate workspaces."""
+ result: list[Path] = []
+ seen_history_dirs: set[Path] = set()
+
+ def add_history_dir(hist_dir: Path) -> None:
+ try:
+ key = hist_dir.resolve()
+ except Exception:
+ key = hist_dir
+ if key in seen_history_dirs:
+ return
+ seen_history_dirs.add(key)
+ result.append(hist_dir)
+
+ for history_root in history_roots:
+ root = Path(history_root)
+ add_history_dir(root / ".agent_history")
+ if not include_child_workspaces:
+ continue
+ if not root.is_dir():
+ continue
+ try:
+ children = list(root.iterdir())
+ except OSError:
+ continue
+ for child in children:
+ if child.is_dir():
+ add_history_dir(child / ".agent_history")
+ return result
+
+ @staticmethod
+ def _is_internal_team_workspace_file(file_path: str) -> bool:
+ """Return whether an edited file is an internal team workspace artifact."""
+ parts = str(file_path or "").replace("\\", "/").lower().split("/")
+ return ".agent_teams" in parts
- def _read_agent_history(self, session_id: str | None = None, project_dir: str | None = None) -> dict[str, Any]:
+ def _read_agent_history(
+ self,
+ session_id: str | None = None,
+ project_dir: str | None = None,
+ *,
+ extra_history_roots: list[str] | None = None,
+ ) -> dict[str, Any]:
"""读取 .agent_history(同时读取全局与 session-specific 文件并合并).
Args:
session_id: 若提供,额外扫描匹配该 session 的 file_ops 文件。
project_dir: 项目目录路径,若提供则也从项目目录读取 .agent_history。
+ extra_history_roots: 额外写入根目录,例如 team/member workspace。
"""
result: dict[str, Any] = {}
@@ -613,6 +697,26 @@ class DiffService:
project_dir = self._get_project_dir_from_metadata(session_id)
if project_dir:
project_hist_dir = Path(project_dir) / ".agent_history"
+ if project_hist_dir.is_dir():
+ for f in project_hist_dir.iterdir():
+ name = f.name
+ if self._is_valid_file_ops_file(name, session_id):
+ paths.append(f)
+ 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()
+ )
+
+ for project_hist_dir in self._agent_history_dirs_for_roots(
+ extra_roots,
+ include_child_workspaces=True,
+ ):
if project_hist_dir.is_dir():
# 读取 session-specific file_ops 文件
for f in project_hist_dir.iterdir():
@@ -638,6 +742,8 @@ class DiffService:
try:
data = json.loads(history_file.read_text(encoding="utf-8"))
for file_path, entries in data.items():
+ if self._is_internal_team_workspace_file(file_path):
+ continue
# 规范化路径,避免大小写差异导致的重复
normalized_path = normalize_path(file_path)
if normalized_path not in result:
@@ -1519,7 +1625,12 @@ class DiffService:
)
def get_files_to_restore(
- self, session_id: str, turn_index: int, project_dir: str | None = None
+ self,
+ session_id: str,
+ turn_index: int,
+ project_dir: str | None = None,
+ *,
+ extra_history_roots: list[str] | None = None,
) -> dict[str, dict[str, Any]]:
"""返回需要恢复的文件及其目标内容.
@@ -1554,7 +1665,11 @@ class DiffService:
return {}
# 2. 读取 file_ops 日志
- agent_history = self._read_agent_history(session_id, project_dir)
+ agent_history = self._read_agent_history(
+ session_id,
+ project_dir,
+ extra_history_roots=extra_history_roots,
+ )
# 3. 对于每个文件,找到第一条 timestamp >= target_timestamp 的 entry
# 该 entry 的 old_content 即为目标 turn 开始前的文件状态
@@ -1585,6 +1700,8 @@ class DiffService:
session_id: str,
cutoff_ts: float,
project_dir: str | None = None,
+ *,
+ extra_history_roots: list[str] | None = None,
) -> None:
"""截断 file_ops 日志,移除 timestamp >= cutoff_ts 的条目.
@@ -1621,7 +1738,7 @@ class DiffService:
if self._is_valid_file_ops_file(f.name, session_id, require_session=True):
file_ops_paths.append(f)
- # 也从项目目录扫描(显式传入优先,否则从 metadata 推断)
+ # 也从项目目录/额外写入根扫描(显式传入优先,否则从 metadata 推断)
resolved_project_dir = project_dir or self._get_project_dir_from_metadata(session_id)
if resolved_project_dir:
project_hist_dir = Path(resolved_project_dir) / ".agent_history"
@@ -1630,6 +1747,23 @@ 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()
+ )
+
+ for project_hist_dir in self._agent_history_dirs_for_roots(
+ extra_roots,
+ include_child_workspaces=True,
+ ):
+ if project_hist_dir.is_dir():
+ for f in project_hist_dir.iterdir():
+ if self._is_valid_file_ops_file(f.name, session_id, require_session=True):
+ if f not in file_ops_paths:
+ file_ops_paths.append(f)
for file_ops_path in file_ops_paths:
try:
diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.py
index 3de4c31c3c..d9abced21a 100644
--- a/tests/unit_tests/agentserver/test_team_helpers.py
+++ b/tests/unit_tests/agentserver/test_team_helpers.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import asyncio
import json
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -3919,3 +3920,103 @@ def test_workflow_updated_to_team_events_first_sight_terminal_spawns_then_status
assert member_types == ["team.member.spawned", "team.member.status_changed"]
task = next(e for e in out if e["event_type"] == "team.task")
assert task["event"]["type"] == "team.task.cancelled"
+
+
+def test_persist_team_file_monitor_roots_replaces_stale_roots(monkeypatch: pytest.MonkeyPatch) -> None:
+ """_persist_team_file_monitor_roots 应替换旧 root,而非累积合并。"""
+ written: list[dict[str, Any]] = []
+
+ def _fake_read_metadata(session_id: str, cache_bust: bool = False) -> dict[str, Any]:
+ return {
+ "session_id": session_id,
+ "team_file_monitor_roots": ["/old/stale/workspace"],
+ }
+
+ def _fake_enqueue_write(
+ session_id: str, metadata: dict[str, Any], **kwargs: Any
+ ) -> None:
+ written.append(metadata)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_metadata._read_metadata",
+ _fake_read_metadata,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_metadata._enqueue_write",
+ _fake_enqueue_write,
+ )
+ fake_home = Path("/team/home/unit-team")
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.team_helpers.team_home",
+ lambda name: fake_home,
+ )
+
+ team_spec = SimpleNamespace(
+ team_name="unit-team",
+ workspace=SimpleNamespace(root_path="/team/home/unit-team/team-workspace"),
+ agents={
+ "worker": SimpleNamespace(
+ workspace=SimpleNamespace(root_path="/team/home/unit-team/workspaces/worker_workspace"),
+ ),
+ },
+ )
+ team_helpers._persist_team_file_monitor_roots("sess-1", team_spec)
+
+ assert len(written) == 1
+ persisted_roots = written[0]["team_file_monitor_roots"]
+ # 旧 root 应被清除
+ assert "/old/stale/workspace" not in persisted_roots
+ # 新 root 应包含 team-workspace 和 member workspace(路径经 resolve 归一化)
+ home = fake_home.resolve()
+ assert str(home / "team-workspace") in persisted_roots
+ assert str(home / "workspaces") in persisted_roots
+ assert str(home / "workspaces" / "worker_workspace") in persisted_roots
+
+
+def test_persist_team_file_monitor_roots_noop_when_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:
+ """当 roots 未变化时不应触发写盘。"""
+ written: list[dict[str, Any]] = []
+ fake_home = Path("/team/home/unit-team")
+
+ expected_roots = [
+ str(fake_home.resolve() / "team-workspace"),
+ str(fake_home.resolve() / "workspaces"),
+ str(fake_home.resolve() / "workspaces" / "worker_workspace"),
+ ]
+
+ def _fake_read_metadata(session_id: str, cache_bust: bool = False) -> dict[str, Any]:
+ return {
+ "session_id": session_id,
+ "team_file_monitor_roots": list(expected_roots),
+ }
+
+ def _fake_enqueue_write(
+ session_id: str, metadata: dict[str, Any], **kwargs: Any
+ ) -> None:
+ written.append(metadata)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_metadata._read_metadata",
+ _fake_read_metadata,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_metadata._enqueue_write",
+ _fake_enqueue_write,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.team_helpers.team_home",
+ lambda name: fake_home,
+ )
+
+ team_spec = SimpleNamespace(
+ team_name="unit-team",
+ workspace=SimpleNamespace(root_path="/team/home/unit-team/team-workspace"),
+ agents={
+ "worker": SimpleNamespace(
+ workspace=SimpleNamespace(root_path="/team/home/unit-team/workspaces/worker_workspace"),
+ ),
+ },
+ )
+ team_helpers._persist_team_file_monitor_roots("sess-1", team_spec)
+
+ assert len(written) == 0
diff --git a/tests/unit_tests/server/test_turn_diff_history.py b/tests/unit_tests/server/test_turn_diff_history.py
index f1dd3e3667..e49fea82d4 100644
--- a/tests/unit_tests/server/test_turn_diff_history.py
+++ b/tests/unit_tests/server/test_turn_diff_history.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import json
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import patch
@@ -144,6 +145,130 @@ def test_get_turn_diff_finds_second_turn():
assert turn["request_id"] == "req-002"
+def test_get_turn_diffs_reads_extra_history_roots(tmp_path, monkeypatch):
+ """Team 模式的成员 workspace file_ops 也应纳入 last_turn diff。"""
+ agent_ws = tmp_path / "agent-ws"
+ user_ws = tmp_path / "user-ws"
+ project_root = tmp_path / "project"
+ workspaces_root = tmp_path / "team-home" / "workspaces"
+ team_root = workspaces_root / "worker_workspace"
+ team_hist = team_root / ".agent_history"
+ team_hist.mkdir(parents=True)
+ target_file = project_root / "team_file.py"
+ internal_file = tmp_path / ".agent_teams" / "unit-team" / "workspaces" / "worker_workspace" / "notes.md"
+ (team_hist / "file_ops_jiuwen_team_unit_worker_sess-1.json").write_text(
+ json.dumps(
+ {
+ str(target_file): [
+ {
+ "action": "write",
+ "timestamp": _ts(1784542850.0),
+ "old_content": "old\n",
+ "new_content": "old\nnew\n",
+ },
+ ],
+ str(internal_file): [
+ {
+ "action": "write",
+ "timestamp": _ts(1784542850.0),
+ "old_content": "",
+ "new_content": "internal scratch\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),
+ extra_history_roots=[str(workspaces_root)],
+ )
+
+ assert len(turns) == 1
+ expected_path = str(target_file.resolve())
+ internal_path = str(internal_file.resolve())
+ assert expected_path in turns[0]["files"]
+ assert internal_path not 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"
+ user_ws = tmp_path / "user-ws"
+ project_root = tmp_path / "project"
+ project_hist = project_root / ".agent_history"
+ nested_hist = project_root / "nested" / ".agent_history"
+ project_hist.mkdir(parents=True)
+ nested_hist.mkdir(parents=True)
+ project_file = project_root / "kept.py"
+ nested_file = project_root / "nested" / "leaked.py"
+ (project_hist / "file_ops_agent_sess-1.json").write_text(
+ json.dumps(
+ {
+ str(project_file): [
+ {
+ "action": "write",
+ "timestamp": _ts(1784542850.0),
+ "old_content": "old\n",
+ "new_content": "old\nnew\n",
+ },
+ ],
+ }
+ ),
+ encoding="utf-8",
+ )
+ (nested_hist / "file_ops_agent_sess-1.json").write_text(
+ json.dumps(
+ {
+ str(nested_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,
+ )
+ 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 str(project_file.resolve()) in turns[0]["files"]
+ assert str(nested_file.resolve()) not in turns[0]["files"]
+
+
def test_get_turn_diff_by_change_set_id():
ph, pa, pl, ps = _patch_diff_service_with_persistence()
with ph, pa, pl, ps:
@@ -307,6 +432,59 @@ def test_mark_turn_discarded_preserves_snapshot():
assert "/proj/file_a.py" in turn["files"]
+def test_truncate_file_ops_reads_extra_history_roots(tmp_path, monkeypatch):
+ """撤销本轮修改时也应截断 team 额外目录中的 session-specific file_ops。"""
+ agent_ws = tmp_path / "agent-ws"
+ user_ws = tmp_path / "user-ws"
+ workspaces_root = tmp_path / "team-home" / "workspaces"
+ team_root = workspaces_root / "worker_workspace"
+ team_hist = team_root / ".agent_history"
+ team_hist.mkdir(parents=True)
+ history_file = team_hist / "file_ops_jiuwen_team_unit_worker_sess-1.json"
+ history_file.write_text(
+ json.dumps(
+ {
+ str(team_root / "team_file.py"): [
+ {
+ "action": "write",
+ "timestamp": _ts(1784542840.0),
+ "old_content": "before\n",
+ "new_content": "middle\n",
+ },
+ {
+ "action": "write",
+ "timestamp": _ts(1784542850.0),
+ "old_content": "middle\n",
+ "new_content": "after\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,
+ )
+
+ service = DiffService()
+ service.truncate_file_ops_by_timestamp(
+ "sess-1",
+ 1784542850.0,
+ project_dir="/proj",
+ extra_history_roots=[str(workspaces_root)],
+ )
+
+ data = json.loads(history_file.read_text(encoding="utf-8"))
+ entries = next(iter(data.values()))
+ assert len(entries) == 1
+ assert entries[0]["new_content"] == "middle\n"
+
+
def test_turn_diff_list_returns_summaries_with_files_without_hunks():
ph, pa, pl, ps = _patch_diff_service()
with ph, pa, pl, ps:
@@ -358,6 +536,101 @@ def test_turn_diff_list_includes_change_set_metadata():
assert result["turns"][1]["assistant_message_id"] == "req-001:assistant"
+def test_get_session_extra_history_roots_infers_team_workspaces(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")
+
+ assert str(tmp_path / ".agent_teams" / "unit-team" / "team-workspace") in roots
+ assert str(tmp_path / ".agent_teams" / "unit-team" / "workspaces") in roots
+ assert str(tmp_path / "team-home" / "team-workspace") in roots
+ assert str(tmp_path / "team-home" / "workspaces") in roots
+
+
+def test_is_valid_file_ops_file_uses_suffix_match():
+ """session_id 后缀匹配,避免子串误匹配其他 session 的 file_ops 文件。"""
+ service = DiffService()
+ # 正确匹配: session_id 是 .json 前的最后一段
+ assert service._is_valid_file_ops_file("file_ops_agent_sess-1.json", "sess-1")
+ assert service._is_valid_file_ops_file("file_ops_agent_sess-1.json", "sess-1", require_session=True)
+ # 前缀不同的 session 不应匹配(sess-1 不应匹配 sess-10)
+ assert not service._is_valid_file_ops_file("file_ops_agent_sess-10.json", "sess-1")
+ # session_id 不在末尾段时不应匹配
+ assert not service._is_valid_file_ops_file("file_ops_sess-1_agent.json", "sess-1")
+ # 非 file_ops 前缀
+ assert not service._is_valid_file_ops_file("other_ops_agent_sess-1.json", "sess-1")
+ # 非 .json 后缀
+ assert not service._is_valid_file_ops_file("file_ops_agent_sess-1.txt", "sess-1")
+ # require_session=True 但 session_id=None
+ assert not service._is_valid_file_ops_file("file_ops_agent.json", None, require_session=True)
+ # require_session=False 且 session_id=None: 接受所有 file_ops 文件
+ assert service._is_valid_file_ops_file("file_ops_agent.json", None)
+ 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)。"""
+ agent_ws = tmp_path / "agent-ws"
+ user_ws = tmp_path / "user-ws"
+ project_root = tmp_path / "project"
+ extra_root = tmp_path / "extra"
+
+ proj_hist = project_root / ".agent_history"
+ extra_hist = extra_root / ".agent_history"
+ proj_hist.mkdir(parents=True)
+ extra_hist.mkdir(parents=True)
+
+ target_file = str(project_root / "shared.py")
+ # project_dir 记录的 old_content 优先
+ (proj_hist / "file_ops_agent_sess-1.json").write_text(
+ json.dumps({target_file: [{"action": "write", "timestamp": _ts(1784542850.0),
+ "old_content": "proj-old\n", "new_content": "proj-new\n"}]}),
+ encoding="utf-8",
+ )
+ # extra_root 记录了不同的 old_content,不应覆盖 project_dir
+ (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"}]}),
+ 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),
+ extra_history_roots=[str(extra_root)],
+ )
+ assert len(turns) == 1
+ entry = turns[0]["files"][target_file]
+ # project_dir 优先, old_content 应为 proj-old
+ assert entry["linesAdded"] == 1
+ assert entry["linesRemoved"] == 1
+
+
def test_turn_diff_list_respects_limit():
ph, pa, pl, ps = _patch_diff_service()
with ph, pa, pl, ps:
diff --git a/tests/unit_tests/test_discard_turn_changes.py b/tests/unit_tests/test_discard_turn_changes.py
index 31cbeca791..d58719e8fb 100644
--- a/tests/unit_tests/test_discard_turn_changes.py
+++ b/tests/unit_tests/test_discard_turn_changes.py
@@ -162,28 +162,31 @@ async def test_successful_discard_restores_files_and_marks_dirty():
truncate_calls: list[dict] = []
restore_calls: list[dict] = []
- def fake_truncate(session_id, cutoff_ts, project_dir=None):
+ def fake_truncate(session_id, cutoff_ts, project_dir=None, *, extra_history_roots=None):
truncate_calls.append({
"session_id": session_id,
"cutoff_ts": cutoff_ts,
"project_dir": project_dir,
+ "extra_history_roots": extra_history_roots,
})
mark_discarded_calls: list[dict] = []
- def fake_mark_discarded(session_id, turn_index, project_dir=None):
+ def fake_mark_discarded(session_id, turn_index, project_dir=None, *, extra_history_roots=None):
mark_discarded_calls.append({
"session_id": session_id,
"turn_index": turn_index,
"project_dir": project_dir,
+ "extra_history_roots": extra_history_roots,
})
return "cs_sess-1_2_test1234"
- def fake_restore(*, session_id, turn_index, project_dir=None):
+ def fake_restore(*, session_id, turn_index, project_dir=None, extra_history_roots=None):
restore_calls.append({
"session_id": session_id,
"turn_index": turn_index,
"project_dir": project_dir,
+ "extra_history_roots": extra_history_roots,
})
return fake_restore_result
@@ -219,6 +222,10 @@ async def test_successful_discard_restores_files_and_marks_dirty():
"jiuwenswarm.agents.harness.common.session_ops_service.restore_session_files",
side_effect=fake_restore,
),
+ patch(
+ "jiuwenswarm.server.runtime.session.git_diff_status.get_session_extra_history_roots",
+ return_value=["/tmp/team-workspace"],
+ ),
patch(
"jiuwenswarm.server.utils.diff_service.get_diff_service",
return_value=fake_diff_service,
@@ -245,6 +252,9 @@ async def test_successful_discard_restores_files_and_marks_dirty():
assert restore_calls[0]["project_dir"] == "/tmp/proj-A"
assert mark_discarded_calls[0]["project_dir"] == "/tmp/proj-A"
assert truncate_calls[0]["project_dir"] == "/tmp/proj-A"
+ assert restore_calls[0]["extra_history_roots"] == ["/tmp/team-workspace"]
+ assert mark_discarded_calls[0]["extra_history_roots"] == ["/tmp/team-workspace"]
+ assert truncate_calls[0]["extra_history_roots"] == ["/tmp/team-workspace"]
# watcher 标脏正确项目
assert registry.mark_dirty_calls == ["proj-A"]