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

fix:jiuwenswarm端口冲突自动辨别

openJiuwen-bota4e716b97083
diff --git a/docs/en/Quickstart.md b/docs/en/Quickstart.md
index 1c7efa1d80..76ec6c4206 100644
--- a/docs/en/Quickstart.md
+++ b/docs/en/Quickstart.md
@@ -58,6 +58,38 @@ After successful startup, the terminal will display backend service status:
When you see similar output, the service is ready. Open `http://localhost:5173` in your browser to use.
+### Automatic Port Conflict Resolution
+
+JiuWenSwarm uses a fixed set of default ports (`18092 / 19000 / 19001 / 5173`). If a port is already in use when starting (e.g. a previous run did not fully stop, or another app occupies it), the launcher **automatically scans upward for the next free port group** and uses it instead of failing:
+
+```
+[start_services] ⚠️ Original ports conflict. Falling back to alternative port group (index 1):
+[start_services] Using ports:
+ agent_server: 19092
+ web: 20000
+ gateway: 20001
+ frontend: 6173
+[start_services] TUI/CLI connect with:
+ jiuwenswarm-tui --url ws://127.0.0.1:20001/tui
+ jiuwenswarm chat (auto-reads GATEWAY_PORT)
+```
+
+The chosen ports are **persisted**, so the next launch and the TUI/CLI read them automatically — no need to memorize. If no free group is found within the scan range, the command prints conflict-resolution hints and exits.
+
+To **force specific ports**, two options:
+
+1. **Stop the occupying process**: `jiuwenswarm-start --stop default` (or `lsof -i :19001` on Linux/macOS; on Windows `netstat -ano | findstr :19001` then `taskkill /PID <pid> /F`).
+2. **Override base ports via env vars** (Docker / container-friendly):
+
+ ```bash
+ # Override base ports (index-0 starting ports; named instances add index×1000)
+ export JIUWENSWARM_GATEWAY_PORT=29001
+ export JIUWENSWARM_AGENT_SERVER_PORT=28092
+ export JIUWENSWARM_FRONTEND_PORT=15173
+ export JIUWENSWARM_WEB_PORT=29000
+ jiuwenswarm-start
+ ```
+
### Terminal CLI
You can also chat with JiuwenSwarm directly from the terminal:
diff --git a/docs/zh/Quickstart.md b/docs/zh/Quickstart.md
index a4878bf27a..f33facfcdf 100644
--- a/docs/zh/Quickstart.md
+++ b/docs/zh/Quickstart.md
@@ -58,6 +58,38 @@ jiuwenswarm-start
当看到类似上述提示时,表示服务已启动,在浏览器中访问 `http://localhost:5173` 即可使用。
+### 端口冲突自动处理
+
+JiuWenSwarm 默认使用一组固定端口(`18092 / 19000 / 19001 / 5173`)。若启动时检测到某端口已被占用(例如上一次未完全停止、或被其他应用占用),系统会**自动向上扫描相邻索引寻找可用的端口组**并使用,而不会直接退出:
+
+```
+[start_services] ⚠️ Original ports conflict. Falling back to alternative port group (index 1):
+[start_services] Using ports:
+ agent_server: 19092
+ web: 20000
+ gateway: 20001
+ frontend: 6173
+[start_services] TUI/CLI connect with:
+ jiuwenswarm-tui --url ws://127.0.0.1:20001/tui
+ jiuwenswarm chat (auto-reads GATEWAY_PORT)
+```
+
+选中的新端口会被**持久化**,下次启动和 TUI/CLI 都会自动读到,无需手动记忆。若整段扫描范围内仍无可用端口组,会打印占用排查命令并退出。
+
+如需**强制使用特定端口**,有两种方式:
+
+1. **停掉占用进程**:`jiuwenswarm-start --stop default`(Linux/Mac 可 `lsof -i :19001`,Windows 可 `netstat -ano | findstr :19001` 后 `taskkill /PID <pid> /F`)。
+2. **用环境变量覆盖 base 端口**(适合 Docker / 容器化部署):
+
+ ```bash
+ # 覆盖 base 端口(index 0 的起始端口,命名实例在其上 +index×1000)
+ export JIUWENSWARM_GATEWAY_PORT=29001
+ export JIUWENSWARM_AGENT_SERVER_PORT=28092
+ export JIUWENSWARM_FRONTEND_PORT=15173
+ export JIUWENSWARM_WEB_PORT=29000
+ jiuwenswarm-start
+ ```
+
### 终端 CLI
也可以直接在终端中与 JiuwenSwarm 对话:
diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
index b8ff677454..b79a0cb89f 100644
--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
@@ -45,6 +45,25 @@
| `--token <token>` | 鉴权令牌(若 Gateway 需要) | 空字符串 | `jiuwenswarm-cli --token YOUR_TOKEN` |
| `-h`, `--help` | 打印帮助并退出 | - | `jiuwenswarm-cli -h` |
+### 连接到非标准端口(端口冲突回退后)
+
+当后端启动时端口被占用,`jiuwenswarm-start` 会自动回退到相邻可用端口组(详见 [快速开始 · 端口冲突自动处理](Quickstart.md#端口冲突自动处理))。回退后新端口会被持久化,TUI / CLI 有两种连接方式:
+
+1. **自动读取**(推荐):`jiuwenswarm chat` 和 `jiuwenswarm-tui` 会自动从持久化的 `GATEWAY_PORT` 读取回退后的 Gateway 端口,无需任何参数。
+
+ ```bash
+ jiuwenswarm chat # 自动读 GATEWAY_PORT
+ jiuwenswarm-tui # 自动读 GATEWAY_PORT
+ ```
+
+2. **显式 `--url`**:若 TUI 未读到持久化端口(例如在另一台机器、或持久化文件被清理),按启动日志里的提示显式指定:
+
+ ```bash
+ jiuwenswarm-tui --url ws://127.0.0.1:20001/tui
+ ```
+
+ 启动后端时日志会打印实际的 Gateway 端口和对应的 `--url`,直接复制即可。
+
### 启动后界面
- **欢迎区**:ASCII 标题、版本、当前 Provider / Model / Mode;窄终端下为精简布局(`jiuwenswarm/cli/src/ui/welcome.ts`)。
diff --git a/jiuwenswarm/init_workspace.py b/jiuwenswarm/init_workspace.py
index bbd98ac307..ec2dccaa91 100644
--- a/jiuwenswarm/init_workspace.py
+++ b/jiuwenswarm/init_workspace.py
@@ -32,6 +32,9 @@ from jiuwenswarm.instance_manager import (
get_instance_workspace_path,
get_instance_index,
calculate_instance_ports,
+ find_available_ports,
+ is_port_available,
+ collect_all_ports,
update_instances_yaml,
validate_instance_name,
InstanceConfig,
@@ -100,6 +103,37 @@ def run_init(force: bool = False, name: Optional[str] = None) -> int:
index = get_instance_index(name)
ports = calculate_instance_ports(index)
+ # Proactively scan for a conflict-free port group so the instance is
+ # launchable immediately (otherwise the first jiuwenswarm-start --name
+ # would hit a port clash and have to fall back at start time). If the
+ # index's own group is fully available, keep it; otherwise scan upward.
+ conflict_ports = [
+ p for p in ports.values()
+ if not is_port_available("127.0.0.1", p)
+ ]
+ if conflict_ports:
+ # Exclude ports already claimed by other configured instances so
+ # the scan never picks a group that collides with a sibling.
+ exclude_ports = collect_all_ports(exclude_name=name)
+ found = find_available_ports(
+ base_index=index,
+ host="127.0.0.1",
+ scan_range=20,
+ exclude_ports=exclude_ports,
+ )
+ if found is None:
+ logging.info(
+ f"[jiuwenswarm-init] WARNING: No available port group within "
+ f"scan_range=20 (from index {index}). Falling back to index "
+ f"{index} ports; 'jiuwenswarm-start --name {name}' will retry."
+ )
+ else:
+ ports, index = found
+ logging.info(
+ f"[jiuwenswarm-init] Reserved conflict-free port group "
+ f"(index {index}) for instance '{name}': {ports}"
+ )
+
# Update YAML with full configuration (workspace + ports)
update_instances_yaml(name, workspace_path, ports)
diff --git a/jiuwenswarm/instance_manager/__init__.py b/jiuwenswarm/instance_manager/__init__.py
index 2eea7275bf..a2ddb5ca9b 100644
--- a/jiuwenswarm/instance_manager/__init__.py
+++ b/jiuwenswarm/instance_manager/__init__.py
@@ -49,7 +49,10 @@ from jiuwenswarm.instance_manager.config import (
check_port_conflicts,
collect_all_ports,
compute_auto_port,
+ find_available_ports,
is_port_available,
+ PORT_ENV_NAMES,
+ PORT_ENV_OVERRIDES,
)
# YAML management from yaml
@@ -117,6 +120,9 @@ __all__ = [
"is_port_available",
"check_port_conflicts",
"collect_all_ports",
+ "find_available_ports",
+ "PORT_ENV_NAMES",
+ "PORT_ENV_OVERRIDES",
# YAML management
"get_instances_yaml_path",
"get_instances_dir",
diff --git a/jiuwenswarm/instance_manager/config.py b/jiuwenswarm/instance_manager/config.py
index dbf9c65dcb..9d26d2c26b 100644
--- a/jiuwenswarm/instance_manager/config.py
+++ b/jiuwenswarm/instance_manager/config.py
@@ -126,6 +126,38 @@ def is_valid_instance_name(name: str) -> bool:
return validate_instance_name(name) is None
+# Environment variable names that override BASE_PORTS, enabling Docker /
+# container deployments and ad-hoc base-port customization. When unset,
+# behavior is identical to the historical fixed defaults (backward compatible).
+PORT_ENV_OVERRIDES = {
+ "agent_server": "JIUWENSWARM_AGENT_SERVER_PORT",
+ "web": "JIUWENSWARM_WEB_PORT",
+ "gateway": "JIUWENSWARM_GATEWAY_PORT",
+ "frontend": "JIUWENSWARM_FRONTEND_PORT",
+}
+
+
+def _resolved_base_port(port_type: str) -> int:
+ """Return the effective base port for a port type.
+
+ Honors ``JIUWENSWARM_<TYPE>_PORT`` env-var overrides (Phase 2 / Docker),
+ falling back to the static ``BASE_PORTS`` default. Malformed env values are
+ ignored with a debug log so a typo never breaks startup.
+ """
+ env_key = PORT_ENV_OVERRIDES.get(port_type)
+ if env_key:
+ raw = os.getenv(env_key)
+ if raw:
+ try:
+ return int(raw)
+ except ValueError:
+ logger.debug(
+ "Ignoring invalid %s=%r (not an int), using default",
+ env_key, raw,
+ )
+ return BASE_PORTS.get(port_type, 10000)
+
+
def compute_auto_port(port_type: str, index: int) -> int:
"""Compute auto-allocated port for an instance.
@@ -133,6 +165,10 @@ def compute_auto_port(port_type: str, index: int) -> int:
- index 0 reserved for default instance
- Named instances start from index 1
+ The base_port honors ``JIUWENSWARM_<TYPE>_PORT`` env-var overrides
+ (see ``PORT_ENV_OVERRIDES``); when unset the historical fixed default is
+ used, so existing deployments are unaffected.
+
Args:
port_type: Service type (agent_server, web, gateway, frontend)
index: Instance index (0 for default, 1+ for named)
@@ -140,32 +176,58 @@ def compute_auto_port(port_type: str, index: int) -> int:
Returns:
Computed port number
"""
- base = BASE_PORTS.get(port_type, 10000)
- return base + index * 1000
+ return _resolved_base_port(port_type) + index * 1000
def calculate_instance_ports(index: int) -> Dict[str, int]:
- """Calculate ports for an instance: base_port + index * 1000."""
- return {k: v + index * 1000 for k, v in BASE_PORTS.items()}
+ """Calculate ports for an instance: base_port + index * 1000.
+
+ Base ports honor env-var overrides (see ``compute_auto_port``).
+ """
+ return {k: _resolved_base_port(k) + index * 1000 for k in BASE_PORTS}
def is_port_available(host: str, port: int) -> bool:
- """Check if a port is available on the given host.
+ """Check if a port is available for binding on the given host.
+
+ Probes by attempting to ``bind()``+``listen()`` (without SO_REUSEADDR) and
+ immediately closing. This mirrors how the real services (AgentServer /
+ Gateway / Web / Frontend) actually acquire their ports, so it correctly
+ detects:
+
+ - A live service listening on the port (bind fails -> occupied).
+ - A *stuck/zombie* listener that is in LISTENING state but no longer
+ accept()ing connections (connect()-based probes falsely report these as
+ free because the connect times out, but bind() still fails).
+
+ Earlier connect()-based probes mis-detected stuck listeners as available,
+ which made the fallback logic pick an index whose ports were actually
+ held by a dead-but-listening socket, causing the real service to crash
+ with ``OSError [Errno 10048]`` on its own bind.
Args:
host: Host address to check
port: Port number to check
Returns:
- True if port is available, False if occupied
+ True if the port can be bound (available), False if occupied.
"""
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
- sock.settimeout(0.5)
+ 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.connect((host, port))
- return False # Port is occupied
+ sock.close()
except OSError:
- return True # Port is available
+ pass
def check_port_conflicts(
@@ -262,4 +324,123 @@ def _get_system_executable(name: str) -> str:
return exe_path
# Fallback to shutil.which for cross-platform resolution
resolved = shutil.which(name)
- return resolved or name
\ No newline at end of file
+ return resolved or name
+
+
+# Port-type to bootstrap .env variable name mapping. Kept here (next to the
+# port allocation logic) so fallback persistence and bootstrap .env creation
+# stay in sync. Must match jiuwenswarm/instance_manager/bootstrap.py.
+PORT_ENV_NAMES = {
+ "agent_server": "AGENT_SERVER_PORT",
+ "web": "WEB_PORT",
+ "gateway": "GATEWAY_PORT",
+ "frontend": "FRONTEND_PORT",
+}
+
+
+def find_available_ports(
+ base_index: int = 0,
+ host: str = "127.0.0.1",
+ scan_range: int = 10,
+ exclude_ports: Optional[Sequence[int]] = None,
+) -> Optional[tuple]:
+ """Scan upward for the first fully-available port group.
+
+ Starting at ``base_index``, walks ``scan_range`` consecutive instance
+ indices. For each index it computes the full 4-port group via
+ ``calculate_instance_ports``; the group is usable only when *every* port
+ is available on ``host`` AND not in ``exclude_ports`` (ports already
+ claimed by other live instances).
+
+ Args:
+ base_index: Instance index to start scanning from (typically the
+ instance's own index).
+ host: Host address to probe.
+ scan_range: Number of consecutive indices to try.
+ exclude_ports: Ports to treat as occupied regardless of probe result
+ (avoids colliding with other configured instances).
+
+ Returns:
+ ``(ports_dict, actual_index)`` for the first usable group, or ``None``
+ if the entire scan range is exhausted.
+ """
+ exclude_set = set(exclude_ports or [])
+
+ # scan_range=0 means "scan nothing" → immediately None. (Previously this
+ # was clamped via max(1, scan_range), which silently scanned one index
+ # even when the caller asked for zero — making the exhausted-range error
+ # message in start_services.py ("scanned indices base..base+range-1")
+ # describe a range that did not match what was actually scanned.)
+ for offset in range(scan_range):
+ index = base_index + offset
+ candidate = calculate_instance_ports(index)
+
+ if all(
+ p not in exclude_set and is_port_available(host, p)
+ for p in candidate.values()
+ ):
+ return candidate, index
+
+ return None
+
+
+def _upsert_env_ports(
+ env_path: Path,
+ ports: Dict[str, int],
+) -> None:
+ """Idempotently write port assignments into a .env file.
+
+ For each port type in ``PORT_ENV_NAMES``: if a ``KEY=...`` line exists it
+ is replaced in place, otherwise the line is appended. All other lines
+ (API keys, model config, etc.) are preserved untouched. Creates the file
+ if missing.
+
+ This is the persistence mechanism for the default instance (whose ports
+ are read from ``~/.jiuwenswarm/config/.env`` via ``app.py``'s
+ ``load_dotenv(get_env_file(), override=True)``). Named instances persist
+ via ``instances.yaml`` + ``create_bootstrap_env`` instead.
+ """
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+
+ target_keys = {env_name: str(ports[pt]) for pt, env_name in PORT_ENV_NAMES.items() if pt in ports}
+
+ lines: List[str] = []
+ if env_path.exists():
+ lines = env_path.read_text(encoding="utf-8").splitlines()
+
+ seen: set = set()
+ updated: List[str] = []
+ for line in lines:
+ stripped = line.lstrip()
+ if "=" in stripped and not stripped.startswith("#"):
+ key = stripped.split("=", 1)[0].strip()
+ if key in target_keys:
+ updated.append(f"{key}={target_keys[key]}")
+ seen.add(key)
+ continue
+ updated.append(line)
+
+ # Append any port keys not already present in the file
+ for key, val in target_keys.items():
+ if key not in seen:
+ updated.append(f"{key}={val}")
+
+ env_path.write_text("\n".join(updated) + "\n", encoding="utf-8")
+ logger.debug("Upserted port env vars into %s: %s", env_path, list(target_keys))
+
+
+def _format_url_hint(ports: Dict[str, int]) -> str:
+ """Build the TUI/CLI connection hint shown after a port fallback.
+
+ Emits ``jiuwenswarm-tui --url ...`` (explicit, works even if the TUI cannot
+ read the persisted GATEWAY_PORT) and ``jiuwenswarm chat`` (which reads
+ GATEWAY_PORT from the loaded .env automatically). Returns a multi-line
+ string without a trailing newline.
+ """
+ gateway_port = ports.get("gateway", 0)
+ lines = [
+ "[start_services] TUI/CLI connect with:",
+ f" jiuwenswarm-tui --url ws://127.0.0.1:{gateway_port}/tui",
+ " jiuwenswarm chat (auto-reads GATEWAY_PORT)",
+ ]
+ return "\n".join(lines)
\ No newline at end of file
diff --git a/jiuwenswarm/instance_manager/yaml.py b/jiuwenswarm/instance_manager/yaml.py
index aa420d7df2..d273e41ddc 100644
--- a/jiuwenswarm/instance_manager/yaml.py
+++ b/jiuwenswarm/instance_manager/yaml.py
@@ -219,11 +219,39 @@ def load_instances_yaml() -> dict:
def save_instances_yaml(data: dict) -> None:
- """Save instances.yaml file."""
+ """Save instances.yaml file atomically.
+
+ Writes to a sibling temp file then ``os.replace`` swaps it into place.
+ This avoids a partially-written (corrupt) instances.yaml if the process
+ is interrupted mid-write, and narrows the read-modify-write race window
+ when two named instances start concurrently and both call
+ ``update_instances_yaml``: a reader can never observe a half-written
+ file. (Interleaved writes from two concurrent updaters can still lose
+ one update — that's guarded per-instance by ``InstanceLock``; this
+ function guarantees the file is never left corrupted.)
+ """
+ import os
+ import tempfile
+
path = get_instances_yaml_path()
path.parent.mkdir(parents=True, exist_ok=True)
- with open(path, 'w', encoding='utf-8') as f:
- yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True)
+
+ # Write to a temp file in the SAME directory (so os.replace is atomic
+ # on POSIX and a same-volume rename on Windows).
+ fd, tmp_name = tempfile.mkstemp(
+ prefix=".instances.", suffix=".tmp", dir=str(path.parent)
+ )
+ try:
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True)
+ os.replace(tmp_name, path)
+ except Exception:
+ # Clean up the orphan temp file on any failure; never leave it behind.
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
def create_instances_yaml_template() -> Path:
diff --git a/jiuwenswarm/start_services.py b/jiuwenswarm/start_services.py
index d6beabd4b7..b0f7dac66f 100644
--- a/jiuwenswarm/start_services.py
+++ b/jiuwenswarm/start_services.py
@@ -28,13 +28,14 @@ from jiuwenswarm.dotenv_early import parse_dotenv_early
parse_dotenv_early("jiuwenswarm-start")
# --- Now safe to import jiuwenswarm modules ---
-from jiuwenswarm.common.utils import get_root_dir, get_user_workspace_dir, is_package_installation
+from jiuwenswarm.common.utils import get_env_file, get_root_dir, get_user_workspace_dir, is_package_installation
from jiuwenswarm.instance_manager import (
InstanceConfig,
InstanceLock,
InstanceStatus,
calculate_instance_ports,
create_bootstrap_env,
+ find_available_ports,
format_status_line,
get_default_instance_status,
get_instance_config,
@@ -46,6 +47,7 @@ from jiuwenswarm.instance_manager import (
validate_instance_name,
write_pid_file,
PORT_TYPES,
+ PORT_ENV_NAMES,
compute_auto_port,
)
@@ -155,11 +157,29 @@ class InstanceCommand:
Returns:
Error code if port conflicts, None if all ports available.
"""
- if self.config is None:
+ conflicts = self.check_ports_conflicts()
+ if conflicts:
+ logging.info("[start_services] ERROR: Port conflicts detected, cannot start instance.")
return 1
+ return None
+
+ def check_ports_conflicts(self) -> list[tuple[str, int]]:
+ """Check all instance ports and return the list of conflicts.
+
+ Unlike ``check_ports_available`` (which returns an exit code), this
+ returns the structured conflict list so callers (e.g. the fallback
+ path) can decide whether to scan for alternative ports.
+
+ Returns:
+ List of ``(port_type, port)`` tuples that are already in use.
+ Empty list if all ports are available.
+ """
+ if self.config is None:
+ return []
+
logging.info(f"[start_services] Checking ports for instance '{self.name}'...")
- conflicts = []
+ conflicts: list[tuple[str, int]] = []
for port_type, port in self.config.ports.items():
if not is_port_available("127.0.0.1", port):
@@ -168,11 +188,7 @@ class InstanceCommand:
else:
logging.info(f" ✓ {port_type}: {port} - available")
- if conflicts:
- logging.info("[start_services] ERROR: Port conflicts detected, cannot start instance.")
- return 1
-
- return None
+ return conflicts
def print_instance_details(status: InstanceStatus) -> None:
@@ -197,6 +213,170 @@ def print_instance_details(status: InstanceStatus) -> None:
logging.info(f"Started at: {started_dt.isoformat()}")
+def _log_port_table(prefix: str, ports: dict[str, int]) -> None:
+ """Log a port table with the given prefix line."""
+ logging.info(prefix)
+ for port_type in PORT_TYPES:
+ logging.info(f" {port_type}: {ports.get(port_type, 0)}")
+
+
+def _resolve_ports_with_fallback(cmd: InstanceCommand, scan_range: int = 10) -> int | None:
+ """Resolve port conflicts by scanning for an available port group.
+
+ Called when ``cmd.check_ports_conflicts()`` is non-empty. Scans upward from
+ the instance's own index (0 for default) for the first fully-available
+ group that does not collide with other configured instances. On success:
+
+ - Updates ``cmd.config.ports`` in place so downstream launch uses them.
+ - Persists the resolved ports:
+ * Named instance → ``instances.yaml`` (via ``update_instances_yaml``)
+ + bootstrap ``.env`` (via ``create_bootstrap_env``), so the next
+ ``jiuwenswarm-start --name <n>`` and the spawned subprocesses both
+ read the new ports.
+ * Default instance → ``~/.jiuwenswarm/config/.env`` (via
+ ``_upsert_env_ports``), which ``app.py`` loads with
+ ``override=True`` so the default-instance subprocesses and the TUI /
+ CLI (which read ``GATEWAY_PORT``) pick them up automatically.
+ - Emits a warning + the new port table + a TUI/CLI connection hint.
+
+ Returns:
+ ``None`` on success (ports resolved and persisted), ``1`` if no
+ available group was found within ``scan_range``.
+ """
+ # Local imports to avoid any circular dependency at module load time.
+ from jiuwenswarm.instance_manager import (
+ collect_all_ports,
+ get_instance_index,
+ update_instances_yaml,
+ )
+ from jiuwenswarm.instance_manager.config import (
+ _format_url_hint,
+ _upsert_env_ports,
+ )
+
+ if cmd.config is None:
+ return 1
+
+ # Determine the scan starting index: the instance's own declared index.
+ if cmd.is_default:
+ base_index = 0
+ else:
+ base_index = get_instance_index(cmd.name)
+
+ # Exclude ports already claimed by OTHER instances so fallback never
+ # silently collides with a running sibling.
+ exclude_ports = collect_all_ports(exclude_name="default" if cmd.is_default else cmd.name)
+
+ result = find_available_ports(
+ base_index=base_index,
+ host="127.0.0.1",
+ scan_range=scan_range,
+ exclude_ports=exclude_ports,
+ )
+
+ if result is None:
+ logging.info(
+ f"[start_services] ERROR: No available port group within scan_range={scan_range} "
+ f"(scanned indices {base_index}..{base_index + scan_range - 1})."
+ )
+ # Tailor the stop command and the port-inspection command to the
+ # actual instance name and host platform so the hint is actionable.
+ import platform as _platform
+ stop_hint = f"jiuwenswarm-start --stop {cmd.name}"
+ if _platform.system().lower() == "windows":
+ port_hint = "netstat -ano | findstr :<port> (then taskkill /PID <pid> /F)"
+ else:
+ port_hint = "lsof -i :<port> (or: ss -ltnp | grep <port>)"
+ logging.info(
+ f"[start_services] Suggestions: stop the occupying instance ({stop_hint}), "
+ f"find the holder ({port_hint}), increase scan_range, "
+ f"or set JIUWENSWARM_<TYPE>_PORT env vars to move the base."
+ )
+ return 1
+
+ alt_ports, actual_idx = result
+ logging.info(
+ f"[start_services] ⚠️ Original ports conflict. "
+ f"Falling back to alternative port group (index {actual_idx}):"
+ )
+ _log_port_table("[start_services] Using ports:", alt_ports)
+
+ # Mutate the in-memory config so _build_commands / _wait_for_services_ready
+ # and the PID file reflect the resolved ports.
+ cmd.config = InstanceConfig(
+ name=cmd.config.name,
+ workspace=cmd.config.workspace,
+ ports=alt_ports,
+ )
+
+ # Persist so subprocesses + next launch + TUI/CLI all see the new ports.
+ # Failure to persist is FATAL for the launch: subprocesses read the ports
+ # from .env (default instance via app.py's load_dotenv) or from the
+ # bootstrap .env (named instance via --dotenv). If we write neither, the
+ # spawned subprocesses still see the OLD conflicting ports and crash with
+ # OSError [Errno 10048] on bind. So we must surface this to the caller as a
+ # hard failure (return 1) rather than silently proceeding.
+ persist_where = (
+ f"{get_env_file()}" if cmd.is_default
+ else f"instances.yaml + {cmd.config.get_bootstrap_env_path()}"
+ )
+ try:
+ if cmd.is_default:
+ _upsert_env_ports(get_env_file(), alt_ports)
+ else:
+ update_instances_yaml(cmd.name, cmd.config.workspace, alt_ports)
+ create_bootstrap_env(cmd.config)
+ except Exception as exc:
+ logging.info(
+ f"[start_services] ERROR: Failed to persist fallback ports to {persist_where}: {exc}"
+ )
+ logging.info(
+ "[start_services] Aborting: subprocesses would read the old (conflicting) "
+ "ports and crash on bind. Free up the port file location, fix permissions, "
+ "then retry."
+ )
+ return 1
+
+ logging.info(_format_url_hint(alt_ports))
+ return None
+
+
+def _sync_default_env_ports(ports: dict[str, int]) -> int | None:
+ """Sync the default instance's actual ports into ~/.jiuwenswarm/config/.env.
+
+ The default instance has no bootstrap .env; its subprocesses read ports
+ from ``~/.jiuwenswarm/config/.env`` via ``app.py``'s
+ ``load_dotenv(get_env_file(), override=True)``. So .env must ALWAYS
+ reflect the ports this launch actually uses — not just when a fallback
+ happened. Otherwise a previous fallback's ports (e.g. GATEWAY_PORT=20001)
+ linger in .env, and a later no-conflict launch silently binds the
+ subprocesses to 20001 instead of the default 19001.
+
+ Call this on EVERY default-instance launch path, with the ports actually
+ being used (index-0 defaults when no conflict, or the fallback group when
+ a conflict was resolved). Persistence failure is fatal (returns 1) for the
+ same reason as in ``_resolve_ports_with_fallback``: subprocesses would
+ otherwise read stale ports and crash on bind.
+
+ Returns:
+ None on success, 1 if persistence failed.
+ """
+ from jiuwenswarm.instance_manager.config import _upsert_env_ports
+
+ try:
+ _upsert_env_ports(get_env_file(), ports)
+ except Exception as exc: # pragma: no cover - defensive
+ logging.info(
+ f"[start_services] ERROR: Failed to sync ports to {get_env_file()}: {exc}"
+ )
+ logging.info(
+ "[start_services] Aborting: subprocesses would read stale ports and "
+ "crash on bind. Fix the .env location/permissions, then retry."
+ )
+ return 1
+ return None
+
+
def do_stop_instance(cmd: InstanceCommand) -> int:
"""Execute stop operation for an instance.
@@ -396,7 +576,33 @@ def _run_processes(commands: list[tuple[str, list[str], Path]]) -> int:
def _run(mode: str) -> int:
- """Run default instance (existing behavior)."""
+ """Run default instance.
+
+ Unlike named instances, the default instance has no bootstrap .env and no
+ instances.yaml entry — its ports come from code defaults (or env-var
+ overrides) and are read by subprocesses via ``app.py``'s
+ ``load_dotenv(get_env_file(), override=True)``. So on port conflict we
+ probe the default port group, fall back to a free group, and persist the
+ resolved ports into ``~/.jiuwenswarm/config/.env``; the spawned app/web
+ subprocesses and the TUI/CLI (which read ``GATEWAY_PORT``) then pick them
+ up automatically without any --dotenv plumbing.
+ """
+ cmd = InstanceCommand("default")
+ if cmd.validate_and_load():
+ return 1
+
+ if cmd.check_ports_conflicts():
+ if _resolve_ports_with_fallback(cmd) is not None:
+ return 1
+ # Fallback already persisted the resolved ports to .env.
+ else:
+ # No conflict: ensure .env reflects the index-0 defaults so a
+ # PREVIOUS fallback's ports (e.g. GATEWAY_PORT=20001) don't linger
+ # and make this launch's subprocesses bind stale ports. This is the
+ # "first-conflict-then-no-conflict" residue path.
+ if _sync_default_env_ports(cmd.config.ports) is not None:
+ return 1
+
commands = _build_commands(mode)
if not commands:
logging.info(f"[start_services] no commands to run for mode: {mode}")
@@ -530,8 +736,13 @@ def _start_named_instance(name: str, mode: str) -> int:
if cmd.check_running():
logging.info(f"[start_services] ERROR: Instance '{cmd.name}' is already running (PID={cmd.status.pid})")
return 1
- if cmd.check_ports_available():
- return 1
+
+ # Port availability: on conflict, try to fall back to a free port group
+ # (persists to instances.yaml + bootstrap .env so subprocesses/TUI/CLI
+ # pick up the new ports). Only hard-fail if no fallback is possible.
+ if cmd.check_ports_conflicts():
+ if _resolve_ports_with_fallback(cmd) is not None:
+ return 1
config = cmd.config
if config is None:
diff --git a/tests/unit_tests/test_instance_manager.py b/tests/unit_tests/test_instance_manager.py
index af4b5f7003..9a2f1d0f75 100644
--- a/tests/unit_tests/test_instance_manager.py
+++ b/tests/unit_tests/test_instance_manager.py
@@ -33,10 +33,12 @@ from jiuwenswarm.instance_manager import (
calculate_instance_ports,
check_port_conflicts,
collect_all_ports,
+ find_available_ports,
write_pid_file,
read_pid_file,
delete_pid_file,
is_process_alive,
+ is_port_available,
get_instance_status,
get_default_instance_status,
list_all_instances,
@@ -54,8 +56,14 @@ from jiuwenswarm.instance_manager import (
RESERVED_NAMES,
PORT_TYPES,
BASE_PORTS,
+ PORT_ENV_NAMES,
+ PORT_ENV_OVERRIDES,
STALE_LOCK_TIMEOUT,
)
+from jiuwenswarm.instance_manager.config import (
+ _format_url_hint,
+ _upsert_env_ports,
+)
# Module-level helper function for multiprocessing (must be at module level to be pickleable)
@@ -194,6 +202,39 @@ class TestPortAvailability:
conflicts = check_port_conflicts(ports, "127.0.0.1", existing)
assert 19092 in conflicts
+ @staticmethod
+ def test_is_port_available_detects_live_listener(tmp_path):
+ """A port held by a real bind()+listen() is reported as occupied.
+
+ Regression guard: the old connect()-based probe timed out against a
+ stuck/zombie listener (LISTENING but not accept()ing) and falsely
+ reported it as free, which made the fallback pick an index whose
+ ports were actually held and the real service crashed with
+ OSError [Errno 10048] on bind. The bind()-based probe detects this.
+ """
+ import socket as _socket
+ # Pick an ephemeral port the OS hands us, then hold it.
+ s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+ s.listen(1)
+ try:
+ assert is_port_available("127.0.0.1", port) is False
+ finally:
+ s.close()
+
+ @staticmethod
+ def test_is_port_available_true_when_free(tmp_path):
+ """A genuinely free ephemeral port is reported as available."""
+ import socket as _socket
+ # Grab an ephemeral port, release it, then probe — it should be free.
+ s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+ s.close()
+ # Small race window, but in practice the port is free immediately.
+ assert is_port_available("127.0.0.1", port) is True
+
class TestInstanceConfig:
"""Test InstanceConfig dataclass."""
@@ -408,6 +449,29 @@ class TestInstancesYaml:
assert "bob" in loaded["instances"]
assert loaded["instances"]["bob"]["ports"]["agent_server"] == 28092
+ @staticmethod
+ def test_save_is_atomic_and_leaves_no_temp_residue(tmp_path):
+ """save_instances_yaml writes atomically and cleans up its temp file.
+
+ Regression guard for the concurrent-named-instance write race: the
+ file must never be observed half-written, and the sibling ``.tmp``
+ temp file must not be left behind after a successful save.
+ """
+ yaml_path = tmp_path / "instances.yaml"
+ with patch(
+ "jiuwenswarm.instance_manager.yaml.get_instances_yaml_path",
+ return_value=yaml_path,
+ ):
+ save_instances_yaml({"instances": {"alice": {"ports": {"gateway": 21001}}}})
+
+ # File is complete and loadable.
+ loaded = load_instances_yaml()
+ assert loaded["instances"]["alice"]["ports"]["gateway"] == 21001
+
+ # No leftover temp files in the same directory.
+ leftovers = [p.name for p in tmp_path.iterdir() if p.name != "instances.yaml"]
+ assert leftovers == [], f"temp residue left behind: {leftovers}"
+
class TestGetInstanceConfig:
"""Test instance config loading."""
@@ -835,3 +899,456 @@ class TestInstanceLock:
# Clean up
first_lock.release()
+
+
+class TestPortFallback:
+ """Test find_available_ports() conflict-fallback scanning."""
+
+ @staticmethod
+ def test_returns_own_index_when_free(monkeypatch):
+ """When the base index group is fully free, it is returned as-is."""
+ ports_at = lambda idx: calculate_instance_ports(idx)
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available",
+ lambda host, port: True,
+ )
+ result = find_available_ports(base_index=0, scan_range=5)
+ assert result is not None
+ ports, idx = result
+ assert idx == 0
+ assert ports == ports_at(0)
+
+ @staticmethod
+ def test_skips_occupied_index(monkeypatch):
+ """When index 1 group is occupied, returns index 2."""
+ occupied = set(calculate_instance_ports(1).values())
+
+ def fake(host, port):
+ return port not in occupied
+
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available", fake
+ )
+ result = find_available_ports(base_index=1, scan_range=5)
+ assert result is not None
+ ports, idx = result
+ assert idx == 2
+ assert ports == calculate_instance_ports(2)
+
+ @staticmethod
+ def test_returns_none_when_range_exhausted(monkeypatch):
+ """Returns None when every index in range has a conflict."""
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available",
+ lambda host, port: False,
+ )
+ result = find_available_ports(base_index=0, scan_range=3)
+ assert result is None
+
+ @staticmethod
+ def test_scan_range_zero_scans_nothing(monkeypatch):
+ """scan_range=0 means scan nothing → None immediately.
+
+ Regression guard: previously the loop was ``range(max(1, scan_range))``
+ which silently scanned ONE index even when the caller asked for zero,
+ making the exhausted-range error message in start_services.py describe
+ a range that did not match what was actually scanned.
+ """
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available",
+ lambda host, port: True, # all free, but range is 0
+ )
+ result = find_available_ports(base_index=5, scan_range=0)
+ assert result is None
+
+ @staticmethod
+ def test_exclude_ports_treated_as_occupied(monkeypatch):
+ """Ports in exclude_ports are skipped even if probe says free."""
+ occupied = calculate_instance_ports(0)
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available",
+ lambda host, port: True,
+ )
+ result = find_available_ports(
+ base_index=0,
+ scan_range=5,
+ exclude_ports=list(occupied.values()),
+ )
+ assert result is not None
+ _, idx = result
+ assert idx == 1 # index 0 fully excluded -> next group
+
+
+class TestEnvVarOverride:
+ """Test Phase 2 env-var base-port override (Docker-friendly)."""
+
+ @staticmethod
+ def test_no_env_vars_keeps_defaults(monkeypatch):
+ """Without env vars, behavior is identical to BASE_PORTS."""
+ for key in PORT_ENV_OVERRIDES.values():
+ monkeypatch.delenv(key, raising=False)
+ assert compute_auto_port("gateway", 0) == 19001
+ assert calculate_instance_ports(0)["frontend"] == 5173
+
+ @staticmethod
+ def test_env_var_overrides_base(monkeypatch):
+ """JIUWENSWARM_<TYPE>_PORT overrides the base port for that type only."""
+ monkeypatch.setenv("JIUWENSWARM_GATEWAY_PORT", "29001")
+ monkeypatch.setenv("JIUWENSWARM_FRONTEND_PORT", "15173")
+ try:
+ assert compute_auto_port("gateway", 0) == 29001
+ assert compute_auto_port("gateway", 2) == 29001 + 2000
+ ports = calculate_instance_ports(0)
+ assert ports["gateway"] == 29001
+ assert ports["frontend"] == 15173
+ # Unset types keep defaults
+ assert ports["agent_server"] == 18092
+ assert ports["web"] == 19000
+ finally:
+ monkeypatch.delenv("JIUWENSWARM_GATEWAY_PORT", raising=False)
+ monkeypatch.delenv("JIUWENSWARM_FRONTEND_PORT", raising=False)
+
+ @staticmethod
+ def test_invalid_env_var_ignored(monkeypatch):
+ """Malformed env value falls back to default (no crash)."""
+ monkeypatch.setenv("JIUWENSWARM_GATEWAY_PORT", "not-a-number")
+ try:
+ assert compute_auto_port("gateway", 0) == 19001
+ finally:
+ monkeypatch.delenv("JIUWENSWARM_GATEWAY_PORT", raising=False)
+
+
+class TestUpsertEnvPorts:
+ """Test _upsert_env_ports() persistence for the default instance."""
+
+ @staticmethod
+ def test_append_to_empty_file(tmp_path):
+ env_path = tmp_path / ".env"
+ ports = {"agent_server": 19092, "web": 20000, "gateway": 20001, "frontend": 6173}
+ _upsert_env_ports(env_path, ports)
+ txt = env_path.read_text()
+ assert "AGENT_SERVER_PORT=19092" in txt
+ assert "GATEWAY_PORT=20001" in txt
+ assert "FRONTEND_PORT=6173" in txt
+
+ @staticmethod
+ def test_replace_existing_preserves_others(tmp_path):
+ env_path = tmp_path / ".env"
+ env_path.write_text(
+ "API_KEY=sk-keep\nGATEWAY_PORT=19001\nMODEL_NAME=m\n",
+ encoding="utf-8",
+ )
+ ports = {"agent_server": 19092, "web": 20000, "gateway": 20001, "frontend": 6173}
+ _upsert_env_ports(env_path, ports)
+ txt = env_path.read_text()
+ assert "API_KEY=sk-keep" in txt
+ assert "MODEL_NAME=m" in txt
+ assert "GATEWAY_PORT=20001" in txt
+ assert "GATEWAY_PORT=19001" not in txt
+ assert "AGENT_SERVER_PORT=19092" in txt
+
+ @staticmethod
+ def test_idempotent(tmp_path):
+ env_path = tmp_path / ".env"
+ ports = {"agent_server": 19092, "web": 20000, "gateway": 20001, "frontend": 6173}
+ _upsert_env_ports(env_path, ports)
+ before = env_path.read_text()
+ _upsert_env_ports(env_path, ports)
+ assert env_path.read_text() == before
+
+ @staticmethod
+ def test_comment_lines_preserved(tmp_path):
+ """A commented-out port line must not be replaced; a real line is appended."""
+ env_path = tmp_path / ".env"
+ env_path.write_text("# GATEWAY_PORT=9999\nAPI_KEY=x\n", encoding="utf-8")
+ _upsert_env_ports(env_path, {"gateway": 20001})
+ lines = env_path.read_text().splitlines()
+ assert "# GATEWAY_PORT=9999" in lines
+ assert any(l == "GATEWAY_PORT=20001" for l in lines)
+
+
+class TestFormatUrlHint:
+ """Test _format_url_hint() output."""
+
+ @staticmethod
+ def test_hint_contains_gateway_port():
+ hint = _format_url_hint({"gateway": 20001})
+ assert "jiuwenswarm-tui --url ws://127.0.0.1:20001/tui" in hint
+ assert "jiuwenswarm chat" in hint
+
+ @staticmethod
+ def test_hint_handles_missing_gateway():
+ """Missing gateway port still formats (uses 0 placeholder)."""
+ hint = _format_url_hint({})
+ assert "ws://127.0.0.1:0/tui" in hint
+
+
+class TestStartServicesFallback:
+ """Test start_services._resolve_ports_with_fallback() integration.
+
+ Covers the named-instance path (persists to instances.yaml + bootstrap .env)
+ and the default-instance path (persists to ~/.jiuwenswarm/config/.env).
+ """
+
+ @staticmethod
+ def test_named_instance_fallback_persists(tmp_path, monkeypatch):
+ """Named instance: index-1 conflict → fallback to index-2, persisted."""
+ import yaml
+ from jiuwenswarm import start_services
+
+ # Isolate instances.yaml / workspaces into tmp_path by patching the
+ # path resolvers directly (env-var-based resolution is cached at module
+ # import time, which is unreliable across tests in one process).
+ yaml_path = tmp_path / "instances.yaml"
+ ws = tmp_path / "alice"
+ ws.mkdir()
+ yaml_path.write_text(
+ f"instances:\n alice:\n workspace: {ws}\n", encoding="utf-8"
+ )
+
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.yaml.get_instances_yaml_path",
+ lambda: yaml_path,
+ )
+ # Workspace path resolver must also point at tmp_path for bootstrap .env.
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.yaml.get_instance_workspace_path",
+ lambda name: tmp_path / name,
+ )
+
+ cmd = start_services.InstanceCommand("alice")
+ assert cmd.validate_and_load() is None
+ orig = dict(cmd.config.ports)
+ assert orig["gateway"] == 20001 # index 1
+
+ # Make index-1 group occupied; everything else free
+ occupied = set(calculate_instance_ports(1).values())
+ real = is_port_available
+
+ def fake(host, port):
+ return port not in occupied and real(host, port)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available", fake
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services.is_port_available", fake
+ )
+
+ rc = start_services._resolve_ports_with_fallback(cmd)
+ assert rc is None # success
+ assert cmd.config.ports["agent_server"] == 20092 # index 2
+ assert cmd.config.ports["gateway"] == 21001
+
+ # yaml persisted with new ports
+ data = yaml.safe_load(yaml_path.read_text())
+ assert data["instances"]["alice"]["ports"]["gateway"] == 21001
+
+ # bootstrap .env persisted
+ benv = ws / ".env"
+ assert benv.exists()
+ assert "GATEWAY_PORT=21001" in benv.read_text()
+
+ @staticmethod
+ def test_default_instance_fallback_persists_to_env(tmp_path, monkeypatch):
+ """Default instance: conflict → fallback, persisted to config/.env."""
+ from jiuwenswarm import start_services
+
+ # Patch get_env_file (used by start_services) to a tmp path so the
+ # test never touches the real ~/.jiuwenswarm/config/.env.
+ cfg_env = tmp_path / "config" / ".env"
+ cfg_env.parent.mkdir(parents=True, exist_ok=True)
+ cfg_env.write_text("API_KEY=sk-keep\nMODEL_NAME=m-keep\n", encoding="utf-8")
+ monkeypatch.setattr("jiuwenswarm.start_services.get_env_file", lambda: cfg_env)
+
+ # Isolate from other instances configured on the host machine
+ # (e.g. a leftover 'alice'/'bob' in instances.yaml would otherwise
+ # pollute collect_all_ports and shift the fallback index).
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.collect_all_ports",
+ lambda exclude_name=None: [],
+ )
+
+ cmd = start_services.InstanceCommand("default")
+ assert cmd.validate_and_load() is None
+
+ # Force ONLY the index-0 group to be occupied; every higher index free.
+ occupied = set(calculate_instance_ports(0).values())
+ real = is_port_available
+
+ def fake(host, port):
+ return port not in occupied and real(host, port)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available", fake
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services.is_port_available", fake
+ )
+
+ rc = start_services._resolve_ports_with_fallback(cmd)
+ assert rc is None
+ assert cmd.config.ports["gateway"] == 20001 # index 1
+
+ # config/.env got the new ports AND preserved existing keys
+ txt = cfg_env.read_text()
+ assert "API_KEY=sk-keep" in txt
+ assert "MODEL_NAME=m-keep" in txt
+ assert "GATEWAY_PORT=20001" in txt
+ assert "AGENT_SERVER_PORT=19092" in txt
+
+ @staticmethod
+ def test_no_fallback_returns_error_when_range_exhausted(tmp_path, monkeypatch):
+ """When the whole scan range is occupied, fallback returns 1."""
+ from jiuwenswarm import start_services
+
+ cfg_env = tmp_path / "config" / ".env"
+ cfg_env.parent.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setattr("jiuwenswarm.start_services.get_env_file", lambda: cfg_env)
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.collect_all_ports",
+ lambda exclude_name=None: [],
+ )
+
+ cmd = start_services.InstanceCommand("default")
+ assert cmd.validate_and_load() is None
+
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available",
+ lambda host, port: False,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services.is_port_available",
+ lambda host, port: False,
+ )
+ rc = start_services._resolve_ports_with_fallback(cmd, scan_range=3)
+ assert rc == 1
+
+ @staticmethod
+ def test_persistence_failure_aborts_launch(tmp_path, monkeypatch):
+ """P2: if port persistence fails, fallback returns 1 (not None).
+
+ Without this, a default instance whose .env write fails would return
+ success and the launcher would spawn subprocesses that read the OLD
+ (still-conflicting) ports from .env and crash on bind. The caller
+ must be told persistence failed so it aborts instead.
+ """
+ from unittest.mock import patch as _patch
+ from jiuwenswarm import start_services
+
+ cfg_env = tmp_path / "config" / ".env"
+ cfg_env.parent.mkdir(parents=True, exist_ok=True)
+ # Pre-create the file so the post-check read works even though the
+ # write is mocked to fail. Pre-existing content must be preserved
+ # (no fallback ports written into it).
+ cfg_env.write_text("API_KEY=sk-keep\n", encoding="utf-8")
+ monkeypatch.setattr("jiuwenswarm.start_services.get_env_file", lambda: cfg_env)
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.collect_all_ports",
+ lambda exclude_name=None: [],
+ )
+
+ cmd = start_services.InstanceCommand("default")
+ assert cmd.validate_and_load() is None
+
+ # Only index-0 occupied so a fallback group IS found — but then make
+ # the .env write raise so the persistence path fails.
+ occupied = set(calculate_instance_ports(0).values())
+ real = is_port_available
+
+ def fake_probe(host, port):
+ return port not in occupied and real(host, port)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available", fake_probe
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services.is_port_available", fake_probe
+ )
+
+ def boom(*args, **kwargs):
+ raise OSError("simulated .env write failure")
+
+ with _patch(
+ "jiuwenswarm.instance_manager.config._upsert_env_ports",
+ side_effect=boom,
+ ):
+ rc = start_services._resolve_ports_with_fallback(cmd)
+
+ # Must surface the failure (return 1), not silently succeed.
+ assert rc == 1
+ # Persistence failed, so the .env must NOT contain fallback ports;
+ # only the pre-existing content remains.
+ assert "GATEWAY_PORT=20001" not in cfg_env.read_text()
+ assert "API_KEY=sk-keep" in cfg_env.read_text()
+
+ @staticmethod
+ def test_no_conflict_launch_clears_stale_env_ports(tmp_path, monkeypatch):
+ """P2 regression: a previous fallback's ports must not linger in .env.
+
+ Scenario ("conflict-then-no-conflict"):
+ 1. Prior launch hit a conflict and wrote GATEWAY_PORT=20001 to .env.
+ 2. The conflict is now gone (index-0 ports are free again).
+ 3. This launch has NO conflict → check_ports_conflicts() is empty.
+
+ Without the _sync_default_env_ports call on the no-conflict path,
+ .env would keep GATEWAY_PORT=20001 and subprocesses (which read .env
+ via load_dotenv) would bind 20001 instead of the default 19001. The
+ fix re-writes index-0 defaults into .env on every no-conflict launch.
+ """
+ from unittest.mock import patch as _patch
+ from jiuwenswarm import start_services
+
+ cfg_env = tmp_path / "config" / ".env"
+ cfg_env.parent.mkdir(parents=True, exist_ok=True)
+ # Simulate a stale fallback residue from a previous launch.
+ cfg_env.write_text(
+ "API_KEY=sk-keep\n"
+ "AGENT_SERVER_PORT=19092\n" # stale fallback (index 1)
+ "GATEWAY_PORT=20001\n" # stale fallback (index 1)
+ "MODEL_NAME=m-keep\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("jiuwenswarm.start_services.get_env_file", lambda: cfg_env)
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.collect_all_ports",
+ lambda exclude_name=None: [],
+ )
+
+ cmd = start_services.InstanceCommand("default")
+ assert cmd.validate_and_load() is None
+
+ # Make index-0 ports look free (no conflict) so _run takes the
+ # no-conflict path. Other indices are irrelevant here.
+ monkeypatch.setattr(
+ "jiuwenswarm.instance_manager.config.is_port_available",
+ lambda host, port: True,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services.is_port_available",
+ lambda host, port: True,
+ )
+
+ # Stub out the actual subprocess launch — we only care about .env sync.
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services._build_commands",
+ lambda mode: [("stub", ["true"], tmp_path)],
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.start_services._run_processes",
+ lambda commands: 0,
+ )
+
+ rc = start_services._run("app")
+ assert rc == 0
+
+ # .env must now carry the index-0 DEFAULTS (not the stale 20001).
+ txt = cfg_env.read_text()
+ assert "GATEWAY_PORT=19001" in txt, txt
+ assert "AGENT_SERVER_PORT=18092" in txt, txt
+ # Stale fallback ports must be gone.
+ assert "GATEWAY_PORT=20001" not in txt
+ assert "AGENT_SERVER_PORT=19092" not in txt
+ # And pre-existing unrelated keys preserved.
+ assert "API_KEY=sk-keep" in txt
+ assert "MODEL_NAME=m-keep" in txt