Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

fix(extensions): record starts on the owner's side; never 500 on a refused record (#8249)

Mike Bradleye9131c928069
diff --git a/ods/bin/ods-host-agent.py b/ods/bin/ods-host-agent.py
index 78f228210..0b14c19a9 100755
--- a/ods/bin/ods-host-agent.py
+++ b/ods/bin/ods-host-agent.py
@@ -8437,6 +8437,19 @@ def _read_progress_status(service_id: str) -> str | None:
return status if isinstance(status, str) else None
+def _start_records_outcome(service_id: str) -> bool:
+ """Whether a synchronous start replaces the service's progress record.
+
+ No record, ``prepared`` (this enable's images are ready), ``started`` and
+ the Dashboard's own ``pulling`` receipt for this start are replaced. An
+ unreadable record or another operation's phase is left as it is; a
+ running install or image preparation holds the service lock.
+ """
+ if not (DATA_DIR / "extension-progress" / f"{service_id}.json").exists():
+ return True
+ return _read_progress_status(service_id) in {"prepared", "started", "pulling"}
+
+
def _run_post_install_hook(service_id: str, ext_dir: Path) -> tuple[bool, str]:
"""Run an extension's ``post_install`` hook with sandboxed env.
@@ -12626,7 +12639,15 @@ class AgentHandler(BaseHTTPRequestHandler):
_start_enable_retry(self, service_id, lock)
return
+ # The start's outcome is recorded here, on the owner's side: the
+ # Dashboard API runs as UID 1000 and cannot write the record when the
+ # install owner is another user (Workstation06: nvuser, UID 1001).
+ records = action == "start" and _start_records_outcome(service_id)
+ # Kept when an unexpected error escapes; that error is then raised.
+ ok, err, status = False, "The start stopped unexpectedly; see the host agent log.", 500
try:
+ if records:
+ _write_progress(service_id, "starting", "Starting container...")
ok, err = docker_compose_action(service_id, action)
status = 503 if "timed out" in err else 500
except RuntimeError as exc:
@@ -12634,7 +12655,15 @@ class AgentHandler(BaseHTTPRequestHandler):
except subprocess.CalledProcessError as exc:
ok, err, status = False, f"Compose resolution failed: {exc.stderr[:300]}", 500
finally:
- lock.release()
+ try:
+ # A one-shot CLI start records its own verified outcome.
+ if records and _read_progress_status(service_id) == "starting":
+ if ok:
+ _write_progress(service_id, "started", "Service started")
+ else:
+ _write_progress(service_id, "error", "Start failed", error=err)
+ finally:
+ lock.release()
if ok:
json_response(self, 200, {"status": "ok", "service_id": service_id, "action": action})
return
diff --git a/ods/extensions/services/dashboard-api/routers/extensions.py b/ods/extensions/services/dashboard-api/routers/extensions.py
index 11aab593e..e065dd894 100644
--- a/ods/extensions/services/dashboard-api/routers/extensions.py
+++ b/ods/extensions/services/dashboard-api/routers/extensions.py
@@ -265,21 +265,46 @@ def _cleanup_stale_progress() -> None:
pass
+def _store_progress(service_id: str, record: dict) -> None:
+ """Replace a service's progress record, never rewriting it in place.
+
+ The host agent replaces the same records and the Extensions page polls
+ them, so a reader sees the old record or the new one. Where the install
+ owner is not UID 1000 this API cannot write the owner's progress
+ directory, and the refusal turned a failed start into an HTTP 500 that
+ also broke Retry (Workstation06, 2026-10-26). The host agent records the
+ outcome of starts and installs itself, so a refusal is logged instead.
+ """
+ progress_dir = Path(DATA_DIR) / "extension-progress"
+ temporary = None
+ try:
+ progress_dir.mkdir(parents=True, exist_ok=True)
+ descriptor, temporary = tempfile.mkstemp(dir=progress_dir, prefix=f".{service_id}-", suffix=".tmp")
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(record, stream)
+ # mkstemp creates 0600; the host agent reads these records as the owner.
+ os.chmod(temporary, 0o644)
+ os.replace(temporary, progress_dir / f"{service_id}.json")
+ temporary = None
+ except PermissionError as exc:
+ logger.warning("Progress record for %s was not written (%s); the host agent records "
+ "start and install outcomes itself.", service_id, exc)
+ finally:
+ if temporary is not None:
+ Path(temporary).unlink(missing_ok=True)
+
+
def _write_initial_progress(service_id: str) -> None:
"""Write an initial progress file so the UI sees 'installing' immediately."""
- progress_dir = Path(DATA_DIR) / "extension-progress"
- progress_dir.mkdir(parents=True, exist_ok=True)
now = datetime.now(timezone.utc).isoformat()
- progress = {
+ _store_progress(service_id, {
"service_id": service_id,
"status": "pulling",
"phase_label": "Starting installation...",
"error": None,
"started_at": now,
"updated_at": now,
- }
- progress_file = progress_dir / f"{service_id}.json"
- progress_file.write_text(json.dumps(progress), encoding="utf-8")
+ })
def _write_error_progress(service_id: str, error_msg: str) -> None:
@@ -296,8 +321,7 @@ def _write_error_progress(service_id: str, error_msg: str) -> None:
data["status"] = "error"
data["error"] = error_msg
data["updated_at"] = now
- progress_file.parent.mkdir(parents=True, exist_ok=True)
- progress_file.write_text(json.dumps(data), encoding="utf-8")
+ _store_progress(service_id, data)
def _write_started_progress(service_id: str) -> None:
@@ -315,8 +339,7 @@ def _write_started_progress(service_id: str) -> None:
return
progress.update(status="started", phase_label="Service started", error=None,
updated_at=datetime.now(timezone.utc).isoformat())
- progress_file = Path(DATA_DIR) / "extension-progress" / f"{service_id}.json"
- progress_file.write_text(json.dumps(progress), encoding="utf-8")
+ _store_progress(service_id, progress)
def _has_error_progress(service_id: str) -> bool:
diff --git a/ods/extensions/services/dashboard-api/tests/test_extensions.py b/ods/extensions/services/dashboard-api/tests/test_extensions.py
index c7dd5bf15..aa4e0db28 100644
--- a/ods/extensions/services/dashboard-api/tests/test_extensions.py
+++ b/ods/extensions/services/dashboard-api/tests/test_extensions.py
@@ -3,7 +3,9 @@
import contextlib
import hashlib
import json
+import logging
import os
+import tempfile
from pathlib import Path
from unittest.mock import AsyncMock, Mock, patch
@@ -1216,6 +1218,41 @@ class TestEnableExtension:
# compose.yaml still exists (no rename happened)
assert (user_dir / "my-ext" / "compose.yaml").exists()
+ def test_enable_stopped_survives_an_unwritable_progress_record(
+ self, test_client, monkeypatch, tmp_path, caplog,
+ ):
+ """Retry answered HTTP 500 on Workstation06 (2026-10-26): the install
+ owner is UID 1001, so this API (UID 1000) could not write the owner's
+ progress record. The host agent records the start there itself."""
+ user_dir = _setup_user_ext(tmp_path, "my-ext", enabled=True)
+ _patch_mutation_config(monkeypatch, tmp_path, user_dir=user_dir)
+ starts = []
+
+ def start(action, sid):
+ starts.append((action, sid))
+ return True
+
+ monkeypatch.setattr("routers.extensions._call_agent", start)
+ progress_dir = tmp_path / "extension-progress"
+ real_mkstemp = tempfile.mkstemp
+
+ def refuse_progress(*args, **kwargs):
+ if Path(kwargs.get("dir", "")) == progress_dir:
+ raise PermissionError(13, "Permission denied", str(progress_dir))
+ return real_mkstemp(*args, **kwargs)
+
+ monkeypatch.setattr(tempfile, "mkstemp", refuse_progress)
+
+ with caplog.at_level(logging.WARNING, logger="routers.extensions"):
+ resp = test_client.post(
+ "/api/extensions/my-ext/enable",
+ headers=test_client.auth_headers,
+ )
+
+ assert resp.status_code == 200
+ assert ("start", "my-ext") in starts
+ assert "Progress record for my-ext was not written" in caplog.text
+
def test_enable_allows_core_service_dependency(self, test_client, monkeypatch, tmp_path):
"""Enable succeeds when depends_on includes a core service."""
manifest = {"service": {"depends_on": ["open-webui"]}}
@@ -4794,6 +4831,57 @@ class TestWriteErrorProgress:
assert data["error"] == "Agent unreachable"
assert "phase_label" in data
+ def test_records_are_replaced_whole_and_leave_no_temporary_file(self, monkeypatch, tmp_path):
+ """The host agent and the Extensions page read these records while
+ they change, so a record is replaced, never truncated in place."""
+ from routers.extensions import _write_error_progress, _write_initial_progress
+
+ monkeypatch.setattr("routers.extensions.DATA_DIR", str(tmp_path))
+ directory = tmp_path / "extension-progress"
+ replaced = []
+ real_replace = os.replace
+
+ def record_replace(source, target):
+ replaced.append((Path(source).parent, Path(target)))
+ real_replace(source, target)
+
+ monkeypatch.setattr(os, "replace", record_replace)
+
+ _write_initial_progress("my-ext")
+ _write_error_progress("my-ext", "Host agent failed")
+
+ assert replaced == [(directory, directory / "my-ext.json")] * 2
+ assert [path.name for path in directory.iterdir()] == ["my-ext.json"]
+ assert json.loads((directory / "my-ext.json").read_text())["error"] == "Host agent failed"
+ if os.name == "posix":
+ # The host agent reads the record as the install owner.
+ assert (directory / "my-ext.json").stat().st_mode & 0o777 == 0o644
+
+ @pytest.mark.parametrize("refused", ["mkstemp", "replace"])
+ def test_a_refused_write_is_logged_and_keeps_the_owner_record(self, monkeypatch, tmp_path, caplog, refused):
+ """An install owner other than UID 1000 keeps this API out of its
+ progress directory; the host agent's own record must stay intact."""
+ from routers.extensions import _write_error_progress
+
+ monkeypatch.setattr("routers.extensions.DATA_DIR", str(tmp_path))
+ directory = tmp_path / "extension-progress"
+ directory.mkdir()
+ owner_record = {"service_id": "comfyui", "status": "error", "phase_label": "Start failed",
+ "error": "Docker compose operation timed out (600s)"}
+ (directory / "comfyui.json").write_text(json.dumps(owner_record))
+
+ def refuse(*args, **kwargs):
+ raise PermissionError(13, "Permission denied", str(directory))
+
+ monkeypatch.setattr(tempfile if refused == "mkstemp" else os, refused, refuse)
+
+ with caplog.at_level(logging.WARNING, logger="routers.extensions"):
+ _write_error_progress("comfyui", "Host agent failed to start extension.")
+
+ assert json.loads((directory / "comfyui.json").read_text()) == owner_record
+ assert [path.name for path in directory.iterdir()] == ["comfyui.json"]
+ assert "Progress record for comfyui was not written" in caplog.text
+
# --- _activate_service: built-in (EXTENSIONS_DIR) branch ---
diff --git a/ods/extensions/services/dashboard-api/tests/test_host_agent.py b/ods/extensions/services/dashboard-api/tests/test_host_agent.py
index 61836c79e..157dcc0e2 100644
--- a/ods/extensions/services/dashboard-api/tests/test_host_agent.py
+++ b/ods/extensions/services/dashboard-api/tests/test_host_agent.py
@@ -8413,7 +8413,7 @@ class TestEnableRetry:
# Hook failure must NOT proceed to compose start
assert compose_calls == []
- def test_no_progress_file_uses_sync_path_without_progress_write(self, retry_env, monkeypatch):
+ def test_no_progress_file_uses_sync_path_and_records_the_start(self, retry_env, monkeypatch):
_, data_dir, builtin_root, _ = retry_env
ext_dir = builtin_root / "fakesvc"
self._write_manifest(ext_dir, with_hook=True)
@@ -8427,8 +8427,13 @@ class TestEnableRetry:
stdout="", stderr="")
monkeypatch.setattr(_mod.subprocess, "run", fake_run)
- monkeypatch.setattr(_mod, "docker_compose_action",
- lambda sid, act: (True, ""))
+ during = []
+
+ def fake_compose(sid, act):
+ during.append(self._progress(data_dir, sid))
+ return True, ""
+
+ monkeypatch.setattr(_mod, "docker_compose_action", fake_compose)
handler = _FakeHandler(self._body("fakesvc"))
_mod.AgentHandler._handle_extension(handler, "start")
@@ -8441,7 +8446,75 @@ class TestEnableRetry:
len(c) >= 2 and c[0] == "bash" and c[1].endswith("setup.sh")
for c in hook_cmds
)
- # Sync path must not write a progress file
+ # The owner-side agent records the start: the Dashboard API (UID 1000)
+ # cannot write this record when the install owner is another user.
+ assert (during[0]["status"], during[0]["phase_label"]) == ("starting", "Starting container...")
+ progress = self._progress(data_dir, "fakesvc")
+ assert (progress["status"], progress["phase_label"]) == ("started", "Service started")
+
+ def test_sync_start_failure_records_the_hosts_reason(self, retry_env, monkeypatch):
+ """Workstation06 (2026-10-26): ComfyUI's first start timed out, and the
+ Dashboard API's PermissionError on the record left the card stopped."""
+ _, data_dir, builtin_root, _ = retry_env
+ self._write_manifest(builtin_root / "fakesvc", with_hook=False)
+ self._write_progress_file(data_dir, "fakesvc", "prepared")
+ monkeypatch.setattr(_mod, "docker_compose_action",
+ lambda sid, act: (False, "Docker compose operation timed out (600s)"))
+
+ handler = _FakeHandler(self._body("fakesvc"))
+ _mod.AgentHandler._handle_extension(handler, "start")
+
+ assert handler.response_code == 503
+ progress = self._progress(data_dir, "fakesvc")
+ assert (progress["status"], progress["phase_label"]) == ("error", "Start failed")
+ assert progress["error"] == "Docker compose operation timed out (600s)"
+ assert not _mod._service_locks["fakesvc"].locked()
+
+ def test_sync_start_keeps_a_verified_one_shot_record(self, retry_env, monkeypatch):
+ _, data_dir, builtin_root, _ = retry_env
+ self._write_manifest(builtin_root / "fakesvc", with_hook=False)
+
+ def fake_compose(sid, act):
+ # docker_compose_action records a one-shot CLI's verified exit itself.
+ _mod._write_progress(sid, "started", "CLI verification complete", exit_verified=True)
+ return True, ""
+
+ monkeypatch.setattr(_mod, "docker_compose_action", fake_compose)
+
+ handler = _FakeHandler(self._body("fakesvc"))
+ _mod.AgentHandler._handle_extension(handler, "start")
+
+ assert handler.response_code == 200
+ progress = self._progress(data_dir, "fakesvc")
+ assert (progress["phase_label"], progress["exit_verified"]) == ("CLI verification complete", True)
+
+ def test_unexpected_start_error_is_recorded_released_and_raised(self, retry_env, monkeypatch):
+ _, data_dir, builtin_root, _ = retry_env
+ self._write_manifest(builtin_root / "fakesvc", with_hook=False)
+
+ def fake_compose(sid, act):
+ raise ValueError("Compose policy rejected the recipe")
+
+ monkeypatch.setattr(_mod, "docker_compose_action", fake_compose)
+
+ handler = _FakeHandler(self._body("fakesvc"))
+ with pytest.raises(ValueError, match="Compose policy rejected"):
+ _mod.AgentHandler._handle_extension(handler, "start")
+
+ progress = self._progress(data_dir, "fakesvc")
+ assert progress["status"] == "error"
+ assert progress["error"] == "The start stopped unexpectedly; see the host agent log."
+ assert not _mod._service_locks["fakesvc"].locked()
+
+ def test_stop_writes_no_progress(self, retry_env, monkeypatch):
+ _, data_dir, builtin_root, _ = retry_env
+ self._write_manifest(builtin_root / "fakesvc", with_hook=False)
+ monkeypatch.setattr(_mod, "docker_compose_action", lambda sid, act: (True, ""))
+
+ handler = _FakeHandler(self._body("fakesvc"))
+ _mod.AgentHandler._handle_extension(handler, "stop")
+
+ assert handler.response_code == 200
assert self._progress(data_dir, "fakesvc") is None
def test_progress_status_started_uses_sync_path(self, retry_env, monkeypatch):
diff --git a/ods/installers/phases/06-directories.sh b/ods/installers/phases/06-directories.sh
index 28627ae72..cefa24b60 100755
--- a/ods/installers/phases/06-directories.sh
+++ b/ods/installers/phases/06-directories.sh
@@ -564,6 +564,10 @@ else
ods_progress 38 "directories" "Creating directory structure"
mkdir -p "$INSTALL_DIR"/{config,data,models}
mkdir -p "$INSTALL_DIR"/data/{open-webui,whisper,tts,n8n,qdrant,models,privacy-shield,ape,token-spy,hermes,persona}
+ # The host agent writes extension progress as the install owner. Created
+ # here, the Dashboard API (UID 1000, which may be another user) cannot
+ # make it first and lock the owner's host agent out of it.
+ mkdir -p "$INSTALL_DIR"/data/extension-progress
mkdir -p "$INSTALL_DIR"/data/hermes-proxy/{caddy-data,caddy-config}
mkdir -p "$INSTALL_DIR"/data/langfuse/{postgres,clickhouse,redis,minio}
mkdir -p "$INSTALL_DIR"/data/remote-provider/secrets