Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): spawn the engine windowless and bind the gateway exclusively on Windows (#2470)

Call White39f8d242c2f9
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index a0199e0bd..a9a6d4394 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -613,3 +613,14 @@ jobs:
# owner in both Windows PowerShell and PowerShell 7.
- name: Verify the installer's launcher rule matches the Python owner
run: python -m pytest tests/test_installer_uninstall.py -q -ra -k "rule_matches or dirs_match or powershell"
+
+ # Each of these behaves differently only on Windows: the desktop starts the
+ # service with no console, so a console child opens its own window unless
+ # told not to; SO_REUSEADDR there lets another socket share the gateway's
+ # port; and a text-mode descriptor rewrites the native bytes a takeover
+ # compares.
+ - name: Verify the Model Hub engine's Windows process, socket and file flags
+ run: >-
+ python -m pytest -q -ra
+ tests/test_process_isolation.py tests/test_model_hub_l3.py tests/test_model_hub_migration_review_boundaries.py
+ -k "console_window or cannot_be_bound or byte_for_byte"
diff --git a/core/handlers/model_hub/migration_journal.py b/core/handlers/model_hub/migration_journal.py
index 6fdaff2f8..01bfd68d5 100644
--- a/core/handlers/model_hub/migration_journal.py
+++ b/core/handlers/model_hub/migration_journal.py
@@ -143,8 +143,11 @@ class NativeFileEdit:
if _read_regular(self.path) is not None:
raise TakeoverStateError("native configuration changed")
return
+ # O_BINARY: a Windows text-mode descriptor would drop each CR and stop
+ # at 0x1A, so a CRLF native file never compared equal to its own bytes.
descriptor = os.open(
- self.path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0),
+ self.path,
+ os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0),
)
try:
current = os.fstat(descriptor)
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index f37e2476a..e85349866 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -610,7 +610,14 @@ class ModelHubTurnGateway:
)
await runner.setup()
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ # On Windows SO_REUSEADDR lets another socket, even another user's,
+ # bind this port and take the gateway's traffic; claim it exclusively
+ # there, as control IPC does.
+ exclusive = getattr(socket, "SO_EXCLUSIVEADDRUSE", None)
+ if exclusive is not None:
+ listener.setsockopt(socket.SOL_SOCKET, exclusive, 1)
+ else:
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(128)
listener.setblocking(False)
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 89f53a8d8..52da750fe 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -242,10 +242,19 @@ def probe_process_liveness(pid: int) -> ProcessLivenessStatus:
return "alive"
-def isolated_subprocess_kwargs() -> dict[str, Any]:
- """Return subprocess kwargs that put a child outside this process group."""
+def isolated_subprocess_kwargs(*, console: bool = True) -> dict[str, Any]:
+ """Return subprocess kwargs that put a child outside this process group.
+
+ ``console=False`` is for a console program that only ever runs in the
+ background. On Windows it then gets no console window, which a parent with
+ no console of its own -- the desktop app starts the service that way --
+ would otherwise open for it.
+ """
if os.name == "nt":
- return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
+ flags = subprocess.CREATE_NEW_PROCESS_GROUP
+ if not console:
+ flags |= subprocess.CREATE_NO_WINDOW
+ return {"creationflags": flags}
return {"start_new_session": True}
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 638f1bd52..0a5570d05 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -6,6 +6,7 @@ import copy
import inspect
import json
import re
+import socket
import tempfile
import threading
from collections import deque
@@ -2324,6 +2325,32 @@ def test_gateway_models_endpoint_serves_authenticated_backend_catalog(
asyncio.run(exercise())
+def test_gateway_port_cannot_be_bound_by_another_socket(tmp_path: Path) -> None:
+ """Windows SO_REUSEADDR would let any local socket share the gateway's port and its traffic."""
+
+ async def exercise() -> None:
+ service = _service(tmp_path, sources=[_source("src_primary01", "Primary")])
+ gateway = ModelHubTurnGateway(service)
+ base_url, _token = await gateway.endpoint(
+ "codex",
+ process_scope="/repo",
+ turn_id="turn_exclusive_port",
+ requested_model_id="shared-model",
+ resolved_model_id="shared-model",
+ source_id="src_primary01",
+ )
+ port = int(base_url.rsplit(":", 1)[1].split("/", 1)[0])
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as intruder:
+ intruder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ with pytest.raises(OSError):
+ intruder.bind(("127.0.0.1", port))
+ finally:
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
def test_runtime_resolution_sees_controller_reconcile_after_remote_catalog_refresh(
monkeypatch,
tmp_path: Path,
diff --git a/tests/test_model_hub_migration_review_boundaries.py b/tests/test_model_hub_migration_review_boundaries.py
index 65c940f38..f29a84fe6 100644
--- a/tests/test_model_hub_migration_review_boundaries.py
+++ b/tests/test_model_hub_migration_review_boundaries.py
@@ -276,6 +276,20 @@ def test_mode_replay_rejects_replaced_content_without_chmod(home, monkeypatch, r
assert stat.S_IMODE(path.stat().st_mode) == 0o600
+def test_native_file_bytes_survive_takeover_byte_for_byte(tmp_path):
+ """CRLF and 0x1A are native bytes too: a Windows text-mode read dropped one and stopped at the other."""
+ path = tmp_path / "settings.json"
+ before = b'{"model": "native"}\r\n\x1a{"keep": true}\r\n'
+ path.write_bytes(before)
+ edit = NativeFileEdit.plan(path, b'{"model": "hub"}\r\n')
+ edit.check()
+ edit.apply()
+ edit.check(applied=True)
+ assert path.read_bytes() == b'{"model": "hub"}\r\n'
+ edit.apply(reverse=True)
+ assert path.read_bytes() == before
+
+
@pytest.mark.parametrize("operation", ["check", "apply"])
def test_selected_shell_mode_change_invalidates_planned_edit(home, operation):
path = home / ".bashrc"
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
index 0fcdf82db..6444318d6 100644
--- a/tests/test_process_isolation.py
+++ b/tests/test_process_isolation.py
@@ -76,6 +76,21 @@ def test_isolated_subprocess_kwargs_start_new_session_on_posix() -> None:
assert isolated_subprocess_kwargs() == {"start_new_session": True}
[email protected](os.name != "nt", reason="Windows console allocation")
+def test_background_console_program_opens_no_console_window() -> None:
+ """The desktop starts the service with no console, so a console child would open its own window."""
+ probe = "import ctypes; print(ctypes.windll.kernel32.GetConsoleWindow())"
+ result = subprocess.run(
+ [sys.executable, "-c", probe],
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=60,
+ **isolated_subprocess_kwargs(console=False),
+ )
+ assert result.stdout.strip() == "0"
+
+
def test_process_identity_reads_inherited_worker_marker(monkeypatch: pytest.MonkeyPatch) -> None:
process = SimpleNamespace(
create_time=lambda: 123.0,
diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.py
index c9de249a4..14ae913b9 100644
--- a/vibe/model_hub_runtime/installer.py
+++ b/vibe/model_hub_runtime/installer.py
@@ -618,7 +618,7 @@ class EngineRuntimeManager(ManagedRuntimeManager):
timeout=10,
check=False,
env=engine_subprocess_environment(),
- **isolated_subprocess_kwargs(),
+ **isolated_subprocess_kwargs(console=False),
)
except Exception as exc: # noqa: BLE001
self._set_install_failure(self._reason("binary_not_runnable"), exc)
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
index bb5b40fd8..84b16dba1 100644
--- a/vibe/model_hub_runtime/state.py
+++ b/vibe/model_hub_runtime/state.py
@@ -820,7 +820,9 @@ class EngineStateStore:
# Do not turn an open/read failure into content corruption. Ref
# recovery is safe only after a private regular file was read.
descriptor = os.open(
- path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0),
+ path,
+ os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
+ | getattr(os, "O_BINARY", 0),
)
with os.fdopen(descriptor, "rb") as handle:
mode = os.fstat(handle.fileno()).st_mode
@@ -1265,9 +1267,10 @@ class EngineStateStore:
sort_keys=True,
).encode("utf-8") + b"\n"
try:
+ # O_BINARY: Windows would otherwise write each LF as CRLF.
descriptor = os.open(
path,
- os.O_WRONLY | os.O_CREAT | os.O_EXCL,
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0),
0o600,
)
except FileExistsError as exc:
@@ -1301,7 +1304,7 @@ class EngineStateStore:
raise EngineStateError("credential reference collision")
descriptor = -1
try:
- descriptor = os.open(temporary_path, os.O_WRONLY | os.O_TRUNC)
+ descriptor = os.open(temporary_path, os.O_WRONLY | os.O_TRUNC | getattr(os, "O_BINARY", 0))
with os.fdopen(descriptor, "wb") as handle:
descriptor = -1
handle.write(serialized)
diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.py
index 462296c3c..a27e9e55f 100644
--- a/vibe/model_hub_runtime/supervisor.py
+++ b/vibe/model_hub_runtime/supervisor.py
@@ -392,7 +392,7 @@ class EngineSupervisor:
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
umask=0o077,
- **isolated_subprocess_kwargs(),
+ **isolated_subprocess_kwargs(console=False),
)
except (OSError, ValueError) as exc:
# No process was created, so nothing can carry this marker: retire the