Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(api): stop orphaned runtime on reload fallback, surface 422 diagnostics

shadowinlifec5bc1ce266e3
diff --git a/agent/src/api/channels_config_routes.py b/agent/src/api/channels_config_routes.py
index 0a2ceb5a8..0ac757d4d 100644
--- a/agent/src/api/channels_config_routes.py
+++ b/agent/src/api/channels_config_routes.py
@@ -12,6 +12,9 @@ Security properties owned here: secret values never cross the wire (masked via
``split_values_secrets``), and a section that fails validation or the
enable-transition credential probe is rejected with 422 *before* anything is
written to disk.
+
+Plugin channels discovered via entry points are intentionally not surfaced
+here; they remain file-configured.
"""
from __future__ import annotations
@@ -20,6 +23,7 @@ import asyncio
import logging
import sys as _sys
from collections import defaultdict
+from pathlib import Path
from typing import Any, Awaitable, Callable
from fastapi import Depends, FastAPI, HTTPException, status
@@ -40,12 +44,25 @@ from src.config.paths import get_config_path
logger = logging.getLogger(__name__)
-# Helper modules in src/channels/ that are not adapters; discovery enumerates them.
-_NON_CHANNEL_MODULES = frozenset({"targets", "config_meta"})
-
_PROBE_CODES = frozenset({"ok", "invalid_credentials", "network", "unsupported"})
_VERIFY_BLOCK_CODES = frozenset({"invalid_credentials", "network"})
+# Bound the fallback stop so a wedged adapter cannot stall the reset + restart.
+_FALLBACK_STOP_TIMEOUT_S = 10.0
+
+# Per-channel lifecycle keys the manager consumes from the section; they are
+# not adapter model fields but are legitimate config content (#341 lineage).
+_MANAGER_OVERRIDE_KEYS = frozenset(
+ {
+ "send_progress",
+ "send_tool_hints",
+ "show_reasoning",
+ "sendProgress",
+ "sendToolHints",
+ "showReasoning",
+ }
+)
+
# Per-channel PUT/test serialization + one lock around runtime reset/rebuild.
_channel_locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
_runtime_lock = asyncio.Lock()
@@ -70,7 +87,12 @@ class ChannelConfigUpdateRequest(BaseModel):
class ChannelTestRequest(BaseModel):
- """Optional unsaved partial config for an ephemeral connection test."""
+ """Optional unsaved partial config for an ephemeral connection test.
+
+ ``clear_<field>: true`` flags arrive as extra keys, matching the PUT body.
+ """
+
+ model_config = ConfigDict(extra="allow")
config: dict[str, Any] | None = None
@@ -86,8 +108,8 @@ def _host():
def _known_channel_names() -> set[str]:
- """Return discovered channel adapter names, minus non-channel helpers."""
- return set(discover_channel_names()) - _NON_CHANNEL_MODULES
+ """Return the discovered built-in channel adapter names."""
+ return set(discover_channel_names())
def _is_secret_key(name: str, key: str) -> bool:
@@ -112,6 +134,15 @@ def _patch_of(name: str, body: dict[str, Any]) -> dict[str, Any]:
}
+def _clear_flags(extra: dict[str, Any] | None) -> list[str]:
+ """Return the ``clear_<field>`` targets from a request's extra keys."""
+ return [
+ key[len("clear_") :]
+ for key, value in (extra or {}).items()
+ if key.startswith("clear_") and len(key) > len("clear_") and value
+ ]
+
+
def _supports_connection_test(name: str) -> bool:
"""Return whether the adapter class declares a standalone connection test."""
try:
@@ -154,6 +185,19 @@ def _fresh_entry(name: str) -> dict[str, Any]:
return _channel_entry(name, _stored_section(name), status_map)
+def _display_config_path(path: Path) -> str:
+ """Return a display-only config path: home-relative when possible.
+
+ The absolute path discloses the local username and directory layout to any
+ read-authorized caller; the UI only needs to show the operator which file
+ to edit by hand.
+ """
+ try:
+ return "~/" + path.relative_to(Path.home()).as_posix()
+ except ValueError:
+ return path.name
+
+
def _scrub_detail(name: str, text: Any, section: dict[str, Any]) -> str:
"""Mask every secret value of *section* found in *text* (defense in depth)."""
cleaned = str(text or "")
@@ -176,7 +220,11 @@ def _reject_validation(fields: list[str]) -> HTTPException:
"""Build the frozen 422 ``validation_error`` envelope."""
return HTTPException(
status_code=422, # literal per repo convention (the starlette constant is deprecated)
- detail={"code": "validation_error", "fields": fields},
+ detail={
+ "code": "validation_error",
+ "fields": fields,
+ "message": "invalid fields: " + ", ".join(fields),
+ },
)
@@ -225,6 +273,13 @@ async def _hot_apply(name: str, section: dict[str, Any] | None) -> str:
exc_info=True,
)
async with _runtime_lock:
+ try:
+ await asyncio.wait_for(runtime.stop(), timeout=_FALLBACK_STOP_TIMEOUT_S)
+ except Exception: # noqa: BLE001 - a wedged stop must not block the rebuild
+ logger.warning(
+ "Stopping the failed runtime timed out; resetting anyway",
+ exc_info=True,
+ )
_state.reset_channel_runtime()
await host._get_channel_runtime().start(start_manager=True)
return "reset"
@@ -234,25 +289,41 @@ async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[
"""Validate → optional enable-transition probe → write → hot apply."""
stored = _stored_section(name)
patch = _patch_of(name, payload.config)
- clears = [
- key[len("clear_"):]
- for key, value in (payload.model_extra or {}).items()
- if key.startswith("clear_") and len(key) > len("clear_") and value
- ]
+ clears = _clear_flags(payload.model_extra)
merged = {**stored, **patch}
for key in clears:
merged.pop(key, None)
cls, instance = _build_ephemeral(name, merged)
+ unknown = sorted(
+ key
+ for key in patch
+ if key not in set(cls.default_config()) and key not in _MANAGER_OVERRIDE_KEYS
+ )
+ if unknown:
+ raise _reject_validation(unknown)
+
enabling = bool(merged.get("enabled")) and not bool(stored.get("enabled"))
if enabling and cls.supports_connection_test and not payload.skip_verify:
- probe = await instance.test_connection()
+ try:
+ probe = await instance.test_connection()
+ except Exception as exc: # noqa: BLE001 - a raising probe is a network-class failure
+ probe = {
+ "ok": False,
+ "code": "network",
+ "detail": f"{type(exc).__name__}: {exc}",
+ }
if not probe.get("ok"):
code = probe.get("code")
+ message = _scrub_detail(name, probe.get("detail", ""), merged)[:200]
raise HTTPException(
status_code=422,
- detail={"code": code if code in _VERIFY_BLOCK_CODES else "network", "fields": []},
+ detail={
+ "code": code if code in _VERIFY_BLOCK_CODES else "network",
+ "fields": [],
+ "message": message or "connection probe failed",
+ },
)
try:
@@ -268,10 +339,12 @@ async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[
return {"channel": _fresh_entry(name), "applied": applied}
-async def _run_test(name: str, body: dict[str, Any] | None) -> dict[str, Any]:
+async def _run_test(name: str, body: dict[str, Any] | None, clears: list[str]) -> dict[str, Any]:
"""Probe credentials on an ephemeral instance; never persists anything."""
stored = _stored_section(name)
merged = {**stored, **_patch_of(name, body or {})}
+ for key in clears:
+ merged.pop(key, None)
tested_saved_config = not body
sdk_fallback = bool(inspect_channel(name).to_dict().get("available", False))
@@ -357,7 +430,7 @@ def register_channels_config_routes(
path = get_config_path()
channels: dict[str, Any] = {}
- for name in sorted(set(availability) - _NON_CHANNEL_MODULES):
+ for name in sorted(availability):
section = disk.get(name)
status_map = dict(availability[name])
live_entry = live.get(name)
@@ -367,7 +440,7 @@ def register_channels_config_routes(
name, section if isinstance(section, dict) else {}, status_map
)
return {
- "config_path": str(path),
+ "config_path": _display_config_path(path),
"writable": path.suffix.lower() == ".json",
"runtime_running": running,
"channels": channels,
@@ -393,4 +466,4 @@ def register_channels_config_routes(
if name not in _known_channel_names():
raise HTTPException(status_code=404, detail=f"Unknown channel: {name}")
async with _channel_locks[name]:
- return await _run_test(name, payload.config)
+ return await _run_test(name, payload.config, _clear_flags(payload.model_extra))
diff --git a/agent/src/config/writer.py b/agent/src/config/writer.py
index 34107842c..941ea1217 100644
--- a/agent/src/config/writer.py
+++ b/agent/src/config/writer.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import json
import os
import tempfile
+import threading
from contextlib import suppress
from pathlib import Path
from typing import Any, Sequence
@@ -24,6 +25,12 @@ class ConfigNotWritableError(RuntimeError):
"""Raised when the active agent config cannot be written as JSON."""
+# Serializes the read-modify-write of the whole agent.json across channels and
+# across entry points (web PUT, Feishu QR login). The body is synchronous, so
+# this is a threading lock, not an asyncio lock.
+_WRITE_LOCK = threading.Lock()
+
+
def _resolve_config_path(config_path: Path | None) -> Path:
"""Resolve the config file to update.
@@ -72,37 +79,38 @@ def update_channel_section(
section.
"""
path = _resolve_config_path(config_path)
- if path.suffix.lower() != ".json":
- raise ConfigNotWritableError(
- "Agent config is not writable as JSON: "
- f"expected a .json file, got {path}. "
- "Point the runtime at ~/.vibe-trading/agent.json to persist "
- "channel credentials."
- )
-
- payload: dict[str, Any] = {}
- if path.exists():
- try:
- payload = _read_config_file(path)
- except (OSError, ValueError) as exc:
+ with _WRITE_LOCK:
+ if path.suffix.lower() != ".json":
raise ConfigNotWritableError(
- f"Agent config at {path} could not be read for update: {exc}"
- ) from exc
-
- channels = payload.setdefault("channels", {})
- if not isinstance(channels, dict):
- raise ConfigNotWritableError("agent config 'channels' must be an object")
- section = channels.setdefault(channel, {})
- if not isinstance(section, dict):
- raise ConfigNotWritableError(
- f"agent config 'channels.{channel}' must be an object"
- )
-
- section.update(updates)
- for key in clears:
- section.pop(key, None)
-
- _write_json_atomically(path, payload)
+ "Agent config is not writable as JSON: "
+ f"expected a .json file, got {path}. "
+ "Point the runtime at ~/.vibe-trading/agent.json to persist "
+ "channel credentials."
+ )
+
+ payload: dict[str, Any] = {}
+ if path.exists():
+ try:
+ payload = _read_config_file(path)
+ except (OSError, ValueError) as exc:
+ raise ConfigNotWritableError(
+ f"Agent config at {path} could not be read for update: {exc}"
+ ) from exc
+
+ channels = payload.setdefault("channels", {})
+ if not isinstance(channels, dict):
+ raise ConfigNotWritableError("agent config 'channels' must be an object")
+ section = channels.setdefault(channel, {})
+ if not isinstance(section, dict):
+ raise ConfigNotWritableError(
+ f"agent config 'channels.{channel}' must be an object"
+ )
+
+ section.update(updates)
+ for key in clears:
+ section.pop(key, None)
+
+ _write_json_atomically(path, payload)
return path
diff --git a/agent/tests/test_channels_config_api.py b/agent/tests/test_channels_config_api.py
index 05848fe52..ec275569d 100644
--- a/agent/tests/test_channels_config_api.py
+++ b/agent/tests/test_channels_config_api.py
@@ -1,6 +1,6 @@
"""API contracts for the web IM channel-config surface (Task 5).
-Covers the frozen contract from ``.omo/plans/im-channel-web-config.md``:
+Covers the contract from https://github.com/HKUDS/Vibe-Trading/issues/1519:
``GET /channels/config``, ``PUT /channels/config/{name}`` and
``POST /channels/{name}/test`` — secret masking, the 422-before-write ordering
(bad credentials never reach disk), hot-apply modes (hot_swapped / reset /
@@ -23,7 +23,7 @@ from fastapi.testclient import TestClient
import api_server
from src.api import channels_config_routes as routes
from src.api import state as api_state
-from src.channels.dingtalk import DINGTALK_AVAILABLE
+from src.channels.dingtalk import DINGTALK_AVAILABLE, DingTalkChannel
CLIENT_ID = "ding-client-id-1234567890"
STORED_SECRET = "stored-secret-abcdefghij"
@@ -69,6 +69,7 @@ class FakeRuntime:
self._running = running
self.manager = manager if manager is not None else FakeManager()
self.start_calls: list[bool] = []
+ self.stop_calls: list[bool] = []
def status(self) -> dict[str, Any]:
return {"running": self._running, "channels": {}}
@@ -76,6 +77,10 @@ class FakeRuntime:
async def start(self, *, start_manager: bool = True) -> None:
self.start_calls.append(start_manager)
+ async def stop(self) -> None:
+ self.stop_calls.append(True)
+ self._running = False
+
def _write_agent_config(
tmp_path: Path, channels: dict[str, Any], *, suffix: str = ".json"
@@ -163,7 +168,7 @@ def test_get_masks_secrets_and_reports_writable(tmp_path: Path, monkeypatch) ->
assert response.status_code == 200
payload = response.json()
- assert payload["config_path"] == str(path)
+ assert payload["config_path"] == path.name
assert payload["writable"] is True
assert payload["runtime_running"] is False
@@ -210,7 +215,7 @@ def test_get_reports_not_writable_for_yaml_config(tmp_path: Path, monkeypatch) -
assert response.status_code == 200
payload = response.json()
assert payload["writable"] is False
- assert payload["config_path"] == str(path)
+ assert payload["config_path"] == path.name
assert payload["channels"]["dingtalk"]["values"]["client_id"] == CLIENT_ID
assert STORED_SECRET not in response.text
@@ -228,6 +233,13 @@ def test_get_reports_runtime_running_from_live_status(tmp_path: Path, monkeypatc
assert payload["runtime_running"] is True
+def test_display_config_path_relativizes_home() -> None:
+ home = Path.home()
+
+ assert routes._display_config_path(home / "sub" / "agent.json") == "~/sub/agent.json"
+ assert routes._display_config_path(Path("/not-under-home/agent.json")) == "agent.json"
+
+
# --------------------------------------------------------------------------- #
# PUT /channels/config/{name}
# --------------------------------------------------------------------------- #
@@ -301,6 +313,49 @@ def test_put_enable_with_bad_credentials_is_blocked_before_write(
assert STORED_SECRET not in response.text
+def test_put_enable_rejection_carries_scrubbed_message(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, text=f"appSecret {STORED_SECRET} is invalid")
+
+ requests = _inject_mock_transport(monkeypatch, handler)
+
+ response = client.put("/channels/config/dingtalk", json={"config": {"enabled": True}})
+
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert detail["code"] == "invalid_credentials"
+ assert isinstance(detail["message"], str)
+ assert detail["message"]
+ assert len(requests) == 1
+ assert path.read_bytes() == before
+ assert STORED_SECRET not in response.text
+
+
+def test_put_enable_probe_exception_becomes_422_network(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ async def raising_probe(self) -> dict[str, Any]:
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(DingTalkChannel, "test_connection", raising_probe)
+
+ response = client.put("/channels/config/dingtalk", json={"config": {"enabled": True}})
+
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert detail["code"] == "network"
+ assert "boom" in detail["message"]
+ assert path.read_bytes() == before
+
+
def test_put_enable_skip_verify_writes_without_probe(tmp_path: Path, monkeypatch) -> None:
client, path = _client(
tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
@@ -358,6 +413,38 @@ def test_put_clear_flag_removes_stored_secret(tmp_path: Path, monkeypatch) -> No
assert STORED_SECRET not in response.text
+def test_put_rejects_unknown_config_keys(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ response = client.put(
+ "/channels/config/dingtalk",
+ json={"config": {"definitely_unknown_key": 1, "__proto__": 1}},
+ )
+
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert detail["code"] == "validation_error"
+ assert {"definitely_unknown_key", "__proto__"} <= set(detail["fields"])
+ assert path.read_bytes() == before
+
+
+def test_put_accepts_manager_override_keys(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"send_progress": True}}
+ )
+
+ assert response.status_code == 200
+ on_disk = json.loads(path.read_text(encoding="utf-8"))["channels"]["dingtalk"]
+ assert on_disk["send_progress"] is True
+
+
def test_put_yaml_config_returns_config_not_writable(tmp_path: Path, monkeypatch) -> None:
client, path = _client(
tmp_path,
@@ -416,8 +503,15 @@ def test_put_reload_failure_falls_back_to_reset_and_restart(
client, _ = _client(
tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
)
- resets: list[bool] = []
- monkeypatch.setattr(api_state, "reset_channel_runtime", lambda: resets.append(True))
+ new_runtime = FakeRuntime(running=False)
+
+ def _stub_get_channel_runtime() -> FakeRuntime:
+ # Mirror the real accessor's caching contract: the rebuilt singleton is
+ # observable on the host module, which is what `_hot_apply` leaves behind.
+ monkeypatch.setattr(api_server, "_channel_runtime", new_runtime)
+ return new_runtime
+
+ monkeypatch.setattr(api_server, "_get_channel_runtime", _stub_get_channel_runtime)
response = client.put(
"/channels/config/dingtalk", json={"config": {"client_id": "fallback-id"}}
@@ -425,9 +519,36 @@ def test_put_reload_failure_falls_back_to_reset_and_restart(
assert response.status_code == 200
assert response.json()["applied"] == "reset"
- assert resets == [True]
- # The fallback restarts through the same path /channels/start uses.
- assert runtime.start_calls == [True]
+ # The orphaned runtime is stopped before the reset + restart...
+ assert runtime.stop_calls == [True]
+ # ...and the old runtime is never restarted in its orphaned state.
+ assert runtime.start_calls == []
+ assert new_runtime.start_calls == [True]
+ assert api_server._channel_runtime is new_runtime
+
+
+def test_put_reload_failure_survives_a_wedged_stop(tmp_path: Path, monkeypatch) -> None:
+ class WedgedStopRuntime(FakeRuntime):
+ """A runtime whose stop() fails, standing in for a wedged adapter."""
+
+ async def stop(self) -> None:
+ raise RuntimeError("wedged")
+
+ runtime = WedgedStopRuntime(running=True, manager=FakeManager(fail=True))
+ client, _ = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
+ )
+ new_runtime = FakeRuntime(running=False)
+ monkeypatch.setattr(api_server, "_get_channel_runtime", lambda: new_runtime)
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_id": "fallback-id"}}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "reset"
+ # A failed stop must not block the rebuild.
+ assert new_runtime.start_calls == [True]
def test_concurrent_puts_serialize_per_channel(tmp_path: Path, monkeypatch) -> None:
@@ -538,6 +659,31 @@ def test_post_test_reports_invalid_credentials(tmp_path: Path, monkeypatch) -> N
assert path.read_bytes() == before
+def test_post_test_honors_pending_secret_clear(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover
+ raise AssertionError("a cleared credential must not reach the transport")
+
+ requests = _inject_mock_transport(monkeypatch, handler)
+
+ response = client.post(
+ "/channels/dingtalk/test", json={"config": {}, "clear_client_secret": True}
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is False
+ assert body["code"] == "invalid_credentials"
+ assert body["detail"] == "missing credentials"
+ # The stored secret was excluded from the probe, so nothing was sent.
+ assert requests == []
+ assert path.read_bytes() == before
+
+
def test_post_test_unsupported_channel_short_circuits(tmp_path: Path, monkeypatch) -> None:
client, path = _client(
tmp_path, monkeypatch, channels={"email": {"enabled": False}}
diff --git a/agent/tests/test_config_writer.py b/agent/tests/test_config_writer.py
index fd7565cc5..f3caa1f83 100644
--- a/agent/tests/test_config_writer.py
+++ b/agent/tests/test_config_writer.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import os
import stat
+import threading
from pathlib import Path
import pytest
@@ -126,3 +127,51 @@ def test_update_channel_section_sequential_writes_accumulate(tmp_path):
payload = _read(config_path)
assert payload["channels"]["feishu"] == {"enabled": True, "app_id": "cli_app"}
assert payload["channels"]["telegram"] == {"enabled": True, "token": "t"}
+
+
+def test_concurrent_writes_to_different_channels_both_survive(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Two threads patching different channels at once must not lose a patch.
+
+ The barrier forces both readers to overlap when the write lock is absent;
+ with the lock, the first reader times out at the barrier and the second runs
+ after the first write, so both sections land.
+ """
+ config_path = tmp_path / "agent.json"
+ config_path.write_text(json.dumps({"channels": {}}), encoding="utf-8")
+
+ import src.config.writer as writer
+
+ real_read = writer._read_config_file
+ barrier = threading.Barrier(2, timeout=1.0)
+
+ def synchronized_read(path: Path) -> dict:
+ payload = real_read(path)
+ try:
+ barrier.wait()
+ except threading.BrokenBarrierError:
+ # Expected when the write lock serialized the two readers.
+ pass
+ return payload
+
+ monkeypatch.setattr(writer, "_read_config_file", synchronized_read)
+
+ def patch_channel(channel: str) -> None:
+ update_channel_section(
+ channel, {"token": f"{channel}-token"}, config_path=config_path
+ )
+
+ threads = [
+ threading.Thread(target=patch_channel, args=("feishu",)),
+ threading.Thread(target=patch_channel, args=("telegram",)),
+ ]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout=10)
+ assert not thread.is_alive()
+
+ payload = _read(config_path)
+ assert payload["channels"]["feishu"] == {"token": "feishu-token"}
+ assert payload["channels"]["telegram"] == {"token": "telegram-token"}