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(start-services): 修复启动端口展示/绑定不一致与 IPv6 预检漏检
NickFuryXXX51ed46d3c43d
diff --git a/jiuwenswarm/dotenv_early.py b/jiuwenswarm/dotenv_early.pyindex 796554400e..53a3e38586 100644--- a/jiuwenswarm/dotenv_early.py+++ b/jiuwenswarm/dotenv_early.py@@ -65,9 +65,10 @@ def _early_error(component_name: str, message: str) -> None:_early_logger.error("[%s] %s", component_name, message)-# Port / bind keys injected by jiuwenswarm-desktop for the current session.-# When JIUWENSWARM_DESKTOP=1, load_dotenv(override=True) must not clobber them-# with stale values from ~/.jiuwenswarm/config/.env (e.g. a prior CLI fallback).+# Port / bind keys injected for the current launch session (desktop or+# jiuwenswarm-start). When a session flag is set, load_dotenv(override=True)+# must not clobber them with stale values from ~/.jiuwenswarm/config/.env+# (e.g. a prior CLI port-fallback residue such as GATEWAY_PORT=20001).DESKTOP_PRESERVED_ENV_KEYS = ("WEB_HOST","WEB_PORT",@@ -77,23 +78,36 @@ DESKTOP_PRESERVED_ENV_KEYS = ("FRONTEND_PORT",)+# Flag set by jiuwenswarm-start when it injects the resolved port group into+# child env. Mirrors JIUWENSWARM_DESKTOP=1 for the CLI launcher path (issue #2749).+CLI_PORTS_ENV_FLAG = "JIUWENSWARM_CLI_PORTS"+++def _should_preserve_session_ports() -> bool:+ """True when this process was launched with an explicit session port remap."""+ return (+ os.environ.get("JIUWENSWARM_DESKTOP") == "1"+ or os.environ.get(CLI_PORTS_ENV_FLAG) == "1"+ )+def load_dotenv_runtime(dotenv_path: str | Path | None, *, override: bool = True) -> bool:- """load_dotenv wrapper that keeps desktop-injected port env vars.+ """load_dotenv wrapper that keeps session-injected port env vars.- Non-desktop processes behave exactly like ``load_dotenv``. Under- ``JIUWENSWARM_DESKTOP=1``, any of ``DESKTOP_PRESERVED_ENV_KEYS`` already- present in ``os.environ`` are restored after loading so a session-local- port remap survives ``override=True``.+ Plain processes behave exactly like ``load_dotenv``. Under+ ``JIUWENSWARM_DESKTOP=1`` or ``JIUWENSWARM_CLI_PORTS=1``, any of+ ``DESKTOP_PRESERVED_ENV_KEYS`` already present in ``os.environ`` are+ restored after loading so the launcher's resolved port group survives+ ``override=True`` (avoids banner vs Gateway bind mismatch, issue #2749).- Also drops ``AGENT_SERVER_URL`` in desktop mode: Gateway prefers that URL+ Also drops ``AGENT_SERVER_URL`` in those modes: Gateway prefers that URLover ``AGENT_SERVER_PORT``, so a stale value from .env/shell would bypassthe remapped agent port. Without the URL, Gateway builds``ws://{host}:{AGENT_SERVER_PORT}`` from the injected port."""from dotenv import load_dotenv- preserve = os.environ.get("JIUWENSWARM_DESKTOP") == "1"+ preserve = _should_preserve_session_ports()saved = ({k: os.environ[k] for k in DESKTOP_PRESERVED_ENV_KEYS if k in os.environ}if preserve@@ -291,6 +305,7 @@ def load_instance_bootstrap_by_name(name: str) -> Path | None:__all__ = [+ "CLI_PORTS_ENV_FLAG","DESKTOP_PRESERVED_ENV_KEYS","parse_dotenv_early","load_dotenv_runtime",diff --git a/jiuwenswarm/instance_manager/config.py b/jiuwenswarm/instance_manager/config.pyindex 9d26d2c26b..ad3cc1075d 100644--- a/jiuwenswarm/instance_manager/config.py+++ b/jiuwenswarm/instance_manager/config.py@@ -187,6 +187,44 @@ def calculate_instance_ports(index: int) -> Dict[str, int]:return {k: _resolved_base_port(k) + index * 1000 for k in BASE_PORTS}+def _bind_listen_probe(host: str, port: int, family: int) -> bool | None:+ """Try bind()+listen() on ``host:port``.++ Returns:+ True if the port can be bound, False if occupied, None if this address+ family / host is unsupported on the machine (caller should ignore).+ """+ try:+ sock = socket.socket(family, socket.SOCK_STREAM)+ except OSError:+ return None+ # Intentionally NOT setting SO_REUSEADDR: on Windows it permits multiple+ # sockets to bind the same port, which would mask an occupied port and+ # reproduce the very 10048 crash we are trying to avoid. The real services+ # do not set it either.+ try:+ sock.bind((host, port))+ sock.listen(1)+ return True+ except OSError as exc:+ # Windows: WinError 10022/10049; POSIX: EADDRNOTAVAIL / EAFNOSUPPORT+ # when IPv6 is disabled — treat as "family unavailable", not occupied.+ winerr = getattr(exc, "winerror", None)+ errno = getattr(exc, "errno", None)+ if winerr in (10022, 10049) or errno in (+ getattr(socket, "EADDRNOTAVAIL", 99),+ getattr(socket, "EAFNOSUPPORT", 97),+ getattr(socket, "EPROTONOSUPPORT", 93),+ ):+ return None+ return False+ finally:+ try:+ sock.close()+ except OSError:+ pass++def is_port_available(host: str, port: int) -> bool:"""Check if a port is available for binding on the given host.@@ -205,6 +243,11 @@ def is_port_available(host: str, port: int) -> bool:held by a dead-but-listening socket, causing the real service to crashwith ``OSError [Errno 10048]`` on its own bind.+ When ``host`` is IPv4 loopback / wildcard, also probes ``::1``: Vite on+ Windows often listens on ``[::1]:5173`` only. An IPv4-only probe would+ report the port free, skip ``jiuwenswarm-start`` port-group fallback, and+ then ``strictPort: true`` would fail with "Port 5173 is already in use".+Args:host: Host address to checkport: Port number to check@@ -212,22 +255,20 @@ def is_port_available(host: str, port: int) -> bool:Returns:True if the port can be bound (available), False if occupied."""- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- # Intentionally NOT setting SO_REUSEADDR: on Windows it permits multiple- # sockets to bind the same port, which would mask an occupied port and- # reproduce the very 10048 crash we are trying to avoid. The real services- # do not set it either.- try:- sock.bind((host, port))- sock.listen(1)- return True # Port is available (we could bind it)- except OSError:- return False # Port is occupied- finally:- try:- sock.close()- except OSError:- pass+ family = socket.AF_INET6 if ":" in host and host.count(":") >= 2 else socket.AF_INET+ primary = _bind_listen_probe(host, port, family)+ if primary is False:+ return False+ if primary is None and family == socket.AF_INET6:+ # Explicit IPv6 host but stack unavailable — fall back to IPv4 view.+ return bool(_bind_listen_probe("127.0.0.1", port, socket.AF_INET))++ # Dual-stack localhost: Vite / Node frequently bind ::1 only.+ if host in ("127.0.0.1", "0.0.0.0", "", "localhost"):+ ipv6 = _bind_listen_probe("::1", port, socket.AF_INET6)+ if ipv6 is False:+ return False+ return primary is not Falsedef check_port_conflicts(diff --git a/jiuwenswarm/start_services.py b/jiuwenswarm/start_services.pyindex 6e0d1e1eb5..91bcef588d 100644--- a/jiuwenswarm/start_services.py+++ b/jiuwenswarm/start_services.py@@ -495,18 +495,27 @@ def _start_process() -> subprocess.Popen[bytes]:"""Start a single subprocess."""import json+ from jiuwenswarm.dotenv_early import CLI_PORTS_ENV_FLAG+logging.info(f"[start_services] starting {name}: {' '.join(cmd)} (cwd={cwd})")env = os.environ.copy()env["JIUWENSWARM_START_CMD"] = json.dumps(sys.argv[:])if ports:+ # Inject the resolved port group and mark the child so+ # load_dotenv_runtime(override=True) cannot clobber it with a stale+ # ~/.jiuwenswarm/config/.env residue (issue #2749: banner 19001 vs+ # Gateway bind 20001).env.update({+ CLI_PORTS_ENV_FLAG: "1","AGENT_SERVER_PORT": str(ports["agent_server"]),+ "AGENT_PORT": str(ports["agent_server"]),"WEB_PORT": str(ports["web"]),"GATEWAY_PORT": str(ports["gateway"]),"FRONTEND_PORT": str(ports["frontend"]),})+ env.pop("AGENT_SERVER_URL", None)return subprocess.Popen(cmd, cwd=str(cwd), env=env)diff --git a/tests/unit_tests/test_desktop_port_resolve.py b/tests/unit_tests/test_desktop_port_resolve.pyindex bf1ad07905..2c2b6334b0 100644--- a/tests/unit_tests/test_desktop_port_resolve.py+++ b/tests/unit_tests/test_desktop_port_resolve.py@@ -10,7 +10,11 @@ from pathlib import Pathimport pytest-from jiuwenswarm.dotenv_early import DESKTOP_PRESERVED_ENV_KEYS, load_dotenv_runtime+from jiuwenswarm.dotenv_early import (+ CLI_PORTS_ENV_FLAG,+ DESKTOP_PRESERVED_ENV_KEYS,+ load_dotenv_runtime,+)from jiuwenswarm.instance_manager.config import BASE_PORTS, calculate_instance_ports@@ -39,6 +43,7 @@ def test_load_dotenv_runtime_preserves_desktop_ports(tmp_path: Path, monkeypatch)monkeypatch.setenv("JIUWENSWARM_DESKTOP", "1")+ monkeypatch.delenv(CLI_PORTS_ENV_FLAG, raising=False)monkeypatch.setenv("WEB_PORT", "20000")monkeypatch.setenv("GATEWAY_PORT", "20001")monkeypatch.setenv("AGENT_SERVER_PORT", "19092")@@ -62,6 +67,7 @@ def test_load_dotenv_runtime_drops_stale_agent_server_url(tmp_path: Path, monkey)monkeypatch.setenv("JIUWENSWARM_DESKTOP", "1")+ monkeypatch.delenv(CLI_PORTS_ENV_FLAG, raising=False)monkeypatch.setenv("AGENT_SERVER_PORT", "19092")monkeypatch.delenv("AGENT_SERVER_URL", raising=False)@@ -81,6 +87,7 @@ def test_load_dotenv_runtime_non_desktop_keeps_agent_server_url()monkeypatch.delenv("JIUWENSWARM_DESKTOP", raising=False)+ monkeypatch.delenv(CLI_PORTS_ENV_FLAG, raising=False)monkeypatch.delenv("AGENT_SERVER_URL", raising=False)load_dotenv_runtime(env_file, override=True)@@ -93,6 +100,7 @@ def test_load_dotenv_runtime_non_desktop_allows_override(tmp_path: Path, monkeypenv_file.write_text("WEB_PORT=11111\n", encoding="utf-8")monkeypatch.delenv("JIUWENSWARM_DESKTOP", raising=False)+ monkeypatch.delenv(CLI_PORTS_ENV_FLAG, raising=False)monkeypatch.setenv("WEB_PORT", "20000")load_dotenv_runtime(env_file, override=True)@@ -100,6 +108,60 @@ def test_load_dotenv_runtime_non_desktop_allows_override(tmp_path: Path, monkeypassert os.environ["WEB_PORT"] == "11111"+def test_load_dotenv_runtime_preserves_cli_ports(tmp_path: Path, monkeypatch):+ """Issue #2749: jiuwenswarm-start injected ports must beat stale .env.++ Scenario: a prior fallback left GATEWAY_PORT=20001 in .env, while this+ launch's banner / child env decided on index-0 defaults (19001). Without+ JIUWENSWARM_CLI_PORTS preservation, load_dotenv(override=True) would make+ Gateway bind 20001 while the start banner still prints 19001.+ """+ env_file = tmp_path / ".env"+ env_file.write_text(+ "WEB_PORT=11111\nGATEWAY_PORT=22222\nAGENT_SERVER_PORT=33333\nFRONTEND_PORT=44444\n"+ "AGENT_SERVER_URL=ws://127.0.0.1:18092\n",+ encoding="utf-8",+ )++ monkeypatch.delenv("JIUWENSWARM_DESKTOP", raising=False)+ monkeypatch.setenv(CLI_PORTS_ENV_FLAG, "1")+ monkeypatch.setenv("WEB_PORT", "19000")+ monkeypatch.setenv("GATEWAY_PORT", "19001")+ monkeypatch.setenv("AGENT_SERVER_PORT", "18092")+ monkeypatch.setenv("AGENT_PORT", "18092")+ monkeypatch.setenv("FRONTEND_PORT", "5173")+ monkeypatch.delenv("AGENT_SERVER_URL", raising=False)++ load_dotenv_runtime(env_file, override=True)++ assert os.environ["WEB_PORT"] == "19000"+ assert os.environ["GATEWAY_PORT"] == "19001"+ assert os.environ["AGENT_SERVER_PORT"] == "18092"+ assert os.environ["AGENT_PORT"] == "18092"+ assert os.environ["FRONTEND_PORT"] == "5173"+ assert "AGENT_SERVER_URL" not in os.environ+++def test_load_dotenv_runtime_cli_ports_drops_stale_agent_server_url(+ tmp_path: Path, monkeypatch+):+ env_file = tmp_path / ".env"+ env_file.write_text(+ "AGENT_SERVER_URL=ws://127.0.0.1:18092\nAGENT_SERVER_PORT=33333\n",+ encoding="utf-8",+ )++ monkeypatch.delenv("JIUWENSWARM_DESKTOP", raising=False)+ monkeypatch.setenv(CLI_PORTS_ENV_FLAG, "1")+ monkeypatch.setenv("AGENT_SERVER_PORT", "18092")+ monkeypatch.delenv("AGENT_SERVER_URL", raising=False)++ load_dotenv_runtime(env_file, override=True)++ assert os.environ["AGENT_SERVER_PORT"] == "18092"+ assert "AGENT_SERVER_URL" not in os.environ++def test_resolve_desktop_ports_uses_default_group(desktop_app, monkeypatch):default = calculate_instance_ports(0)monkeypatch.setattr(diff --git a/tests/unit_tests/test_instance_manager.py b/tests/unit_tests/test_instance_manager.pyindex 0a5f9f06ec..45522e3e3b 100644--- a/tests/unit_tests/test_instance_manager.py+++ b/tests/unit_tests/test_instance_manager.py@@ -235,6 +235,40 @@ class TestPortAvailability:# Small race window, but in practice the port is free immediately.assert is_port_available("127.0.0.1", port) is True+ @staticmethod+ def test_is_port_available_detects_ipv6_only_listener():+ """IPv6-only listeners must count as occupied for 127.0.0.1 probes.++ Vite on Windows often binds ``[::1]:5173`` only. An IPv4-only bind+ probe would miss it, skip jiuwenswarm-start's port-group fallback, and+ then Vite ``strictPort: true`` fails with "Port 5173 is already in use".+ """+ import socket as _socket+ import pytest++ s = None+ try:+ try:+ s = _socket.socket(_socket.AF_INET6, _socket.SOCK_STREAM)+ # Restrict to IPv6-only so we do not also claim IPv4 via dualstack.+ if hasattr(_socket, "IPV6_V6ONLY"):+ s.setsockopt(_socket.IPPROTO_IPV6, _socket.IPV6_V6ONLY, 1)+ s.bind(("::1", 0))+ s.listen(1)+ except OSError:+ # Must close before skip: an unbound AF_INET6 socket still+ # triggers ResourceWarning / PytestUnraisableExceptionWarning+ # on the next test's setup (seen on Linux CI without ::1).+ if s is not None:+ s.close()+ s = None+ pytest.skip("IPv6 loopback unavailable on this host")+ port = s.getsockname()[1]+ assert is_port_available("127.0.0.1", port) is False+ finally:+ if s is not None:+ s.close()+class TestInstanceConfig:"""Test InstanceConfig dataclass."""diff --git a/tests/unit_tests/test_start_services_ready_hint.py b/tests/unit_tests/test_start_services_ready_hint.pyindex c7fbbb43e1..e5f891ec74 100644--- a/tests/unit_tests/test_start_services_ready_hint.py+++ b/tests/unit_tests/test_start_services_ready_hint.py@@ -5,6 +5,7 @@from __future__ import annotationsimport logging+import osimport timefrom unittest.mock import MagicMock, patch@@ -86,6 +87,8 @@ def test_start_process_passes_resolved_ports_to_child(monkeypatch: pytest.MonkeyPatch,tmp_path,):+ from jiuwenswarm.dotenv_early import CLI_PORTS_ENV_FLAG+captured: dict[str, object] = {}def fake_popen(cmd, *, cwd, env):@@ -93,6 +96,7 @@ def test_start_process_passes_resolved_ports_to_child(return MagicMock()monkeypatch.setattr("jiuwenswarm.start_services.subprocess.Popen", fake_popen)+ monkeypatch.setenv("AGENT_SERVER_URL", "ws://127.0.0.1:18092")ports = {"agent_server": 19092,"web": 20000,@@ -104,10 +108,14 @@ def test_start_process_passes_resolved_ports_to_child(child_env = captured["env"]assert isinstance(child_env, dict)+ assert child_env[CLI_PORTS_ENV_FLAG] == "1"assert child_env["AGENT_SERVER_PORT"] == "19092"+ assert child_env["AGENT_PORT"] == "19092"assert child_env["WEB_PORT"] == "20000"assert child_env["GATEWAY_PORT"] == "20001"assert child_env["FRONTEND_PORT"] == "6173"+ # Stale URL from parent shell must not override the remapped agent port.+ assert "AGENT_SERVER_URL" not in child_envdef test_wait_for_services_ready_prints_access_url_for_web_dev(caplog: pytest.LogCaptureFixture):@@ -336,3 +344,58 @@ def test_process_death_ends_wait_early(caplog: pytest.LogCaptureFixture):assert "required process exited during startup wait" in joinedassert elapsed < 3.0assert "服务启动中,端口信息如下:" in joined+++def test_cli_injected_ports_survive_stale_dotenv_override(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+):+ """Issue #2749: banner ports and Gateway bind ports must stay aligned.++ jiuwenswarm-start injects index-0 defaults into the child env and prints+ them in the access banner, but app/gateway historically re-loaded a stale+ .env (GATEWAY_PORT=20001 from a prior fallback) with override=True and+ rebound to 20001. The CLI_PORTS flag must keep the injected group.+ """+ from jiuwenswarm.dotenv_early import CLI_PORTS_ENV_FLAG, load_dotenv_runtime++ captured: dict[str, object] = {}++ def fake_popen(cmd, *, cwd, env):+ captured["env"] = env+ return MagicMock()++ monkeypatch.setattr("jiuwenswarm.start_services.subprocess.Popen", fake_popen)++ banner_ports = {+ "agent_server": 18092,+ "web": 19000,+ "gateway": 19001,+ "frontend": 5173,+ }+ _start_process("app", ["python", "-m", "jiuwenswarm.app"], tmp_path, ports=banner_ports)++ child_env = captured["env"]+ assert isinstance(child_env, dict)++ # Simulate the child process environment after spawn.+ monkeypatch.delenv("JIUWENSWARM_DESKTOP", raising=False)+ for key, value in child_env.items():+ monkeypatch.setenv(key, value)++ stale_env = tmp_path / ".env"+ stale_env.write_text(+ "AGENT_SERVER_PORT=19092\n"+ "WEB_PORT=20000\n"+ "GATEWAY_PORT=20001\n"+ "FRONTEND_PORT=6173\n",+ encoding="utf-8",+ )++ load_dotenv_runtime(stale_env, override=True)++ assert os.environ.get(CLI_PORTS_ENV_FLAG) == "1"+ assert os.environ["GATEWAY_PORT"] == "19001"+ assert os.environ["WEB_PORT"] == "19000"+ assert os.environ["AGENT_SERVER_PORT"] == "18092"+ assert os.environ["FRONTEND_PORT"] == "5173"