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: consolidate local compatibility fixes
hualingeb792ec7f1cfd
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.pyindex a11e6d0b7b..5df23ce221 100644--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py@@ -42,6 +42,18 @@ logger = logging.getLogger(__name__)MAX_STRUCTURED_QUESTIONS = 4++def _decode_questions_array(raw_questions: Any) -> tuple[Any, bool]:+ """Accept one accidental JSON encoding layer around a questions array."""+ if not isinstance(raw_questions, str):+ return raw_questions, False+ try:+ decoded = json.loads(raw_questions)+ except (ValueError, TypeError):+ return raw_questions, False+ return (decoded, True) if isinstance(decoded, list) else (raw_questions, False)++# ---------------------------------------------------------------------------# Extended input schema# ---------------------------------------------------------------------------@@ -314,7 +326,11 @@ class StructuredAskUserRail(AskUserRail):"[INVALID_ARGUMENT] return_json must be a boolean when provided."))- raw_questions = args.get("questions")+ raw_questions, questions_were_decoded = _decode_questions_array(+ args.get("questions")+ )+ if questions_were_decoded:+ args["questions"] = raw_questionsif "questions" in args and not isinstance(raw_questions, list):return self.reject(tool_result=(@@ -403,7 +419,12 @@ class StructuredAskUserRail(AskUserRail):)if user_input is None:- return self.interrupt(self._build_ask_request(tool_call))+ interrupt_tool_call = tool_call+ if tool_call is not None and questions_were_decoded:+ interrupt_tool_call = tool_call.model_copy(+ update={"arguments": json.dumps(args, ensure_ascii=False)}+ )+ return self.interrupt(self._build_ask_request(interrupt_tool_call))# Detect if this was a structured questions call by checking tool_argsis_structured = questions_data is not None and len(questions_data) > 0diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/path_safety.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/path_safety.pyindex 14a12822fa..4d909a2c0d 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/path_safety.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/path_safety.py@@ -3,6 +3,7 @@from __future__ import annotations+import osimport stat@@ -15,3 +16,21 @@ def is_direct_directory(metadata: object) -> bool:and not stat.S_ISLNK(mode)and not attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT)+++def is_direct_regular_file(metadata: object) -> bool:+ """Return true only for a regular file that is not a link or reparse point."""+ mode = getattr(metadata, "st_mode", 0)+ attributes = getattr(metadata, "st_file_attributes", 0)+ return (+ stat.S_ISREG(mode)+ and not stat.S_ISLNK(mode)+ and not attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT+ )+++def private_mode_is_compatible(metadata: object, expected_mode: int) -> bool:+ """Enforce exact POSIX modes without rejecting Windows' synthetic modes."""+ if os.name == "nt" or hasattr(metadata, "st_file_attributes"):+ return True+ return stat.S_IMODE(getattr(metadata, "st_mode", 0)) == expected_modediff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.pyindex c67fb65938..380d22f820 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py@@ -14,6 +14,11 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, AsyncIterator+from jiuwenswarm.agents.harness.common.tools.deepresearch.path_safety import (+ is_direct_directory,+ is_direct_regular_file,+ private_mode_is_compatible,+)from jiuwenswarm.common.local_env_config import export_spawn_environ_ALLOWED_PROXY_KEYS = (@@ -124,9 +129,8 @@ def _create_bridge_artifact() -> _BridgeArtifact:directory.chmod(0o700)directory_metadata = directory.lstat()if (- not stat.S_ISDIR(directory_metadata.st_mode)- or stat.S_ISLNK(directory_metadata.st_mode)- or stat.S_IMODE(directory_metadata.st_mode) != 0o700+ not is_direct_directory(directory_metadata)+ or not private_mode_is_compatible(directory_metadata, 0o700)):raise OSError("unsafe bridge directory")path = directory / "styled.zip"@@ -134,9 +138,9 @@ def _create_bridge_artifact() -> _BridgeArtifact:descriptor = os.open(path, flags, 0o600)file_metadata = os.fstat(descriptor)if (- not stat.S_ISREG(file_metadata.st_mode)+ not is_direct_regular_file(file_metadata)or file_metadata.st_nlink != 1- or stat.S_IMODE(file_metadata.st_mode) != 0o600+ or not private_mode_is_compatible(file_metadata, 0o600)):raise OSError("unsafe bridge output")return _BridgeArtifact(@@ -311,10 +315,9 @@ async def _drain_stderr_tail(stream: Any, limit: int) -> bytes:def _validate_bridge_output(artifact: _BridgeArtifact) -> None:metadata = artifact.path.lstat()invalid_output = (- not stat.S_ISREG(metadata.st_mode)- or stat.S_ISLNK(metadata.st_mode)+ not is_direct_regular_file(metadata)or metadata.st_nlink != 1- or stat.S_IMODE(metadata.st_mode) != 0o600+ or not private_mode_is_compatible(metadata, 0o600)or (metadata.st_dev, metadata.st_ino) != artifact.file_identityor metadata.st_size <= 0or metadata.st_size > _BRIDGE_ARCHIVE_MAX_BYTESdiff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.pyindex 6a930a10de..a7a4b5c11c 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py@@ -9,13 +9,17 @@ import ioimport jsonimport loggingimport os-import statimport sysimport zipfilefrom contextlib import redirect_stdoutfrom pathlib import Pathfrom typing import BinaryIO+try:+ from .path_safety import is_direct_regular_file, private_mode_is_compatible+except ImportError: # Executed as a standalone script by runtime.py.+ from path_safety import is_direct_regular_file, private_mode_is_compatible+BRIDGE_INPUT_MAX_BYTES = 64 * 1024 * 1024BRIDGE_ARCHIVE_MAX_BYTES = 128 * 1024 * 1024BRIDGE_JSON_MAX_DEPTH = 64@@ -158,10 +162,9 @@ def write_convert_content(output: str | Path, convert_content: object) -> None:except OSError as exc:raise BridgeError("bridge_output_invalid") from excinvalid_target = (- not stat.S_ISREG(before.st_mode)- or stat.S_ISLNK(before.st_mode)+ not is_direct_regular_file(before)or before.st_nlink != 1- or stat.S_IMODE(before.st_mode) != 0o600+ or not private_mode_is_compatible(before, 0o600)or before.st_size != 0)if invalid_target:@@ -175,9 +178,9 @@ def write_convert_content(output: str | Path, convert_content: object) -> None:try:opened = os.fstat(descriptor)invalid_open_file = (- not stat.S_ISREG(opened.st_mode)+ not is_direct_regular_file(opened)or opened.st_nlink != 1- or stat.S_IMODE(opened.st_mode) != 0o600+ or not private_mode_is_compatible(opened, 0o600)or opened.st_size != 0or not _same_unchanged_file(before, opened))@@ -193,10 +196,11 @@ def write_convert_content(output: str | Path, convert_content: object) -> None:os.fsync(descriptor)after = os.fstat(descriptor)invalid_written_file = (- not _same_file(opened, after)+ not is_direct_regular_file(after)+ or not _same_file(opened, after)or after.st_size != len(archive)or after.st_nlink != 1- or stat.S_IMODE(after.st_mode) != 0o600+ or not private_mode_is_compatible(after, 0o600))if invalid_written_file:raise BridgeError("bridge_output_invalid")diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.pyindex 1a8e85a645..f3fb9fc0f5 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py@@ -35,6 +35,8 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.runtime import ()from jiuwenswarm.agents.harness.common.tools.deepresearch.path_safety import (is_direct_directory,+ is_direct_regular_file,+ private_mode_is_compatible,)from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (RouterState,@@ -1048,9 +1050,8 @@ def _create_progress_artifact() -> _ProgressArtifact:try:directory_metadata = directory.lstat()if (- not stat.S_ISDIR(directory_metadata.st_mode)- or stat.S_ISLNK(directory_metadata.st_mode)- or stat.S_IMODE(directory_metadata.st_mode) != 0o700+ not is_direct_directory(directory_metadata)+ or not private_mode_is_compatible(directory_metadata, 0o700)):raise OSError("unsafe DeepResearch progress directory")path = directory / "progress.jsonl"@@ -1060,9 +1061,9 @@ def _create_progress_artifact() -> _ProgressArtifact:try:file_metadata = os.fstat(descriptor)if (- not stat.S_ISREG(file_metadata.st_mode)+ not is_direct_regular_file(file_metadata)or file_metadata.st_nlink != 1- or stat.S_IMODE(file_metadata.st_mode) != 0o600+ or not private_mode_is_compatible(file_metadata, 0o600)):raise OSError("unsafe DeepResearch progress file")finally:diff --git a/tests/unit_tests/agentserver/memory/test_external_memory_config.py b/tests/unit_tests/agentserver/memory/test_external_memory_config.pyindex 065585060e..54eb2e2ef0 100644--- a/tests/unit_tests/agentserver/memory/test_external_memory_config.py+++ b/tests/unit_tests/agentserver/memory/test_external_memory_config.py@@ -106,7 +106,11 @@ def test_get_memory_engine_valid_values(value, expected):{},None,])-def test_get_memory_engine_falls_back_to_builtin(cfg):+def test_get_memory_engine_falls_back_to_builtin(cfg, monkeypatch):+ if cfg is None:+ from jiuwenswarm.agents.harness.common.memory import config as memory_config++ monkeypatch.setattr(memory_config, "get_memory_section", lambda _config: {})assert emc.get_memory_engine(cfg) == "builtin"diff --git a/tests/unit_tests/agentserver/test_agent_warm_pool.py b/tests/unit_tests/agentserver/test_agent_warm_pool.pyindex 8c60ded0b1..72afb45859 100644--- a/tests/unit_tests/agentserver/test_agent_warm_pool.py+++ b/tests/unit_tests/agentserver/test_agent_warm_pool.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import osimport threadingfrom pathlib import Path@@ -150,7 +151,7 @@ def test_warm_key_normalizes_project_directory(tmp_path: Path) -> None:work_mode="CODE",)assert key.channel_id == "web"- assert key.project_dir == str(tmp_path.resolve()).lower()+ assert key.project_dir == os.path.normcase(str(tmp_path.resolve()))assert key.agent_mode == "code"assert key.agent_sub_mode == "normal"diff --git a/tests/unit_tests/agentserver/test_ask_user_validation.py b/tests/unit_tests/agentserver/test_ask_user_validation.pyindex 5661ecf6f4..5ff5612080 100644--- a/tests/unit_tests/agentserver/test_ask_user_validation.py+++ b/tests/unit_tests/agentserver/test_ask_user_validation.py@@ -15,6 +15,9 @@ from jiuwenswarm.agents.harness.common.rails.ask_user_rail import (StructuredAskUserRail,StructuredAskUserTool,)+from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ convert_interactions_to_ask_user_question,+)def _make_tool_call(arguments: dict) -> ToolCall:@@ -85,6 +88,53 @@ async def test_valid_options_still_interrupt():assert isinstance(decision, InterruptResult)+async def test_json_encoded_questions_array_still_interrupts_with_structured_payload():+ """A provider may serialize the valid questions array once more."""+ questions = [+ {+ "question": "Which option?",+ "header": "Choice",+ "options": [+ {"label": "A", "description": "a"},+ {"label": "B", "description": "b"},+ ],+ }+ ]+ rail = StructuredAskUserRail()+ tc = _make_tool_call(+ {+ "query": "Choose",+ "questions": json.dumps(questions),+ }+ )++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ assert isinstance(decision, InterruptResult)+ assert decision.request.questions == questions++ interaction = MagicMock()+ interaction.id = "req_ask"+ interaction.value = decision.request+ payload = convert_interactions_to_ask_user_question([interaction])+ assert payload is not None+ assert payload["source"] == "ask_user_interrupt"+ assert payload["questions"][0]["question"] == questions[0]["question"]++[email protected]("questions", ["[not json]", json.dumps({"question": "not an array"})])+async def test_json_encoded_non_array_questions_remain_rejected(questions):+ rail = StructuredAskUserRail()+ tc = _make_tool_call({"query": "Choose", "questions": questions})++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ assert isinstance(decision, RejectResult)+ assert "questions must be an array" in decision.tool_result++@pytest.mark.asyncioasync def test_empty_structured_answers_preserve_answered_machine_state():"""The shared AskUser contract preserves answered even when answers are empty."""diff --git a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.pyindex d42e521687..63c7e00603 100644--- a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py+++ b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py@@ -7,6 +7,7 @@ import asyncioimport ioimport jsonimport os+import statimport sysimport typesimport zipfile@@ -104,8 +105,10 @@ def test_bridge_writes_only_to_precreated_private_regular_file(tmp_path: Path):assert zipfile.is_zipfile(output)[email protected]("kind", ["missing", "symlink", "hardlink", "mode", "nonempty"])-def test_bridge_rejects_unsafe_output(tmp_path: Path, kind: str):+ "kind", ["missing", "symlink", "hardlink", "mode", "nonempty", "reparse"]+)+def test_bridge_rejects_unsafe_output(tmp_path: Path, kind: str, monkeypatch):output = tmp_path / "styled.zip"if kind == "symlink":source = tmp_path / "source"@@ -121,6 +124,25 @@ def test_bridge_rejects_unsafe_output(tmp_path: Path, kind: str):elif kind == "nonempty":_private_file(output)output.write_bytes(b"occupied")+ elif kind == "reparse":+ _private_file(output)+ original_lstat = Path.lstat++ def reparse_lstat(path: Path):+ metadata = original_lstat(path)+ if path == output:+ return types.SimpleNamespace(+ st_mode=metadata.st_mode,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_nlink=metadata.st_nlink,+ st_size=metadata.st_size,+ st_ctime_ns=metadata.st_ctime_ns,+ st_file_attributes=stat.FILE_ATTRIBUTE_REPARSE_POINT,+ )+ return metadata++ monkeypatch.setattr(Path, "lstat", reparse_lstat)with pytest.raises(bridge.BridgeError, match="bridge_output_invalid"):bridge.write_convert_content(output, base64.b64encode(_zip_bytes()).decode())@@ -179,6 +201,113 @@ def test_parent_keeps_bridge_output_open_until_cleanup():os.fstat(artifact.descriptor)+def test_parent_bridge_artifact_accepts_windows_synthetic_mode_bits(+ tmp_path: Path, monkeypatch+):+ directory = tmp_path / "deepresearch-sdk-bridge"+ directory.mkdir(mode=0o700)+ original_lstat = Path.lstat+ original_fstat = os.fstat++ def windows_lstat(path: Path):+ metadata = original_lstat(path)+ if path == directory:+ return types.SimpleNamespace(+ st_mode=stat.S_IFDIR | 0o777,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_file_attributes=0,+ )+ return metadata++ def windows_fstat(descriptor: int):+ metadata = original_fstat(descriptor)+ return types.SimpleNamespace(+ st_mode=stat.S_IFREG | 0o666,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_nlink=1,+ st_file_attributes=0,+ )++ monkeypatch.setattr(runtime.tempfile, "mkdtemp", lambda **_kwargs: str(directory))+ monkeypatch.setattr(Path, "lstat", windows_lstat)+ monkeypatch.setattr(runtime.os, "fstat", windows_fstat)++ artifact = runtime._create_bridge_artifact()+ try:+ assert artifact.path == directory / "styled.zip"+ finally:+ runtime._remove_bridge_artifact(artifact)+++def test_parent_validates_windows_synthetic_archive_mode(monkeypatch):+ artifact = runtime._create_bridge_artifact()+ original_lstat = Path.lstat+ try:+ os.write(artifact.descriptor, _zip_bytes())+ os.fsync(artifact.descriptor)++ def windows_lstat(path: Path):+ metadata = original_lstat(path)+ if path == artifact.path:+ return types.SimpleNamespace(+ st_mode=stat.S_IFREG | 0o666,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_nlink=metadata.st_nlink,+ st_size=metadata.st_size,+ st_file_attributes=0,+ )+ return metadata++ monkeypatch.setattr(Path, "lstat", windows_lstat)+ runtime._validate_bridge_output(artifact)+ finally:+ runtime._remove_bridge_artifact(artifact)+++def test_child_bridge_accepts_windows_synthetic_mode_bits(+ tmp_path: Path, monkeypatch+):+ output = tmp_path / "styled.zip"+ _private_file(output)+ original_lstat = Path.lstat+ original_fstat = os.fstat++ def windows_lstat(path: Path):+ metadata = original_lstat(path)+ if path == output:+ return types.SimpleNamespace(+ st_mode=stat.S_IFREG | 0o666,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_nlink=metadata.st_nlink,+ st_size=metadata.st_size,+ st_ctime_ns=metadata.st_ctime_ns,+ st_file_attributes=0,+ )+ return metadata++ def windows_fstat(descriptor: int):+ metadata = original_fstat(descriptor)+ return types.SimpleNamespace(+ st_mode=stat.S_IFREG | 0o666,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_nlink=metadata.st_nlink,+ st_size=metadata.st_size,+ st_ctime_ns=metadata.st_ctime_ns,+ st_file_attributes=0,+ )++ monkeypatch.setattr(Path, "lstat", windows_lstat)+ monkeypatch.setattr(bridge.os, "fstat", windows_fstat)++ bridge.write_convert_content(output, base64.b64encode(_zip_bytes()).decode())+ assert zipfile.is_zipfile(output)++@pytest.mark.asyncioasync def test_sdk_is_lazy_logs_only_to_stderr_and_restores_tls(tmp_path: Path, monkeypatch, capsys):output = tmp_path / "styled.zip"diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.pyindex 6f6056d60e..644d7f204f 100644--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py@@ -1683,6 +1683,46 @@ def test_windows_output_root_reparse_point_is_rejected(tmp_path: Path):dt._open_output_root(tmp_path)+def test_progress_artifact_accepts_windows_synthetic_mode_bits(+ tmp_path: Path, monkeypatch+):+ directory = tmp_path / "deepresearch-progress"+ directory.mkdir(mode=0o700)+ original_lstat = Path.lstat+ original_fstat = os.fstat++ def windows_lstat(path: Path):+ metadata = original_lstat(path)+ if path == directory:+ return SimpleNamespace(+ st_mode=stat.S_IFDIR | 0o777,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_file_attributes=0,+ )+ return metadata++ def windows_fstat(descriptor: int):+ metadata = original_fstat(descriptor)+ return SimpleNamespace(+ st_mode=stat.S_IFREG | 0o666,+ st_dev=metadata.st_dev,+ st_ino=metadata.st_ino,+ st_nlink=1,+ st_file_attributes=0,+ )++ monkeypatch.setattr(dt.tempfile, "mkdtemp", lambda **_kwargs: str(directory))+ monkeypatch.setattr(Path, "lstat", windows_lstat)+ monkeypatch.setattr(dt.os, "fstat", windows_fstat)++ artifact = dt._create_progress_artifact()+ try:+ assert artifact.path == directory / "progress.jsonl"+ finally:+ dt._remove_progress_artifact(artifact)++def test_build_deepresearch_config_maps_only_required_values():source = {"MODEL_NAME": "model",diff --git a/tests/unit_tests/extensions/test_agentos_router.py b/tests/unit_tests/extensions/test_agentos_router.pyindex 48ea906ce3..36bfc69f25 100644--- a/tests/unit_tests/extensions/test_agentos_router.py+++ b/tests/unit_tests/extensions/test_agentos_router.py@@ -25,6 +25,7 @@ from jiuwenswarm.extensions.agentos.agentos_router.router_client import (AgentOSRouterClient,resolve_agent_workspace,)+from jiuwenswarm.extensions.agentos.agentos_router import router_clientfrom jiuwenswarm.extensions.yuanrong_frontend_client import SandboxInfo@@ -212,31 +213,41 @@ async def test_swarm_request_repeated_stays_direct() -> None:assert yuanrong.send_calls == 2-def test_resolve_agent_workspace_defaults_under_agentos_users() -> None:- assert resolve_agent_workspace("alice") == f"{DEFAULT_AGENT_WORKSPACE_ROOT}/alice"+def test_resolve_agent_workspace_defaults_under_agentos_users(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(router_client, "DEFAULT_AGENT_WORKSPACE_ROOT", str(tmp_path))+ expected_root = tmp_path.resolve()++ assert resolve_agent_workspace("alice") == str(expected_root / "alice")assert resolve_agent_workspace("alice/../bob") == (- f"{DEFAULT_AGENT_WORKSPACE_ROOT}/alice_.._bob"+ str(expected_root / "alice_.._bob"))assert resolve_agent_workspace("u1", workspace_root="/data/ws") == "/data/ws/u1"@pytest.mark.asyncio-async def test_third_party_type_creates_via_yuanrong() -> None:+async def test_third_party_type_creates_via_yuanrong(tmp_path) -> None:yuanrong = FakeYuanRongClient()agent_manager = AgentManager()- client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)+ workspace_root = str(tmp_path)+ expected_workspace = str(tmp_path.resolve() / "u1")+ client = AgentOSRouterClient(+ yuanrong,+ FakeRegistryClient(),+ agent_manager,+ workspace_root=workspace_root,+ )response = await client.send_request(_envelope(agent_type="opencode"))assert response.okassert yuanrong.create_calls == 1- assert yuanrong.create_payloads[0]["workspace"] == f"{DEFAULT_AGENT_WORKSPACE_ROOT}/u1"+ assert yuanrong.create_payloads[0]["workspace"] == expected_workspaceassert yuanrong.send_calls == 1agents = await agent_manager.list_user_agents("u1")assert agents[0].info.agent_type == "opencode"assert agents[0].info.status is AgentStatus.READYassert agents[0].info.sandbox_id == "sbx-1"- assert agents[0].info.metadata["workspace"] == f"{DEFAULT_AGENT_WORKSPACE_ROOT}/u1"+ assert agents[0].info.metadata["workspace"] == expected_workspace@pytest.mark.asynciodiff --git a/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py b/tests/unit_tests/gateway/test_message_handler_security_review_prompt.pyindex 302eb95d0c..00b5f0a4d1 100644--- a/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py+++ b/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py@@ -76,11 +76,17 @@ def _add_origin_head(path: str, bare: str) -> None:"""subprocess.run([_GIT, "init", "--bare", "-q", bare], check=True)subprocess.run([_GIT, "-C", path, "remote", "add", "origin", bare], check=True)- subprocess.run([_GIT, "-C", path, "push", "-q", "origin", "HEAD"], check=True)+ branch = subprocess.run(+ [_GIT, "-C", path, "branch", "--show-current"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ subprocess.run([_GIT, "-C", path, "push", "-q", "origin", f"HEAD:{branch}"], check=True)# 先 fetch 建立 refs/remotes/origin/* ,再用显式分支名 set-head# (`set-head origin HEAD` 在某些 git 版本会静默不写 symref)。subprocess.run([_GIT, "-C", path, "fetch", "-q", "origin"], check=True)- subprocess.run([_GIT, "-C", path, "remote", "set-head", "origin", "master"], check=True)+ subprocess.run([_GIT, "-C", path, "remote", "set-head", "origin", branch], check=True)def test_run_security_review_git_succeeds_when_origin_head_set(tmp_path):diff --git a/tests/unit_tests/redis/test_redis_runtime.py b/tests/unit_tests/redis/test_redis_runtime.pyindex 1c1a6eb253..07079c0af9 100644--- a/tests/unit_tests/redis/test_redis_runtime.py+++ b/tests/unit_tests/redis/test_redis_runtime.py@@ -75,10 +75,27 @@ async def test_active_standby_unreachable_server_degrades(init_gateway_redis_from_config,)+ class _UnreachableRedisClient:+ def __init__(self, _config) -> None:+ pass++ async def open(self) -> None:+ pass++ async def ping(self) -> bool:+ return False++ async def close(self) -> None:+ pass+monkeypatch.setenv("AGENT_RUNTIME", "1")+ monkeypatch.setattr(+ "jiuwenswarm.extensions.redis.redis_runtime._load_gateway_redis_client_class",+ lambda: _UnreachableRedisClient,+ )await init_gateway_redis_from_config({"gateway": {"deployment_mode": "active-standby"},- "redis": {"host": "127.0.0.1", "port": 6379},+ "redis": {"host": "unreachable.test", "port": 1},})assert get_declared_deployment_mode() == "active-standby"assert not get_effective_distributed_redis_active()diff --git a/tests/unit_tests/telemetry/test_callbacks.py b/tests/unit_tests/telemetry/test_callbacks.pyindex e79711a1c4..bbc2957055 100644--- a/tests/unit_tests/telemetry/test_callbacks.py+++ b/tests/unit_tests/telemetry/test_callbacks.py@@ -2927,7 +2927,8 @@ def test_input_control_errors_propagate_after_state_cleanup(# KeyboardInterrupt/SystemExit inside pytest-asyncio (or asyncio.wait_for's# nested task) aborts the whole pytest session. Drive the coroutine with- # asyncio.run() so pytest.raises can catch them in a sync test.+ # an explicitly closed event loop so pytest.raises can catch them without+ # leaving its selector sockets behind after a prior async test.monkeypatch.setattr(callbacks_module.asyncio, "to_thread", _inline_to_thread)monkeypatch.setattr(callbacks_module.asyncio, "wait_for", _inline_wait_for)@@ -2945,8 +2946,16 @@ def test_input_control_errors_propagate_after_state_cleanup(async def _exercise() -> None:await callbacks._on_llm_invoke_input(messages=[], model="control-model")+ def _run_in_closed_loop() -> None:+ loop = asyncio.new_event_loop()+ try:+ loop.run_until_complete(_exercise())+ finally:+ loop.run_until_complete(loop.shutdown_asyncgens())+ loop.close()+with pytest.raises(type(control_error)):- asyncio.run(_exercise())+ _run_in_closed_loop()assert callbacks._metric_state.active_count() == 0assert callbacks._span_state.active_count() == 0