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
fix(deepresearch): preserve styled ZIP bytes on Windows
Fancy1234567c4b77c2045c6
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.pyindex fabfd3d8bc..2896969421 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py@@ -222,7 +222,8 @@ def write_convert_content(output: str | Path, convert_content: object) -> None:if invalid_target:raise BridgeError("bridge_output_invalid")archive = _decode_archive(convert_content)- flags = os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0)+ flags = os.O_WRONLY | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_NOFOLLOW", 0)try:descriptor = os.open(target, flags, mode=0o600)except OSError as exc:diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.pyindex 80eb727da6..263fcb0f52 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py@@ -1416,6 +1416,7 @@ def _extract_validated_zip_members(continuetarget.parent.mkdir(mode=0o700, parents=True, exist_ok=True)flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL+ flags |= getattr(os, "O_BINARY", 0)flags |= getattr(os, "O_NOFOLLOW", 0)descriptor = os.open(target, flags, 0o600)written = 0@@ -2954,7 +2955,8 @@ def _read_regular_file(path: Path, *, limit: int, label: str) -> bytes:)if invalid_named_file:raise OSError(f"unsafe {label}")- flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_NOFOLLOW", 0)descriptor = os.open(path, flags, mode=0o600)try:opened = os.fstat(descriptor)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex c07f63373b..d8836f6ea8 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -7445,7 +7445,9 @@ class JiuWenSwarmDeepAdapter:"service_id": scope.service_id,"agent_id": scope.agent_id,"workspace_key": scope.workspace_key,- "output_dir": self._deepresearch_artifact_output_dir(),+ "output_dir": self._deepresearch_artifact_output_dir(+ route.get("output_dir")+ ),}context = self._runtime_cron_tool_contextmetadata = context.metadata if isinstance(context.metadata, dict) else {}@@ -7457,11 +7459,25 @@ class JiuWenSwarmDeepAdapter:"service_id": scope.service_id,"agent_id": scope.agent_id,"workspace_key": scope.workspace_key,- "output_dir": self._deepresearch_artifact_output_dir(),+ "output_dir": self._deepresearch_artifact_output_dir(+ metadata.get("project_dir")+ ),}- def _deepresearch_artifact_output_dir(self) -> str:- """Return the tenant-owned root used for immutable report artifacts."""+ def _deepresearch_artifact_output_dir(+ self, request_workspace: str | None = None+ ) -> str:+ """Return the current session workspace, or the legacy artifact root."""+ normalized_request_workspace = (+ request_workspace.strip()+ if isinstance(request_workspace, str)+ else ""+ )+ session_workspace = normalized_request_workspace or str(+ getattr(self, "_project_dir", None) or ""+ ).strip()+ if session_workspace:+ return str(Path(session_workspace).expanduser().resolve())workspace = Path(getattr(self, "_workspace_dir", None) or get_agent_workspace_dir()).expanduser().resolve()@@ -9276,7 +9292,9 @@ class JiuWenSwarmDeepAdapter:service_id=scope.service_id,agent_id=scope.agent_id,workspace_key=scope.workspace_key,- output_dir=self._deepresearch_artifact_output_dir(),+ output_dir=self._deepresearch_artifact_output_dir(+ normalized_metadata.get("project_dir")+ ),)except BaseException:self._reset_runtime_cron_context(@@ -15037,6 +15055,16 @@ class JiuWenSwarmDeepAdapter:getattr(self, "_model", None) and getattr(self._model, "model_config", None)and getattr(self._model.model_config, "model_name", "") or "")+ self._current_request_route = {+ "session_id": session_id,+ "request_id": request.request_id or "",+ "channel_id": request.channel_id or "",+ "output_dir": self._deepresearch_artifact_output_dir(+ request.params.get("project_dir")+ if isinstance(request.params, dict)+ else None+ ),+ }slash_result = await self._handle_slash_command(query,@@ -15680,6 +15708,11 @@ class JiuWenSwarmDeepAdapter:"session_id": session_id,"request_id": rid or "","channel_id": cid or "",+ "output_dir": self._deepresearch_artifact_output_dir(+ request.params.get("project_dir")+ if isinstance(request.params, dict)+ else None+ ),}# Team 模式处理diff --git a/tests/conftest.py b/tests/conftest.pyindex 115b8afa0b..d01b39fdf5 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -6,14 +6,50 @@ import inspectimport sysimport tempfileimport warnings-from importlib import import_module+from importlib import import_module, invalidate_cachesfrom pathlib import Pathfrom types import ModuleTypefrom typing import Generatorimport pytest-from jiuwenswarm.common.openjiuwen_rail_compat import install_evolution_rail_kwargs_compat++def _prefer_current_checkout() -> None:+ """Keep an editable install from another worktree out of this test run."""+ repo_root = Path(__file__).resolve().parent.parent+ package_root = (repo_root / "jiuwenswarm").resolve()+ repo_root_s = str(repo_root)+ if not sys.path or sys.path[0] != repo_root_s:+ sys.path.insert(0, repo_root_s)++ stale_checkout_loaded = False+ for name, module in list(sys.modules.items()):+ if name != "jiuwenswarm" and not name.startswith("jiuwenswarm."):+ continue+ loaded_file = getattr(module, "__file__", None)+ if loaded_file is not None and not Path(loaded_file).resolve().is_relative_to(+ package_root+ ):+ stale_checkout_loaded = True+ break+ if not stale_checkout_loaded:+ return++ stale_modules = [+ name+ for name in sys.modules+ if name == "jiuwenswarm" or name.startswith("jiuwenswarm.")+ ]+ for name in sorted(stale_modules, key=lambda item: item.count("."), reverse=True):+ sys.modules.pop(name, None)+ invalidate_caches()+++_prefer_current_checkout()++install_evolution_rail_kwargs_compat = import_module(+ "jiuwenswarm.common.openjiuwen_rail_compat"+).install_evolution_rail_kwargs_compatdef _install_missing_trajectory_processor_stub() -> None:diff --git a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.pyindex 6281792488..fb03d6c61b 100644--- a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py+++ b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py@@ -628,6 +628,70 @@ def test_stream_normal_completion_resets_route_and_legacy_context_once(assert _get_route()["session_id"] == ""+def test_runtime_route_binds_current_session_workspace(tmp_path: Path) -> None:+ from jiuwenswarm.agents.harness.common.tools.deepresearch import tools as dt++ session_workspace = tmp_path / "current-session-workspace"+ adapter = _make_adapter(+ _env_service_id="service-session-output",+ _env_agent_id="agent-session-output",+ _workspace_dir=str(tmp_path / "agent-workspace"),+ )+ tokens = adapter._bind_runtime_cron_context(+ channel_id="officeclaw",+ session_id="sess-session-output",+ metadata={},+ request_id="req-session-output",+ mode="agent",+ project_dir=str(session_workspace),+ )+ try:+ # Generation and rewrite tools both consume this routed output root.+ assert dt._get_effective_request_output_dir() == session_workspace.resolve()+ finally:+ adapter._reset_runtime_cron_context(tokens)+++def test_deepresearch_tool_context_keeps_session_workspace_snapshot(+ tmp_path: Path,+) -> None:+ session_workspace = tmp_path / "current-session-workspace"+ adapter = _make_adapter(+ _current_request_route={+ "session_id": "sess-background-output",+ "request_id": "req-background-output",+ "channel_id": "officeclaw",+ "output_dir": str(session_workspace),+ },+ _runtime_cron_tool_context=SimpleNamespace(+ session_id=None,+ channel_id="default",+ metadata={},+ ),+ _env_service_id="service-background-output",+ _env_agent_id="agent-background-output",+ _workspace_dir=str(tmp_path / "agent-workspace"),+ )++ context = adapter._get_deepresearch_tool_context()++ assert Path(context["output_dir"]) == session_workspace.resolve()+++def test_artifact_output_uses_session_project_when_request_omits_workspace(+ tmp_path: Path,+) -> None:+ session_workspace = tmp_path / "session-project"+ adapter = _make_adapter(+ _project_dir=str(session_workspace),+ _workspace_dir=str(tmp_path / "agent-workspace"),+ )++ assert Path(adapter._deepresearch_artifact_output_dir()) == (+ session_workspace.resolve()+ )++def test_runtime_route_binds_adapter_artifact_output_dir(tmp_path: Path) -> None:from jiuwenswarm.agents.harness.common.tools.deepresearch import tools as dtdiff --git a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.pyindex a51b66c90d..b1e4be09ca 100644--- a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py+++ b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py@@ -128,6 +128,42 @@ def test_bridge_writes_only_to_precreated_private_regular_file(tmp_path: Path):assert zipfile.is_zipfile(output)+def test_bridge_writes_archive_in_binary_mode_on_windows(tmp_path: Path, monkeypatch):+ output = tmp_path / "styled.zip"+ _private_file(output)+ archive = io.BytesIO()+ with zipfile.ZipFile(archive, "w") as bundle:+ bundle.writestr("report_bundle/report.html", b"line-1\nline-2")++ binary_flag = 1 << 29+ opened_flags: dict[int, int] = {}+ original_open = os.open+ original_write = os.write++ def windows_open(path, flags, mode=0o777, **kwargs):+ descriptor = original_open(path, flags & ~binary_flag, mode, **kwargs)+ opened_flags[descriptor] = flags+ return descriptor++ def windows_write(descriptor: int, data: bytes) -> int:+ payload = bytes(data)+ if opened_flags[descriptor] & binary_flag:+ return original_write(descriptor, payload)+ translated = payload.replace(b"\n", b"\r\n")+ assert original_write(descriptor, translated) == len(translated)+ return len(payload)++ monkeypatch.setattr(bridge.os, "O_BINARY", binary_flag, raising=False)+ monkeypatch.setattr(bridge.os, "open", windows_open)+ monkeypatch.setattr(bridge.os, "write", windows_write)++ bridge.write_convert_content(output, base64.b64encode(archive.getvalue()).decode())++ with zipfile.ZipFile(output) as bundle:+ assert bundle.testzip() is None+ assert bundle.read("report_bundle/report.html") == b"line-1\nline-2"++@pytest.mark.parametrize("kind", ["missing", "symlink", "hardlink", "mode", "nonempty", "reparse"])diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.pyindex d92db6b125..af71cf05ce 100644--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py@@ -3311,6 +3311,75 @@ def test_zip_windows_fallback_extracts_and_rolls_back_by_identity(tmp_path: Pathassert not failed.exists()+def test_zip_windows_fallback_writes_members_in_binary_mode(+ tmp_path: Path, monkeypatch+):+ destination = tmp_path / "destination"+ member_payload = b"line-1\nline-2\x1a"+ payload = _zip_payload(+ [("report_bundle/report.html", member_payload, None)]+ )+ binary_flag = 1 << 29+ opened_flags: dict[int, int] = {}+ original_open = os.open+ original_write = os.write++ def windows_open(path, flags, mode=0o777, *, dir_fd=None):+ if dir_fd is not None:+ raise NotImplementedError("dir_fd unavailable")+ descriptor = original_open(path, flags & ~binary_flag, mode)+ opened_flags[descriptor] = flags+ return descriptor++ def windows_write(descriptor: int, data: bytes) -> int:+ raw = bytes(data)+ if opened_flags[descriptor] & binary_flag:+ return original_write(descriptor, raw)+ translated = raw.replace(b"\n", b"\r\n")+ assert original_write(descriptor, translated) == len(translated)+ return len(raw)++ monkeypatch.setattr(dt.os, "O_BINARY", binary_flag, raising=False)+ monkeypatch.setattr(dt.os, "open", windows_open)+ monkeypatch.setattr(dt.os, "write", windows_write)++ with patch.object(dt, "_uses_windows_path_publication", return_value=True):+ bundle = dt._extract_styled_bundle(payload, destination)++ assert (bundle / "report.html").read_bytes() == member_payload+++def test_regular_file_reader_uses_binary_mode_on_windows(+ tmp_path: Path, monkeypatch+):+ source = tmp_path / "styled.zip"+ payload = b"prefix\r\nsuffix\x1atail"+ source.write_bytes(payload)+ binary_flag = 1 << 29+ opened_flags: dict[int, int] = {}+ original_open = os.open+ original_read = os.read++ def windows_open(path, flags, mode=0o777, **kwargs):+ descriptor = original_open(path, flags & ~binary_flag, mode, **kwargs)+ opened_flags[descriptor] = flags+ return descriptor++ def windows_read(descriptor: int, size: int) -> bytes:+ raw = original_read(descriptor, size)+ if opened_flags[descriptor] & binary_flag:+ return raw+ return raw.split(b"\x1a", 1)[0].replace(b"\r\n", b"\n")++ monkeypatch.setattr(dt.os, "O_BINARY", binary_flag, raising=False)+ monkeypatch.setattr(dt.os, "open", windows_open)+ monkeypatch.setattr(dt.os, "read", windows_read)++ assert dt._read_regular_file(+ source, limit=len(payload), label="styled report archive"+ ) == payload++@pytest.mark.asyncioasync def test_spawn_and_child_env_use_same_resolved_interpreter():proc = _Proc([json.dumps({"__deepsearch_status__": "error", "error": "done"})])diff --git a/tests/unit_tests/test_checkout_import_precedence.py b/tests/unit_tests/test_checkout_import_precedence.pynew file mode 100644index 0000000000..2f7ef74cfb--- /dev/null+++ b/tests/unit_tests/test_checkout_import_precedence.py@@ -0,0 +1,62 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Guard unit tests against importing JiuwenSwarm from another checkout."""++from __future__ import annotations++import subprocess+import sys+import textwrap+from pathlib import Path++import jiuwenswarm+++def test_unit_tests_import_jiuwenswarm_from_current_checkout() -> None:+ repo_root = Path(__file__).resolve().parents[2]+ package_file = Path(jiuwenswarm.__file__).resolve()++ assert package_file.is_relative_to(repo_root / "jiuwenswarm"), (+ f"unit tests imported jiuwenswarm from another checkout: {package_file}"+ )+++def test_conftest_reloads_when_a_submodule_comes_from_another_checkout(+ tmp_path: Path,+) -> None:+ repo_root = Path(__file__).resolve().parents[2]+ stale_file = tmp_path / "other-checkout" / "jiuwenswarm" / "stale_probe.py"+ script = textwrap.dedent(+ f"""+ import runpy+ import sys+ from pathlib import Path+ from types import ModuleType++ repo_root = Path({str(repo_root)!r})+ sys.path.insert(0, str(repo_root))+ import jiuwenswarm++ stale = ModuleType("jiuwenswarm.stale_checkout_probe")+ stale.__file__ = {str(stale_file)!r}+ sys.modules[stale.__name__] = stale++ runpy.run_path(+ str(repo_root / "tests" / "conftest.py"),+ run_name="checkout_conftest_probe",+ )++ assert stale.__name__ not in sys.modules, sys.modules[stale.__name__].__file__+ package_file = Path(sys.modules["jiuwenswarm"].__file__).resolve()+ assert package_file.is_relative_to(repo_root / "jiuwenswarm"), package_file+ """+ )+ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=repo_root,+ capture_output=True,+ text=True,+ check=False,+ )++ assert completed.returncode == 0, completed.stdout + completed.stderr