Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: add Longbridge connector runtime connection card

rooteecb86e1bcbc
diff --git a/agent/tests/test_longbridge_runtime.py b/agent/tests/test_longbridge_runtime.py
new file mode 100644
index 000000000..082560aef
--- /dev/null
+++ b/agent/tests/test_longbridge_runtime.py
@@ -0,0 +1,1019 @@
+"""Tests for Longbridge transport-neutral connector runtime status.
+
+Task 3: extends the live-trading runtime to surface Longbridge broker_sdk
+profiles through the profile registry (not a hard-coded broker list), adds a
+read-only idempotent ``POST /live/connectors/{profile_id}/verify`` endpoint,
+and a bounded 15-second credential-free cache with fake-clock and force-bypass
+coverage.
+
+All tests run against stubs — no network, no real broker SDKs, no raw
+credential/broker exception leakage.
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+
+pytestmark = pytest.mark.unit
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _client(tmp_path: Path, monkeypatch) -> TestClient:
+ """Build a TestClient with runtime root redirected under tmp_path."""
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)
+ monkeypatch.setattr(api_server, "_runner_tasks", {}, raising=False)
+ monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)
+ # Reset the connector verify cache between tests
+ api_server._connector_verify_cache.clear()
+ return TestClient(api_server.app, client=("127.0.0.1", 50001))
+
+
+# ---------------------------------------------------------------------------
+# GET /live/status — Longbridge profiles via the registry
+# ---------------------------------------------------------------------------
+
+
+def test_live_status_includes_longbridge_sdk_profile(tmp_path: Path, monkeypatch) -> None:
+ """Longbridge live-sdk-readonly appears in /live/status via the profile registry."""
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/live/status")
+
+ assert response.status_code == 200
+ brokers = {b["auth"]["broker"]: b for b in response.json()["brokers"]}
+ assert "longbridge" in brokers
+ lb = brokers["longbridge"]
+ # Longbridge is a broker_sdk transport — no oauth_token_present, no mandate, runner dead.
+ # broker_sdk connectors are NOT in LIVE_BROKER_SERVER_KEYS, so is_live_broker=False
+ # (they don't use the OAuth/mandate path).
+ assert lb["auth"]["is_live_broker"] is False
+ assert lb["mandate"] is None
+ assert lb["runner"]["alive"] is False
+ assert lb["halted"] is False
+ # Transport-neutral fields should be present.
+ assert "transport" in lb["auth"]
+ assert lb["auth"]["transport"] == "broker_sdk"
+
+
+def test_longbridge_missing_credentials_maps_not_configured(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """When Longbridge SDK reports no credentials, status shows not_configured."""
+ client = _client(tmp_path, monkeypatch)
+
+ # Stub check_connection to return a not-configured report
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "status": "error",
+ "configured": False,
+ "connection_state": "not_configured",
+ "error": "Longbridge connector not configured: missing app_key.",
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": "longbridge-live-sdk-readonly",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ lb = response.json()["brokers"][0]
+ assert lb["auth"]["broker"] == "longbridge"
+ # The connector verify status should be surfaced.
+ assert lb["auth"]["transport"] == "broker_sdk"
+ assert lb["auth"]["connection_state"] == "not_configured"
+
+
+def test_longbridge_valid_check_maps_connected(tmp_path: Path, monkeypatch) -> None:
+ """When Longbridge SDK reports ok, status shows connected."""
+ client = _client(tmp_path, monkeypatch)
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "status": "ok",
+ "configured": True,
+ "connection_state": "connected",
+ "error": None,
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": "longbridge-live-sdk-readonly",
+ "sdk": {"package": "longbridge", "installed": True},
+ "paper_guard": "config_declared",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ lb = response.json()["brokers"][0]
+ assert lb["auth"]["connection_state"] == "connected"
+ assert lb["auth"]["oauth_token_present"] is False
+ assert lb["auth"]["profile_id"] == "longbridge-live-sdk-readonly"
+ assert lb["auth"]["sdk_installed"] is True
+ assert lb["auth"]["environment_identity"] == "config_declared"
+ assert lb["auth"]["capabilities"] == [
+ "account.read",
+ "positions.read",
+ "orders.read",
+ "quotes.read",
+ "history.read",
+ ]
+ assert lb["auth"]["readonly"] is True
+
+
+def test_live_status_propagates_only_sanitized_sdk_metadata(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Live status exposes the explicit SDK metadata allowlist and no secrets."""
+ client = _client(tmp_path, monkeypatch)
+ sentinels = {
+ "app_key": "SENTINEL_APP_KEY",
+ "app_secret": "SENTINEL_APP_SECRET",
+ "access_token": "SENTINEL_ACCESS_TOKEN",
+ }
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "status": "ok",
+ "profile_id": profile_id,
+ "configured": True,
+ "credential_source": "environment",
+ "sdk_installed": True,
+ "sdk": {"package": "longbridge", "installed": True},
+ "environment_identity": "config_declared_live",
+ "capabilities": [
+ "account.read",
+ "positions.read",
+ "orders.read",
+ "quotes.read",
+ "history.read",
+ ],
+ "readonly": True,
+ "last_checked_at": "2026-07-16T12:34:56Z",
+ "error_code": None,
+ "connection_state": "connected",
+ "config": sentinels,
+ "app_key": sentinels["app_key"],
+ "exception": f"raw SDK failure: {sentinels['access_token']}",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth == {
+ "broker": "longbridge",
+ "oauth_token_present": False,
+ "is_live_broker": False,
+ "transport": "broker_sdk",
+ "connection_state": "connected",
+ "profile_id": "longbridge-live-sdk-readonly",
+ "configured": True,
+ "credential_source": "environment",
+ "sdk_installed": True,
+ "environment_identity": "config_declared_live",
+ "capabilities": [
+ "account.read",
+ "positions.read",
+ "orders.read",
+ "quotes.read",
+ "history.read",
+ ],
+ "readonly": True,
+ "last_checked_at": "2026-07-16T12:34:56Z",
+ "error_code": None,
+ }
+ serialized = response.text
+ assert "config" not in auth
+ assert "app_key" not in auth
+ assert "exception" not in auth
+ assert all(secret not in serialized for secret in sentinels.values())
+
+
+def test_live_status_suppresses_secrets_in_allowlisted_text_metadata(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Report-controlled text/list fields cannot reflect secrets or raw errors."""
+ client = _client(tmp_path, monkeypatch)
+ sentinels = {
+ "configured": "raw SDK failure: SENTINEL_SECRET_IN_CONFIGURED",
+ "credential_source": "SENTINEL_APP_SECRET_IN_CREDENTIAL_SOURCE",
+ "sdk_installed": "raw SDK failure: SENTINEL_SECRET_IN_SDK_INSTALLED",
+ "sdk_nested_installed": "SENTINEL_SECRET_IN_NESTED_SDK_INSTALLED",
+ "environment_identity": "SENTINEL_ACCESS_TOKEN_IN_ENVIRONMENT_IDENTITY",
+ "paper_guard": "raw SDK failure: SENTINEL_APP_KEY_IN_PAPER_GUARD",
+ "capabilities": "SENTINEL_ACCESS_TOKEN_IN_CAPABILITY",
+ "readonly": "raw SDK failure: SENTINEL_SECRET_IN_READONLY",
+ "last_checked_at": "raw SDK failure: SENTINEL_SECRET_IN_TIMESTAMP",
+ "error_code": "raw SDK failure: SENTINEL_SECRET_IN_ERROR_CODE",
+ "connection_state": "raw SDK failure: SENTINEL_SECRET_IN_CONNECTION_STATE",
+ }
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "configured": sentinels["configured"],
+ "credential_source": sentinels["credential_source"],
+ "sdk_installed": sentinels["sdk_installed"],
+ "sdk": {"installed": sentinels["sdk_nested_installed"]},
+ "environment_identity": sentinels["environment_identity"],
+ "paper_guard": sentinels["paper_guard"],
+ "capabilities": ["account.read", sentinels["capabilities"]],
+ "readonly": sentinels["readonly"],
+ "last_checked_at": sentinels["last_checked_at"],
+ "error_code": sentinels["error_code"],
+ "connection_state": sentinels["connection_state"],
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["configured"] is None
+ assert auth["credential_source"] is None
+ assert auth["sdk_installed"] is None
+ assert auth["environment_identity"] is None
+ assert auth["capabilities"] == [
+ "account.read",
+ "positions.read",
+ "orders.read",
+ "quotes.read",
+ "history.read",
+ ]
+ assert auth["last_checked_at"] is None
+ assert auth["error_code"] is None
+ assert auth["connection_state"] is None
+ assert all(value not in response.text for value in sentinels.values())
+
+
+def test_live_status_uses_registry_profile_id(tmp_path: Path, monkeypatch) -> None:
+ """Status verifies the selected registry profile, never a derived id."""
+ client = _client(tmp_path, monkeypatch)
+ registry_profile = SimpleNamespace(
+ id="longbridge-production-custom-readonly",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read",),
+ readonly=True,
+ )
+ monkeypatch.setattr(
+ "src.trading.profiles.list_profiles", lambda: [registry_profile]
+ )
+ checked_profiles: list[str] = []
+
+ def _check_status(profile_id: str, force: bool = False):
+ checked_profiles.append(profile_id)
+ return {
+ "profile_id": profile_id,
+ "connection_state": "connected",
+ }
+
+ monkeypatch.setattr(api_server, "_check_connector_status", _check_status)
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ assert checked_profiles == [registry_profile.id]
+ assert response.json()["brokers"][0]["auth"]["profile_id"] == registry_profile.id
+
+
+def test_live_status_accepts_known_metadata_values_and_canonicalizes_timestamp(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Closed-vocabulary Longbridge metadata and valid UTC timestamps pass."""
+ client = _client(tmp_path, monkeypatch)
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "configured": False,
+ "credential_source": "runtime_file",
+ "sdk_installed": False,
+ "environment_identity": "config_declared",
+ "capabilities": ["orders.place"],
+ "readonly": False,
+ "last_checked_at": "2026-07-16T12:34:56+00:00",
+ "error_code": "credentials_partial",
+ "connection_state": "error",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["configured"] is False
+ assert auth["credential_source"] == "runtime_file"
+ assert auth["sdk_installed"] is False
+ assert auth["environment_identity"] == "config_declared"
+ assert auth["capabilities"] == [
+ "account.read",
+ "positions.read",
+ "orders.read",
+ "quotes.read",
+ "history.read",
+ ]
+ assert auth["readonly"] is True
+ assert auth["last_checked_at"] == "2026-07-16T12:34:56Z"
+ assert auth["error_code"] == "credentials_partial"
+ assert auth["connection_state"] == "error"
+
+
+ ("error_code", "connection_state"),
+ [
+ ("credentials_missing", "not_configured"),
+ ("credentials_conflict", "error"),
+ ("sdk_missing", "error"),
+ ("authentication_failed", "error"),
+ ("network_unreachable", "error"),
+ ("broker_error", "error"),
+ ],
+)
+def test_live_status_accepts_known_longbridge_error_codes(
+ tmp_path: Path,
+ monkeypatch,
+ error_code: str,
+ connection_state: str,
+) -> None:
+ """Every stable Longbridge diagnostic code survives closed-vocabulary mapping."""
+ client = _client(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "error_code": error_code,
+ "connection_state": connection_state,
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["error_code"] == error_code
+ assert auth["connection_state"] == connection_state
+
+
+def test_live_status_normalizes_same_profile_malformed_metadata(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Malformed same-profile values are suppressed without response failure."""
+ client = _client(tmp_path, monkeypatch)
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "configured": "true",
+ "credential_source": ["environment"],
+ "sdk_installed": {"installed": True},
+ "sdk": {"installed": "yes"},
+ "environment_identity": {"kind": "config_declared"},
+ "paper_guard": ["config_declared"],
+ "capabilities": {"account.read": True},
+ "readonly": "true",
+ "last_checked_at": "not-a-timestamp",
+ "error_code": ["authentication_failed"],
+ "connection_state": {"state": "connected"},
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["profile_id"] == "longbridge-live-sdk-readonly"
+ assert auth["configured"] is None
+ assert auth["credential_source"] is None
+ assert auth["sdk_installed"] is None
+ assert auth["environment_identity"] is None
+ assert auth["capabilities"] == [
+ "account.read",
+ "positions.read",
+ "orders.read",
+ "quotes.read",
+ "history.read",
+ ]
+ assert auth["readonly"] is True
+ assert auth["last_checked_at"] is None
+ assert auth["error_code"] is None
+ assert auth["connection_state"] is None
+
+
+def test_live_status_suppresses_unrepresentable_timestamp_only(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """UTC conversion overflow cannot discard otherwise valid safe metadata."""
+ client = _client(tmp_path, monkeypatch)
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "configured": True,
+ "credential_source": "environment",
+ "sdk_installed": True,
+ "environment_identity": "config_declared",
+ "last_checked_at": "0001-01-01T00:00:00+23:59",
+ "error_code": None,
+ "connection_state": "connected",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["configured"] is True
+ assert auth["credential_source"] == "environment"
+ assert auth["sdk_installed"] is True
+ assert auth["environment_identity"] == "config_declared"
+ assert auth["last_checked_at"] is None
+ assert auth["connection_state"] == "connected"
+
+
+def test_live_status_normalizes_null_permission_metadata_from_safe_registry_profile(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Null report permissions fall back to a complete typed registry declaration."""
+ client = _client(tmp_path, monkeypatch)
+ registry_profile = SimpleNamespace(
+ id="longbridge-production-custom-readonly",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read", "positions.read"),
+ readonly=True,
+ )
+ monkeypatch.setattr(
+ "src.trading.profiles.list_profiles", lambda: [registry_profile]
+ )
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "configured": True,
+ "connection_state": "connected",
+ "capabilities": None,
+ "readonly": None,
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["capabilities"] == ["account.read", "positions.read"]
+ assert auth["readonly"] is True
+
+
+def test_live_status_does_not_assert_readonly_without_complete_safe_capabilities(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Malformed report and registry capabilities keep the permission claim unknown."""
+ client = _client(tmp_path, monkeypatch)
+ registry_profile = SimpleNamespace(
+ id="longbridge-production-custom-readonly",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=(),
+ readonly=True,
+ )
+ monkeypatch.setattr(
+ "src.trading.profiles.list_profiles", lambda: [registry_profile]
+ )
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "profile_id": profile_id,
+ "configured": True,
+ "connection_state": "connected",
+ "capabilities": {"account.read": True},
+ "readonly": "true",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["capabilities"] is None
+ assert auth["readonly"] is None
+
+
+def test_live_status_metadata_fallbacks_require_matching_profile(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Registry metadata stays fail-closed when verify identifies another profile."""
+ client = _client(tmp_path, monkeypatch)
+
+ profile_id_sentinel = "raw SDK failure: SENTINEL_SECRET_IN_PROFILE_ID"
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "status": "ok",
+ "profile_id": profile_id_sentinel,
+ "configured": True,
+ "connection_state": "connected",
+ "credential_source": "environment",
+ "sdk_installed": True,
+ "environment_identity": "config_declared_live",
+ "capabilities": ["orders.place"],
+ "readonly": False,
+ "last_checked_at": "2026-07-16T12:34:56Z",
+ "error_code": "authentication_failed",
+ },
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ auth = response.json()["brokers"][0]["auth"]
+ for field in (
+ "profile_id",
+ "configured",
+ "connection_state",
+ "credential_source",
+ "sdk_installed",
+ "environment_identity",
+ "capabilities",
+ "readonly",
+ "last_checked_at",
+ "error_code",
+ ):
+ assert auth[field] is None
+ assert profile_id_sentinel not in response.text
+
+
+# ---------------------------------------------------------------------------
+# POST /live/connectors/{profile_id}/verify — read-only, idempotent
+# ---------------------------------------------------------------------------
+
+
+def test_verify_endpoint_is_readonly_and_idempotent(tmp_path: Path, monkeypatch) -> None:
+ """Verify is read-only (GET-like safety), idempotent, and never needs a mandate."""
+ client = _client(tmp_path, monkeypatch)
+
+ # Two calls with the same profile return the same result
+ payload = {"profile_id": "longbridge-live-sdk-readonly"}
+
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: {
+ "status": "ok",
+ "configured": True,
+ "connection_state": "connected",
+ "error": None,
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": profile_id,
+ },
+ )
+
+ r1 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+ r2 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+
+ assert r1.status_code == 200
+ assert r2.status_code == 200
+ body1 = r1.json()
+ body2 = r2.json()
+ # Idempotent: same status, no side effects
+ assert body1["status"] == body2["status"]
+ assert body1["connection_state"] == body2["connection_state"]
+
+
+def test_verify_rejects_non_live_and_remote_mcp_profiles(tmp_path: Path, monkeypatch) -> None:
+ """Verify must reject paper profiles, remote_mcp live profiles, and unknown IDs
+ with the correct HTTP status *before* calling check_connection.
+
+ Rejected profiles:
+ - ``longbridge-paper-sdk``: environment=paper → 400
+ - ``robinhood-live-mcp``: transport=remote_mcp → 400
+ - ``unknown-profile-id``: not in registry → 404
+
+ The underlying ``check_connection`` must NEVER be called for any rejected profile.
+ """
+ client = _client(tmp_path, monkeypatch)
+ check_calls: list[str] = []
+
+ def _spy_check_connection(profile_id, **kwargs):
+ check_calls.append(profile_id)
+ return {
+ "status": "ok",
+ "configured": True,
+ "connection_state": "connected",
+ "error": None,
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": profile_id,
+ }
+
+ monkeypatch.setattr("src.trading.service.check_connection", _spy_check_connection)
+
+ # Paper profile → 400 (environment != live)
+ r_paper = client.post("/live/connectors/longbridge-paper-sdk/verify")
+ assert r_paper.status_code == 400
+ assert "not a live profile" in r_paper.json()["detail"].lower()
+
+ # Remote MCP live profile → 400 (transport != broker_sdk)
+ r_mcp = client.post("/live/connectors/robinhood-live-mcp/verify")
+ assert r_mcp.status_code == 400
+ assert "broker_sdk" in r_mcp.json()["detail"].lower()
+
+ # Unknown profile → 404
+ r_unknown = client.post("/live/connectors/unknown-profile-id/verify")
+ assert r_unknown.status_code == 404
+ assert "unknown" in r_unknown.json()["detail"].lower()
+
+ # check_connection must NOT have been called for any rejected profile
+ assert check_calls == [], (
+ f"check_connection was called for rejected profiles: {check_calls}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Verify: credential-free cache with fake clock
+# ---------------------------------------------------------------------------
+
+
+def test_verify_cache_hit_and_expiry(tmp_path: Path, monkeypatch) -> None:
+ """Cache returns same result within 15s window; expires after."""
+ client = _client(tmp_path, monkeypatch)
+ call_count = {"n": 0}
+
+ def _stub_check_connection(profile_id, **kwargs):
+ call_count["n"] += 1
+ return {
+ "status": "ok",
+ "configured": True,
+ "connection_state": "connected",
+ "error": None,
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": profile_id,
+ }
+
+ monkeypatch.setattr("src.trading.service.check_connection", _stub_check_connection)
+
+ # First call — cache miss
+ r1 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+ assert r1.status_code == 200
+ assert call_count["n"] == 1
+
+ # Second call — cache hit (no new check_connection call)
+ r2 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+ assert r2.status_code == 200
+ assert call_count["n"] == 1 # still 1
+
+ # Simulate time advancing past 15s TTL
+ api_server._connector_verify_cache._clock = lambda: time.time() + 20
+
+ r3 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+ assert r3.status_code == 200
+ assert call_count["n"] == 2 # cache expired, new call
+
+
+def test_verify_force_bypass_cache(tmp_path: Path, monkeypatch) -> None:
+ """force=True bypasses the cache and forces a fresh check."""
+ client = _client(tmp_path, monkeypatch)
+ call_count = {"n": 0}
+
+ def _stub_check_connection(profile_id, **kwargs):
+ call_count["n"] += 1
+ return {
+ "status": "ok",
+ "configured": True,
+ "connection_state": "connected",
+ "error": None,
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": profile_id,
+ }
+
+ monkeypatch.setattr("src.trading.service.check_connection", _stub_check_connection)
+
+ # First call
+ r1 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+ assert call_count["n"] == 1
+
+ # force=True bypasses cache
+ r2 = client.post("/live/connectors/longbridge-live-sdk-readonly/verify?force=true")
+ assert call_count["n"] == 2
+ assert r2.status_code == 200
+
+
+# ---------------------------------------------------------------------------
+# Backward compatibility: Robinhood OAuth fields remain
+# ---------------------------------------------------------------------------
+
+
+def test_live_status_selects_readonly_sdk_profile_independent_of_registry_order(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """A live readonly SDK profile wins deterministically over a trading profile."""
+ client = _client(tmp_path, monkeypatch)
+ profiles = [
+ SimpleNamespace(
+ id="longbridge-live-trade-readonly",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read", "orders.place.requires_mandate"),
+ readonly=False,
+ ),
+ SimpleNamespace(
+ id="longbridge-live-observer",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read",),
+ readonly=True,
+ ),
+ ]
+ monkeypatch.setattr("src.trading.profiles.list_profiles", lambda: profiles)
+ checked_profiles: list[str] = []
+
+ def _check_status(profile_id: str, force: bool = False):
+ checked_profiles.append(profile_id)
+ return {"profile_id": profile_id, "connection_state": "connected"}
+
+ monkeypatch.setattr(api_server, "_check_connector_status", _check_status)
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ assert checked_profiles == ["longbridge-live-observer"]
+ assert response.json()["brokers"][0]["auth"]["readonly"] is True
+
+
+def test_live_status_prefers_unique_suffixed_declared_readonly_profile(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """One canonical -readonly profile wins over another declared observer profile."""
+ client = _client(tmp_path, monkeypatch)
+ profiles = [
+ SimpleNamespace(
+ id="longbridge-live-observer",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("positions.read",),
+ readonly=True,
+ ),
+ SimpleNamespace(
+ id="longbridge-live-sdk-readonly",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read",),
+ readonly=True,
+ ),
+ ]
+ monkeypatch.setattr("src.trading.profiles.list_profiles", lambda: profiles)
+ checked_profiles: list[str] = []
+
+ def _check_status(profile_id: str, force: bool = False):
+ checked_profiles.append(profile_id)
+ return {"profile_id": profile_id, "connection_state": "connected"}
+
+ monkeypatch.setattr(api_server, "_check_connector_status", _check_status)
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ assert checked_profiles == ["longbridge-live-sdk-readonly"]
+ assert response.json()["brokers"][0]["auth"]["capabilities"] == ["account.read"]
+
+
+def test_live_status_rejects_malformed_registry_profile_id(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """A non-string trusted-registry profile ID fails closed without verification."""
+ client = _client(tmp_path, monkeypatch)
+ malformed_profile = SimpleNamespace(
+ id=123,
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read",),
+ readonly=True,
+ )
+ monkeypatch.setattr(
+ "src.trading.profiles.list_profiles", lambda: [malformed_profile]
+ )
+ checked_profiles: list[object] = []
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: checked_profiles.append(profile_id) or {},
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ assert checked_profiles == []
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["transport"] == "broker_sdk"
+ assert auth["profile_id"] is None
+ assert auth["capabilities"] is None
+ assert auth["readonly"] is None
+
+
+def test_live_status_rejects_ambiguous_readonly_sdk_profiles(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Multiple live SDK readonly profiles fail closed without verifying either."""
+ client = _client(tmp_path, monkeypatch)
+ profiles = [
+ SimpleNamespace(
+ id="longbridge-live-alpha-observer",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("account.read",),
+ readonly=True,
+ ),
+ SimpleNamespace(
+ id="longbridge-live-beta-observer",
+ connector="longbridge",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=("positions.read",),
+ readonly=True,
+ ),
+ ]
+ monkeypatch.setattr("src.trading.profiles.list_profiles", lambda: profiles)
+ checked_profiles: list[str] = []
+ monkeypatch.setattr(
+ api_server,
+ "_check_connector_status",
+ lambda profile_id, force=False: checked_profiles.append(profile_id) or {},
+ )
+
+ response = client.get("/live/status", params={"broker": "longbridge"})
+
+ assert response.status_code == 200
+ assert checked_profiles == []
+ auth = response.json()["brokers"][0]["auth"]
+ assert auth["transport"] == "broker_sdk"
+ for field in (
+ "profile_id",
+ "configured",
+ "connection_state",
+ "credential_source",
+ "sdk_installed",
+ "environment_identity",
+ "capabilities",
+ "readonly",
+ "last_checked_at",
+ "error_code",
+ ):
+ assert auth[field] is None
+
+
+def test_live_status_preserves_first_transport_for_multi_profile_non_sdk_broker(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """IBKR keeps its first live transport while SDK selection scans independently."""
+ client = _client(tmp_path, monkeypatch)
+ profiles = [
+ SimpleNamespace(
+ id="ibkr-live-local-readonly",
+ connector="ibkr",
+ environment="live",
+ transport="local_tws",
+ capabilities=("account.read",),
+ readonly=True,
+ ),
+ SimpleNamespace(
+ id="ibkr-live-official-mcp-readonly",
+ connector="ibkr",
+ environment="live",
+ transport="remote_mcp",
+ capabilities=("mcp.read.discovery",),
+ readonly=True,
+ ),
+ ]
+ monkeypatch.setattr("src.trading.profiles.list_profiles", lambda: profiles)
+
+ response = client.get("/live/status", params={"broker": "ibkr"})
+
+ assert response.status_code == 200
+ assert response.json()["brokers"][0]["auth"]["transport"] == "local_tws"
+
+
+def test_existing_robinhood_oauth_fields_remain_compatible(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Robinhood status still exposes oauth_token_present — no regression."""
+ client = _client(tmp_path, monkeypatch)
+
+ response = client.get("/live/status", params={"broker": "robinhood"})
+
+ assert response.status_code == 200
+ rh = response.json()["brokers"][0]
+ assert rh["auth"]["broker"] == "robinhood"
+ assert rh["auth"]["oauth_token_present"] is False
+ assert rh["auth"]["is_live_broker"] is True
+ # transport field should also be present now
+ assert "transport" in rh["auth"]
+ # Robinhood is remote_mcp, not broker_sdk
+ assert rh["auth"]["transport"] == "remote_mcp"
+
+
+# ---------------------------------------------------------------------------
+# Longbridge verify never needs a mandate, runner is unavailable
+# ---------------------------------------------------------------------------
+
+
+def test_longbridge_verify_never_needs_mandate_and_runner_unavailable(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Longbridge verify is read-only; no mandate required, runner is unavailable."""
+ client = _client(tmp_path, monkeypatch)
+
+ # Verify call succeeds without any mandate
+ r = client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+ # It may fail because _check_connector_status is not yet implemented (RED phase)
+ # or return an error status — but it must NOT return 409 (mandate required)
+ assert r.status_code != 409
+
+ # Runner start must fail for longbridge
+ r2 = client.post("/live/runner/start", json={"broker": "longbridge"})
+ assert r2.status_code == 400
+ assert "runner" in r2.json()["detail"].lower()
+
+
+# ---------------------------------------------------------------------------
+# Cache contains no credentials (structural check)
+# ---------------------------------------------------------------------------
+
+
+def test_cache_contains_no_credentials(tmp_path: Path, monkeypatch) -> None:
+ """The verify cache entry must never store credential material.
+
+ Patches the underlying ``src.trading.service.check_connection`` so the
+ real cache wrapper (``_ConnectorVerifyCache``) is exercised, NOT the
+ top-level ``_check_connector_status`` function (which would bypass the
+ cache entirely).
+ """
+ client = _client(tmp_path, monkeypatch)
+
+ def _stub_check(profile_id, **kwargs):
+ return {
+ "status": "ok",
+ "configured": True,
+ "connection_state": "connected",
+ "error": None,
+ "connector": "longbridge",
+ "transport": "broker_sdk",
+ "profile_id": profile_id,
+ "config": {"app_key": "FAKE***", "app_secret": "***redacted***"},
+ }
+
+ monkeypatch.setattr("src.trading.service.check_connection", _stub_check)
+
+ client.post("/live/connectors/longbridge-live-sdk-readonly/verify")
+
+ # Inspect the cache directly — must exercise the real cache wrapper
+ cache_entry = api_server._connector_verify_cache.get("longbridge-live-sdk-readonly")
+ assert cache_entry is not None
+ serialized = str(cache_entry)
+ assert "FAKE" not in serialized
+ assert "redacted" not in serialized
+ # Cache should only store status-level fields, not config details
+ assert "app_key" not in serialized
+ assert "app_secret" not in serialized
diff --git a/frontend/src/components/chat/RunnerStatus.tsx b/frontend/src/components/chat/RunnerStatus.tsx
index 14adbb64d..60b4058a1 100644
--- a/frontend/src/components/chat/RunnerStatus.tsx
+++ b/frontend/src/components/chat/RunnerStatus.tsx
@@ -275,15 +275,24 @@ function BrokerRow({
* runtime execution. Runner start/stop are privileged surface fetches (`api.startLiveRunner` /
* `api.stopLiveRunner`), never chat messages. Collapses to a compact toggle.
*/
+export function isVisibleRuntimeConnector(broker: LiveBrokerStatus): boolean {
+ const auth = broker.auth;
+ if (auth.oauth_token_present || auth.configured === true) return true;
+ return auth.connection_state === "connected" || auth.connection_state === "ready";
+}
+
export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, halted, onRefresh }: Props) {
const [open, setOpen] = useState(false);
+ const visibleBrokers = status?.brokers.filter(isVisibleRuntimeConnector) ?? [];
if (unavailable) return null;
- if (!status || status.brokers.length === 0) return null;
+ if (!status || visibleBrokers.length === 0) return null;
const isHalted = halted ?? status.global_halted;
- const anyRunning = status.brokers.some((b) => b.runner?.alive);
- const authorizedCount = status.brokers.filter((b) => b.auth.oauth_token_present).length;
+ const anyRunning = visibleBrokers.some((b) => b.runner?.alive);
+ const authorizedCount = visibleBrokers.filter(
+ (b) => b.auth.oauth_token_present || b.auth.connection_state === "connected"
+ ).length;
return (
<div className="grid gap-2">
@@ -315,8 +324,12 @@ export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, ha
</button>
{open && (
- <div className="grid gap-2 rounded-xl border border-primary/20 bg-background/95 p-3 shadow-sm">
- {status.brokers.map((broker) => (
+ <div
+ role="region"
+ aria-label={i18n.t("runnerStatus.configuredProfiles")}
+ className="grid max-h-[min(70vh,36rem)] gap-2 overflow-y-auto rounded-xl border border-primary/20 bg-background/95 p-3 shadow-sm"
+ >
+ {visibleBrokers.map((broker) => (
<BrokerRow key={broker.auth.broker} broker={broker} halted={isHalted || broker.halted} onRefresh={onRefresh} />
))}
</div>
diff --git a/frontend/src/components/chat/__tests__/RunnerStatus.test.tsx b/frontend/src/components/chat/__tests__/RunnerStatus.test.tsx
new file mode 100644
index 000000000..de8ae2c65
--- /dev/null
+++ b/frontend/src/components/chat/__tests__/RunnerStatus.test.tsx
@@ -0,0 +1,127 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { RunnerStatus } from "../RunnerStatus";
+import type { LiveBrokerStatus, LiveStatus } from "@/lib/api";
+import i18n from "@/i18n";
+
+const apiMock = vi.hoisted(() => ({
+ authorizeLive: vi.fn(),
+ startLiveRunner: vi.fn(),
+ stopLiveRunner: vi.fn(),
+}));
+
+vi.mock("@/lib/api", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
+ return { ...actual, api: apiMock };
+});
+
+function broker(
+ name: string,
+ auth: Partial<LiveBrokerStatus["auth"]> = {},
+): LiveBrokerStatus {
+ return {
+ auth: {
+ broker: name,
+ oauth_token_present: false,
+ is_live_broker: false,
+ ...auth,
+ },
+ mandate: null,
+ runner: { broker: name, alive: false, last_tick: null },
+ halted: false,
+ };
+}
+
+function status(brokers: LiveBrokerStatus[]): LiveStatus {
+ return { global_halted: false, brokers };
+}
+
+describe("RunnerStatus compact connector panel", () => {
+ beforeEach(() => {
+ apiMock.authorizeLive.mockResolvedValue({
+ broker: "test",
+ connector_profile: "test-live-sdk-readonly",
+ oauth_token_present: false,
+ instruction: "Configure this connector.",
+ note: "Read-only.",
+ });
+ });
+
+ it("shows relevant connectors and hides an unconfigured connector", async () => {
+ const user = userEvent.setup();
+ render(
+ <RunnerStatus
+ status={status([
+ broker("alpaca", { configured: false, connection_state: "not_configured", transport: "broker_sdk" }),
+ broker("longbridge", { configured: true, connection_state: "connected", transport: "broker_sdk" }),
+ broker("binance", { configured: true, connection_state: "ready", transport: "broker_sdk" }),
+ broker("futu", { configured: true, connection_state: null, transport: "broker_sdk" }),
+ broker("okx", { configured: true, connection_state: "error", transport: "broker_sdk" }),
+ broker("ibkr", { oauth_token_present: true, is_live_broker: true, transport: "remote_mcp" }),
+ ])}
+ onRefresh={vi.fn()}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: /connector runtime/i }));
+
+ expect(screen.queryByText("alpaca", { exact: false })).not.toBeInTheDocument();
+ expect(screen.getByText("longbridge", { exact: false })).toBeInTheDocument();
+ expect(screen.getByText("binance", { exact: false })).toBeInTheDocument();
+ expect(screen.getByText("futu", { exact: false })).toBeInTheDocument();
+ expect(screen.getByText("okx", { exact: false })).toBeInTheDocument();
+ expect(screen.getByText("ibkr", { exact: false })).toBeInTheDocument();
+ });
+
+ it.each([false, null])(
+ "keeps connected and ready connectors visible when configured is %s",
+ async (configured) => {
+ const user = userEvent.setup();
+ render(
+ <RunnerStatus
+ status={status([
+ broker("connected-sdk", { configured, connection_state: "connected", transport: "broker_sdk" }),
+ broker("ready-sdk", { configured, connection_state: "ready", transport: "broker_sdk" }),
+ ])}
+ onRefresh={vi.fn()}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: /connector runtime/i }));
+
+ expect(screen.getByText("connected-sdk", { exact: false })).toBeInTheDocument();
+ expect(screen.getByText("ready-sdk", { exact: false })).toBeInTheDocument();
+ },
+ );
+
+ it("bounds the expanded connector list and enables internal vertical scrolling", async () => {
+ const user = userEvent.setup();
+ render(
+ <RunnerStatus
+ status={status([
+ broker("longbridge", { configured: true, connection_state: "connected", transport: "broker_sdk" }),
+ ])}
+ onRefresh={vi.fn()}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: /connector runtime/i }));
+
+ const list = screen.getByRole("region", { name: i18n.t("runnerStatus.configuredProfiles") });
+ expect(list).toHaveClass("max-h-[min(70vh,36rem)]", "overflow-y-auto");
+ });
+
+ it("hides the compact control when every connector is irrelevant", () => {
+ const { container } = render(
+ <RunnerStatus
+ status={status([
+ broker("alpaca", { configured: false, connection_state: "not_configured", transport: "broker_sdk" }),
+ broker("binance", { configured: false, connection_state: null, transport: "broker_sdk" }),
+ ])}
+ onRefresh={vi.fn()}
+ />,
+ );
+
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 38ce2b276..d221c64d0 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -78,7 +78,43 @@
"perDay": "/يوم",
"leverageSuffix": "ضعف الرافعة",
"never": "أبدًا",
- "ago": "منذ"
+ "ago": "منذ",
+ "notConfigured": "Not configured",
+ "readyToVerify": "Ready to verify",
+ "connectedReadOnly": "Connected · Read-only",
+ "connectionFailed": "Connection failed",
+ "verifyConnection": "Verify connection",
+ "retry": "Retry",
+ "credentialSource": "Credential source",
+ "sdk": "SDK",
+ "configDeclared": "Config-declared",
+ "connectorStatusUnavailable": "Status unavailable",
+ "connectedAccessUnknown": "Connected · Access unknown",
+ "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",
+ "sdkConnectorProfile": "Direct SDK connector · read-only profile",
+ "connectionDetails": "Connection details",
+ "environment": "Environment",
+ "environmentIdentity": "Declared environment",
+ "capabilities": "Capabilities",
+ "capabilityAccount": "Account",
+ "capabilityPositions": "positions",
+ "capabilityOpenOrders": "open orders",
+ "capabilityQuotes": "quotes",
+ "capabilityHistory": "history",
+ "readOnly": "read-only",
+ "accessUnknown": "access unknown",
+ "diagnostics": "Diagnostics",
+ "lastChecked": "Last checked",
+ "errorCode": "Error code",
+ "installed": "Installed",
+ "notInstalled": "Not installed",
+ "connectorVerifyFailed": "Connection verification failed.",
+ "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",
+ "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",
+ "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",
+ "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",
+ "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",
+ "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."
},
"reports": {
"badge": "التقارير",
@@ -662,6 +698,7 @@
},
"runnerStatus": {
"connectorRuntime": "وقت تشغيل الموصل",
+ "configuredProfiles": "ملفات تعريف وقت تشغيل الموصل المهيأة",
"connected": "{{count}} متصل",
"noConnector": "لا يوجد موصل متصل",
"running": "قيد التشغيل",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 99ad4386a..9fab60532 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -83,7 +83,43 @@
"perDay": "/day",
"leverageSuffix": "x leverage",
"never": "never",
- "ago": "ago"
+ "ago": "ago",
+ "notConfigured": "Not configured",
+ "readyToVerify": "Ready to verify",
+ "connectedReadOnly": "Connected · Read-only",
+ "connectionFailed": "Connection failed",
+ "verifyConnection": "Verify connection",
+ "retry": "Retry",
+ "credentialSource": "Credential source",
+ "sdk": "SDK",
+ "configDeclared": "Config-declared",
+ "connectorStatusUnavailable": "Status unavailable",
+ "connectedAccessUnknown": "Connected · Access unknown",
+ "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",
+ "sdkConnectorProfile": "Direct SDK connector · read-only profile",
+ "connectionDetails": "Connection details",
+ "environment": "Environment",
+ "environmentIdentity": "Declared environment",
+ "capabilities": "Capabilities",
+ "capabilityAccount": "Account",
+ "capabilityPositions": "positions",
+ "capabilityOpenOrders": "open orders",
+ "capabilityQuotes": "quotes",
+ "capabilityHistory": "history",
+ "readOnly": "read-only",
+ "accessUnknown": "access unknown",
+ "diagnostics": "Diagnostics",
+ "lastChecked": "Last checked",
+ "errorCode": "Error code",
+ "installed": "Installed",
+ "notInstalled": "Not installed",
+ "connectorVerifyFailed": "Connection verification failed.",
+ "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",
+ "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",
+ "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",
+ "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",
+ "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",
+ "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."
},
"reports": {
"badge": "Reports",
@@ -667,6 +703,7 @@
},
"runnerStatus": {
"connectorRuntime": "Connector runtime",
+ "configuredProfiles": "Configured connector runtime profiles",
"connected": "{{count}} connected",
"noConnector": "no connector connected",
"running": "running",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 48bfa1600..631104976 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -78,7 +78,43 @@
"perDay": "/日",
"leverageSuffix": "倍レバレッジ",
"never": "なし",
- "ago": "前"
+ "ago": "前",
+ "notConfigured": "Not configured",
+ "readyToVerify": "Ready to verify",
+ "connectedReadOnly": "Connected · Read-only",
+ "connectionFailed": "Connection failed",
+ "verifyConnection": "Verify connection",
+ "retry": "Retry",
+ "credentialSource": "Credential source",
+ "sdk": "SDK",
+ "configDeclared": "Config-declared",
+ "connectorStatusUnavailable": "Status unavailable",
+ "connectedAccessUnknown": "Connected · Access unknown",
+ "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",
+ "sdkConnectorProfile": "Direct SDK connector · read-only profile",
+ "connectionDetails": "Connection details",
+ "environment": "Environment",
+ "environmentIdentity": "Declared environment",
+ "capabilities": "Capabilities",
+ "capabilityAccount": "Account",
+ "capabilityPositions": "positions",
+ "capabilityOpenOrders": "open orders",
+ "capabilityQuotes": "quotes",
+ "capabilityHistory": "history",
+ "readOnly": "read-only",
+ "accessUnknown": "access unknown",
+ "diagnostics": "Diagnostics",
+ "lastChecked": "Last checked",
+ "errorCode": "Error code",
+ "installed": "Installed",
+ "notInstalled": "Not installed",
+ "connectorVerifyFailed": "Connection verification failed.",
+ "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",
+ "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",
+ "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",
+ "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",
+ "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",
+ "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."
},
"reports": {
"badge": "レポート",
@@ -662,6 +698,7 @@
},
"runnerStatus": {
"connectorRuntime": "コネクタランタイム",
+ "configuredProfiles": "設定済みコネクタランタイムプロファイル",
"connected": "{{count}} 件接続中",
"noConnector": "接続中のコネクタなし",
"running": "実行中",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 5fed68e3c..9ff95ebac 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -78,7 +78,43 @@
"perDay": "/일",
"leverageSuffix": "배 레버리지",
"never": "없음",
- "ago": "전"
+ "ago": "전",
+ "notConfigured": "Not configured",
+ "readyToVerify": "Ready to verify",
+ "connectedReadOnly": "Connected · Read-only",
+ "connectionFailed": "Connection failed",
+ "verifyConnection": "Verify connection",
+ "retry": "Retry",
+ "credentialSource": "Credential source",
+ "sdk": "SDK",
+ "configDeclared": "Config-declared",
+ "connectorStatusUnavailable": "Status unavailable",
+ "connectedAccessUnknown": "Connected · Access unknown",
+ "missingLongbridgeVariables": "Missing configuration. Configure these variables in agent/.env and recreate the service:",
+ "sdkConnectorProfile": "Direct SDK connector · read-only profile",
+ "connectionDetails": "Connection details",
+ "environment": "Environment",
+ "environmentIdentity": "Declared environment",
+ "capabilities": "Capabilities",
+ "capabilityAccount": "Account",
+ "capabilityPositions": "positions",
+ "capabilityOpenOrders": "open orders",
+ "capabilityQuotes": "quotes",
+ "capabilityHistory": "history",
+ "readOnly": "read-only",
+ "accessUnknown": "access unknown",
+ "diagnostics": "Diagnostics",
+ "lastChecked": "Last checked",
+ "errorCode": "Error code",
+ "installed": "Installed",
+ "notInstalled": "Not installed",
+ "connectorVerifyFailed": "Connection verification failed.",
+ "diagnosticCredentialsPartial": "Credentials are incomplete. Configure all required variables and recreate the service.",
+ "diagnosticCredentialsConflict": "Credential sources conflict. Keep one complete source, then retry.",
+ "diagnosticSdkMissing": "The Longbridge SDK is not installed in the backend service.",
+ "diagnosticAuthenticationFailed": "Authentication failed. Check the configured credentials.",
+ "diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.",
+ "diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."
},
"reports": {
"badge": "리포트",
@@ -662,6 +698,7 @@
},
"runnerStatus": {
"connectorRuntime": "커넥터 런타임",
+ "configuredProfiles": "구성된 커넥터 런타임 프로필",
"connected": "{{count}}개 연결됨",
"noConnector": "연결된 커넥터 없음",
"running": "실행 중",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index a612e2553..52a77b2a0 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -78,7 +78,43 @@
"perDay": "/日",
"leverageSuffix": "倍杠杆",
"never": "从未",
- "ago": "前"
+ "ago": "前",
+ "notConfigured": "未配置",
+ "readyToVerify": "等待验证",
+ "connectedReadOnly": "已连接 · 只读",
+ "connectionFailed": "连接失败",
+ "verifyConnection": "验证连接",
+ "retry": "重试",
+ "credentialSource": "凭证来源",
+ "sdk": "SDK",
+ "configDeclared": "配置声明",
+ "connectorStatusUnavailable": "状态不可用",
+ "connectedAccessUnknown": "已连接 · 访问权限未知",
+ "missingLongbridgeVariables": "缺少配置。请在 agent/.env 中配置以下变量并重新创建服务:",
+ "sdkConnectorProfile": "直连 SDK 连接器 · 只读档案",
+ "connectionDetails": "连接详情",
+ "environment": "环境",
+ "environmentIdentity": "声明环境",
+ "capabilities": "能力",
+ "capabilityAccount": "账户",
+ "capabilityPositions": "持仓",
+ "capabilityOpenOrders": "未结订单",
+ "capabilityQuotes": "行情",
+ "capabilityHistory": "历史数据",
+ "readOnly": "只读",
+ "accessUnknown": "访问权限未知",
+ "diagnostics": "诊断",
+ "lastChecked": "最后检查",
+ "errorCode": "错误代码",
+ "installed": "已安装",
+ "notInstalled": "未安装",
+ "connectorVerifyFailed": "连接验证失败。",
+ "diagnosticCredentialsPartial": "凭证不完整。请配置所有必需变量并重新创建服务。",
+ "diagnosticCredentialsConflict": "凭证来源冲突。请仅保留一套完整来源,然后重试。",
+ "diagnosticSdkMissing": "后端服务未安装 Longbridge SDK。",
+ "diagnosticAuthenticationFailed": "认证失败。请检查已配置的凭证。",
+ "diagnosticNetworkUnreachable": "无法连接 Longbridge 服务。请检查网络后重试。",
+ "diagnosticBrokerError": "券商拒绝了只读验证请求。请重试或检查后端日志。"
},
"reports": {
"badge": "报告",
@@ -662,6 +698,7 @@
},
"runnerStatus": {
"connectorRuntime": "连接器运行时",
+ "configuredProfiles": "已配置的连接器运行时配置",
"connected": "{{count}} 个已连接",
"noConnector": "无连接器已连接",
"running": "运行中",
diff --git a/frontend/src/lib/__tests__/api.test.ts b/frontend/src/lib/__tests__/api.test.ts
index 3ae729133..eb0211ca6 100644
--- a/frontend/src/lib/__tests__/api.test.ts
+++ b/frontend/src/lib/__tests__/api.test.ts
@@ -40,6 +40,32 @@ describe("api request helper", () => {
} satisfies Partial<ApiError>);
});
+ it("posts an authenticated connector verification request with an encoded profile id", async () => {
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn(() => "remote-test-key"),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ });
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ status: "ok", connection_state: "connected" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { api } = await loadApiModule();
+
+ await expect(api.verifyConnector("longbridge/live sdk")).resolves.toMatchObject({ status: "ok" });
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/live/connectors/longbridge%2Flive%20sdk/verify?force=true",
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.objectContaining({ Authorization: "Bearer remote-test-key" }),
+ }),
+ );
+ });
+
it("sends the stored API key when fetching a correlation matrix", async () => {
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => "remote-test-key"),
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 4f276db07..db84afff5 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -217,6 +217,10 @@ export const api = {
// Read the persistent runtime status across all authorized brokers (SPEC §7.5).
// Polled by the RunnerStatus panel; a plain authenticated GET, never a chat message.
getLiveStatus: (signal?: AbortSignal) => request<LiveStatus>("/live/status", { signal }),
+ verifyConnector: (profileId: string) =>
+ request<ConnectorVerifyResponse>(`/live/connectors/${encodeURIComponent(profileId)}/verify?force=true`, {
+ method: "POST",
+ }),
authorizeLive: (broker: string) =>
request<LiveAuthorizeResponse>("/live/authorize", {
method: "POST",
@@ -950,6 +954,36 @@ export interface LiveBrokerAuthStatus {
broker: string;
oauth_token_present: boolean;
is_live_broker: boolean;
+ /** Optional during rolling upgrades from OAuth-only runtime responses. */
+ profile_id?: string | null;
+ transport?: string | null;
+ connection_state?: string | null;
+ configured?: boolean | null;
+ credential_source?: string | null;
+ sdk_installed?: boolean | null;
+ last_checked_at?: string | null;
+ environment_identity?: string | null;
+ readonly?: boolean | null;
+ capabilities?: string[] | null;
+ error_code?: string | null;
+ error?: string | null;
+}
+
+export interface ConnectorVerifyResponse {
+ status?: string;
+ profile_id?: string | null;
+ transport?: string | null;
+ connection_state?: string | null;
+ configured?: boolean | null;
+ credential_source?: string | null;
+ sdk_installed?: boolean | null;
+ last_checked_at?: string | null;
+ environment_identity?: string | null;
+ readonly?: boolean | null;
+ capabilities?: string[] | null;
+ error_code?: string | null;
+ error?: string | null;
+ [key: string]: unknown;
}
/** One broker entry in the `GET /live/status` response. */
diff --git a/frontend/src/pages/Runtime.tsx b/frontend/src/pages/Runtime.tsx
index 7709a8750..b623b351e 100644
--- a/frontend/src/pages/Runtime.tsx
+++ b/frontend/src/pages/Runtime.tsx
@@ -162,7 +162,14 @@ export function Runtime() {
) : (
<section className="grid gap-4">
{status.brokers.map((broker) => (
- <BrokerRuntimeCard key={broker.auth.broker} broker={broker} globalHalted={status.global_halted} t={t} nowMs={nowMs} />
+ <BrokerRuntimeCard
+ key={broker.auth.profile_id || broker.auth.broker}
+ broker={broker}
+ globalHalted={status.global_halted}
+ t={t}
+ nowMs={nowMs}
+ onRefresh={() => loadStatus("refresh")}
+ />
))}
</section>
)}
@@ -220,11 +227,13 @@ function BrokerRuntimeCard({
globalHalted,
t,
nowMs,
+ onRefresh,
}: {
broker: LiveBrokerStatus;
globalHalted: boolean;
t: TFunction;
nowMs: number;
+ onRefresh: () => Promise<void>;
}) {
const brokerKey = broker.auth.broker;
const runnerAlive = broker.runner?.alive ?? false;
@@ -233,6 +242,10 @@ function BrokerRuntimeCard({
const risk = deriveRiskState(broker, globalHalted, t);
const mandateCountdown = formatCountdown(mandate?.expires_at, t, nowMs);
+ if (broker.auth.transport === "broker_sdk") {
+ return <SdkBrokerRuntimeCard broker={broker} t={t} onRefresh={onRefresh} />;
+ }
+
return (
<article className="rounded-md border p-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
@@ -283,6 +296,157 @@ function BrokerRuntimeCard({
);
}
+function SdkBrokerRuntimeCard({ broker, t, onRefresh }: { broker: LiveBrokerStatus; t: TFunction; onRefresh: () => Promise<void> }) {
+ const auth = broker.auth;
+ const [verifying, setVerifying] = useState(false);
+ const [verifyError, setVerifyError] = useState<string | null>(null);
+ const profileId = auth.profile_id || `${auth.broker}-live-sdk-readonly`;
+ const state = connectorState(auth, t);
+
+ const verify = useCallback(async () => {
+ if (verifying) return;
+ setVerifying(true);
+ setVerifyError(null);
+ try {
+ await api.verifyConnector(profileId);
+ await onRefresh();
+ } catch {
+ setVerifyError(t("runtime.connectorVerifyFailed"));
+ } finally {
+ setVerifying(false);
+ }
+ }, [onRefresh, profileId, t, verifying]);
+
+ return (
+ <article className="rounded-md border p-4">
+ <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
+ <div>
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="font-semibold capitalize">{auth.broker}</h2>
+ <StatusPill label={state.label} tone={state.tone} />
+ </div>
+ {isReadOnlyCompatible(auth) ? (
+ <p className="mt-2 text-sm text-muted-foreground">{t("runtime.sdkConnectorProfile")}</p>
+ ) : null}
+ </div>
+ {state.action ? (
+ <button
+ type="button"
+ onClick={verify}
+ disabled={verifying}
+ className="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium transition hover:bg-muted disabled:opacity-50"
+ >
+ {verifying ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
+ {t(state.action)}
+ </button>
+ ) : null}
+ </div>
+
+ {state.kind === "not_configured" ? (
+ <section className="mt-4 rounded-md border border-dashed p-3">
+ <p className="text-sm text-muted-foreground">{t("runtime.missingLongbridgeVariables")}</p>
+ <ul className="mt-2 grid gap-1 font-mono text-sm">
+ <li>LONGBRIDGE_APP_KEY</li>
+ <li>LONGBRIDGE_APP_SECRET</li>
+ <li>LONGBRIDGE_ACCESS_TOKEN</li>
+ </ul>
+ </section>
+ ) : (
+ <div className="mt-4 grid gap-3 md:grid-cols-3">
+ <RuntimePanel title={t("runtime.connectionDetails")} icon={state.kind === "connected" ? Wifi : WifiOff}>
+ <KeyValue label={t("runtime.credentialSource")} value={auth.credential_source || t("runtime.unknown")} />
+ <KeyValue label={t("runtime.sdk")} value={formatSdkState(auth.sdk_installed, t)} />
+ </RuntimePanel>
+ <RuntimePanel title={t("runtime.environment")} icon={ShieldCheck}>
+ <KeyValue label={t("runtime.environmentIdentity")} value={formatEnvironmentIdentity(auth.environment_identity, t)} />
+ <KeyValue label={t("runtime.capabilities")} value={formatCapabilities(auth, t)} />
+ </RuntimePanel>
+ <RuntimePanel title={t("runtime.diagnostics")} icon={state.kind === "error" ? AlertTriangle : CheckCircle2}>
+ <KeyValue label={t("runtime.lastChecked")} value={auth.last_checked_at || t("runtime.never")} />
+ {auth.error_code ? <KeyValue label={t("runtime.errorCode")} value={auth.error_code} /> : null}
+ {state.kind === "error" ? <p className="text-sm text-muted-foreground">{connectorDiagnostic(auth.error_code, t)}</p> : null}
+ </RuntimePanel>
+ </div>
+ )}
+ {verifyError ? <p role="alert" className="mt-3 text-sm text-danger">{verifyError}</p> : null}
+ </article>
+ );
+}
+
+function connectorState(auth: LiveBrokerStatus["auth"], t: TFunction): {
+ kind: "not_configured" | "ready" | "connected" | "error" | "unknown";
+ label: string;
+ tone: "success" | "danger" | "warning" | "neutral";
+ action?: "runtime.verifyConnection" | "runtime.retry";
+} {
+ if (auth.connection_state === "connected") {
+ if (isReadOnlyCompatible(auth)) {
+ return { kind: "connected", label: t("runtime.connectedReadOnly"), tone: "success" };
+ }
+ return { kind: "connected", label: t("runtime.connectedAccessUnknown"), tone: "neutral" };
+ }
+ if (auth.connection_state === "not_configured" || auth.configured === false) {
+ return { kind: "not_configured", label: t("runtime.notConfigured"), tone: "neutral" };
+ }
+ if (auth.connection_state === "error") {
+ return { kind: "error", label: t("runtime.connectionFailed"), tone: "danger", action: "runtime.retry" };
+ }
+ if (auth.connection_state === "ready") {
+ return { kind: "ready", label: t("runtime.readyToVerify"), tone: "warning", action: "runtime.verifyConnection" };
+ }
+ return { kind: "unknown", label: t("runtime.connectorStatusUnavailable"), tone: "neutral" };
+}
+
+function connectorDiagnostic(errorCode: string | null | undefined, t: TFunction): string {
+ switch (errorCode) {
+ case "credentials_partial": return t("runtime.diagnosticCredentialsPartial");
+ case "credentials_conflict": return t("runtime.diagnosticCredentialsConflict");
+ case "sdk_missing": return t("runtime.diagnosticSdkMissing");
+ case "authentication_failed": return t("runtime.diagnosticAuthenticationFailed");
+ case "network_unreachable": return t("runtime.diagnosticNetworkUnreachable");
+ default: return t("runtime.diagnosticBrokerError");
+ }
+}
+
+function formatSdkState(installed: boolean | null | undefined, t: TFunction): string {
+ if (installed === true) return t("runtime.installed");
+ if (installed === false) return t("runtime.notInstalled");
+ return t("runtime.unknown");
+}
+
+function formatEnvironmentIdentity(identity: string | null | undefined, t: TFunction): string {
+ if (identity === "config_declared" || identity === "config-declared") return t("runtime.configDeclared");
+ return identity || t("runtime.unknown");
+}
+
+function isReadCapability(capability: string): boolean {
+ return capability.endsWith(".read");
+}
+
+function isReadOnlyCompatible(auth: LiveBrokerStatus["auth"]): boolean {
+ if (auth.connection_state !== "connected") return false;
+ if (auth.readonly !== true) return false;
+ if (!auth.profile_id?.endsWith("-readonly")) return false;
+ if (!auth.capabilities?.length) return false;
+ return auth.capabilities.every(isReadCapability);
+}
+
+function formatCapabilities(auth: LiveBrokerStatus["auth"], t: TFunction): string {
+ const labels: Record<string, string> = {
+ "account.read": t("runtime.capabilityAccount"),
+ "positions.read": t("runtime.capabilityPositions"),
+ "orders.read": t("runtime.capabilityOpenOrders"),
+ "quotes.read": t("runtime.capabilityQuotes"),
+ "history.read": t("runtime.capabilityHistory"),
+ };
+ const readCapabilities = auth.capabilities?.filter(isReadCapability) ?? [];
+ const rendered = readCapabilities.map((capability) => labels[capability] || capability).join(", ");
+ if (!isReadOnlyCompatible(auth)) {
+ return rendered ? `${rendered} · ${t("runtime.accessUnknown")}` : t("runtime.accessUnknown");
+ }
+ return `${rendered} · ${t("runtime.readOnly")}`;
+}
+
function RuntimePanel({ title, icon: Icon, children }: { title: string; icon: typeof Activity; children: ReactNode }) {
return (
<section className="rounded-md border bg-muted/20 p-3">
@@ -324,7 +488,9 @@ function summarizeRuntime(status: LiveStatus | null) {
const brokers = status?.brokers || [];
return {
brokerCount: brokers.length,
- authorizedCount: brokers.filter((broker) => broker.auth.oauth_token_present).length,
+ authorizedCount: brokers.filter(
+ (broker) => broker.auth.oauth_token_present || broker.auth.connection_state === "connected",
+ ).length,
runningCount: brokers.filter((broker) => broker.runner?.alive).length,
};
}
diff --git a/frontend/src/pages/__tests__/Runtime.test.tsx b/frontend/src/pages/__tests__/Runtime.test.tsx
index 946c8d1fe..790b03bd2 100644
--- a/frontend/src/pages/__tests__/Runtime.test.tsx
+++ b/frontend/src/pages/__tests__/Runtime.test.tsx
@@ -1,9 +1,10 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { Runtime } from "../Runtime";
-import type { LiveStatus } from "@/lib/api";
+import type { LiveBrokerStatus, LiveStatus } from "@/lib/api";
const apiMock = vi.hoisted(() => ({
getLiveStatus: vi.fn(),
+ verifyConnector: vi.fn(),
}));
vi.mock("@/lib/api", () => ({
@@ -64,6 +65,37 @@ function makeStatus(overrides: Partial<LiveStatus> = {}): LiveStatus {
};
}
+function makeLongbridgeStatus(
+ authOverrides: Partial<LiveBrokerStatus["auth"]> = {},
+): LiveStatus {
+ return makeStatus({
+ brokers: [
+ {
+ auth: {
+ broker: "longbridge",
+ oauth_token_present: false,
+ is_live_broker: false,
+ profile_id: "longbridge-live-sdk-readonly",
+ transport: "broker_sdk",
+ configured: true,
+ sdk_installed: true,
+ readonly: true,
+ capabilities: ["account.read", "positions.read", "orders.read", "quotes.read", "history.read"],
+ ...authOverrides,
+ },
+ runner: {
+ broker: "longbridge",
+ alive: false,
+ last_tick: null,
+ last_tick_age_seconds: null,
+ },
+ mandate: null,
+ halted: false,
+ },
+ ],
+ });
+}
+
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
@@ -77,6 +109,7 @@ function deferred<T>() {
describe("Runtime page", () => {
beforeEach(() => {
apiMock.getLiveStatus.mockReset();
+ apiMock.verifyConnector.mockReset();
});
it("renders broker auth, runner, mandate, and risk state from live status", async () => {
@@ -177,4 +210,280 @@ describe("Runtime page", () => {
expect(await screen.findByText("45s")).toBeInTheDocument();
});
+
+ it("shows exact missing Longbridge variable names without rendering secret inputs", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ configured: false,
+ connection_state: "not_configured",
+ error_code: "credentials_missing",
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Not configured")).toBeInTheDocument();
+ expect(screen.getByText("LONGBRIDGE_APP_KEY")).toBeInTheDocument();
+ expect(screen.getByText("LONGBRIDGE_APP_SECRET")).toBeInTheDocument();
+ expect(screen.getByText("LONGBRIDGE_ACCESS_TOKEN")).toBeInTheDocument();
+ expect(document.querySelector('input[type="password"]')).not.toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ it("renders a verify action when Longbridge is ready", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "ready",
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Ready to verify")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Verify connection" })).toBeEnabled();
+ });
+
+ it.each([
+ {
+ name: "ready",
+ auth: { connection_state: "ready" },
+ stateLabel: "Ready to verify",
+ },
+ {
+ name: "error",
+ auth: { connection_state: "error", error_code: "authentication_failed" },
+ stateLabel: "Connection failed",
+ },
+ {
+ name: "missing connection state",
+ auth: { connection_state: undefined, configured: true },
+ stateLabel: "Status unavailable",
+ },
+ ])("does not advertise read-only access when the SDK state is $name", async ({ auth, stateLabel }) => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus(auth));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText(stateLabel)).toBeInTheDocument();
+ expect(screen.queryByText("Connected · Read-only")).not.toBeInTheDocument();
+ expect(screen.queryByText(/read-only profile/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/· read-only$/)).not.toBeInTheDocument();
+ expect(screen.getByText("Account, positions, open orders, quotes, history · access unknown")).toBeInTheDocument();
+ });
+
+ it.each([undefined, true])(
+ "keeps an SDK response without connection state neutral when configured is %s",
+ async (configured) => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: undefined,
+ configured,
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Status unavailable")).toBeInTheDocument();
+ expect(screen.queryByText("Ready to verify")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Verify connection" })).not.toBeInTheDocument();
+ },
+ );
+
+ it.each([true, false, null])(
+ "renders connected Longbridge as read-only when configured is %s",
+ async (configured) => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "connected",
+ configured,
+ credential_source: "runtime_file",
+ environment_identity: "config_declared",
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connected · Read-only")).toBeInTheDocument();
+ expect(screen.getByText("Authorized").parentElement?.parentElement).toHaveTextContent("1");
+ expect(screen.getByText("Credential source")).toBeInTheDocument();
+ expect(screen.getByText("runtime_file")).toBeInTheDocument();
+ expect(screen.getByText("Config-declared")).toBeInTheDocument();
+ expect(screen.getByText("SDK")).toBeInTheDocument();
+ expect(screen.getByText("Account, positions, open orders, quotes, history · read-only")).toBeInTheDocument();
+ },
+ );
+
+ it("keeps connected access neutral when read-only metadata is absent", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "connected",
+ environment_identity: undefined,
+ readonly: undefined,
+ capabilities: undefined,
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connected · Access unknown")).toBeInTheDocument();
+ expect(screen.getAllByText("unknown").length).toBeGreaterThan(0);
+ expect(screen.queryByText("Connected · Read-only")).not.toBeInTheDocument();
+ expect(screen.queryByText("Config-declared")).not.toBeInTheDocument();
+ expect(screen.queryByText("Account, positions, open orders, quotes, history · read-only")).not.toBeInTheDocument();
+ });
+
+ it.each([
+ {
+ name: "readonly metadata is missing",
+ auth: { readonly: undefined },
+ },
+ {
+ name: "the profile ID is missing",
+ auth: { profile_id: undefined },
+ },
+ {
+ name: "capability metadata is missing",
+ auth: { capabilities: undefined },
+ },
+ {
+ name: "the capability list is empty",
+ auth: { capabilities: [] },
+ },
+ {
+ name: "a write capability is present despite a readonly profile",
+ auth: { readonly: true, capabilities: ["account.read", "orders.place"] },
+ },
+ {
+ name: "a capability merely contains a read segment",
+ auth: { readonly: true, capabilities: ["account.read", "orders.read.place"] },
+ },
+ {
+ name: "the profile is not declared readonly",
+ auth: { profile_id: "longbridge-live-trade", readonly: true },
+ },
+ ])("fails closed when $name", async ({ auth }) => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "connected",
+ ...auth,
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connected · Access unknown")).toBeInTheDocument();
+ expect(screen.queryByText("Connected · Read-only")).not.toBeInTheDocument();
+ expect(screen.queryByText(/read-only profile/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/· read-only$/)).not.toBeInTheDocument();
+ });
+
+ it("shows access unknown in the capability summary when capabilities are missing", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "connected",
+ readonly: true,
+ capabilities: undefined,
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connected · Access unknown")).toBeInTheDocument();
+ expect(screen.getByText("access unknown")).toBeInTheDocument();
+ });
+
+ it("shows access unknown without write names when all capabilities are write capabilities", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "connected",
+ readonly: true,
+ capabilities: ["orders.place"],
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connected · Access unknown")).toBeInTheDocument();
+ expect(screen.getByText("access unknown")).toBeInTheDocument();
+ expect(screen.queryByText(/orders\.place/)).not.toBeInTheDocument();
+ });
+
+ it("does not advertise write capabilities in the capability summary", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "connected",
+ readonly: true,
+ capabilities: ["account.read", "orders.place"],
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connected · Access unknown")).toBeInTheDocument();
+ expect(screen.getByText("Account · access unknown")).toBeInTheDocument();
+ expect(screen.queryByText(/orders\.place/)).not.toBeInTheDocument();
+ });
+
+ it("renders failed Longbridge diagnostics without displaying backend detail", async () => {
+ apiMock.getLiveStatus.mockResolvedValue(makeLongbridgeStatus({
+ connection_state: "error",
+ error_code: "authentication_failed",
+ error: "raw diagnostic must stay hidden",
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("Connection failed")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();
+ expect(screen.getByText("authentication_failed")).toBeInTheDocument();
+ expect(screen.getByText("Authentication failed. Check the configured credentials.")).toBeInTheDocument();
+ expect(screen.queryByText("raw diagnostic must stay hidden")).not.toBeInTheDocument();
+ });
+
+ it("verifies once, disables the action while pending, then refreshes status", async () => {
+ const verification = deferred<Record<string, unknown>>();
+ apiMock.getLiveStatus
+ .mockResolvedValueOnce(makeLongbridgeStatus({ connection_state: "ready" }))
+ .mockResolvedValueOnce(makeLongbridgeStatus({ connection_state: "connected" }));
+ apiMock.verifyConnector.mockReturnValueOnce(verification.promise);
+
+ render(<Runtime />);
+
+ const verifyButton = await screen.findByRole("button", { name: "Verify connection" });
+ fireEvent.click(verifyButton);
+
+ expect(apiMock.verifyConnector).toHaveBeenCalledTimes(1);
+ expect(apiMock.verifyConnector).toHaveBeenCalledWith("longbridge-live-sdk-readonly");
+ expect(verifyButton).toBeDisabled();
+ fireEvent.click(verifyButton);
+ expect(apiMock.verifyConnector).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ verification.resolve({ connection_state: "connected" });
+ await verification.promise;
+ });
+
+ expect(apiMock.getLiveStatus).toHaveBeenCalledTimes(2);
+ expect(await screen.findByText("Connected · Read-only")).toBeInTheDocument();
+ });
+
+ it("retains IBKR and Robinhood OAuth status cards without SDK verify actions", async () => {
+ const baseStatus = makeStatus();
+ apiMock.getLiveStatus.mockResolvedValue(makeStatus({
+ brokers: [
+ {
+ ...baseStatus.brokers[0],
+ auth: {
+ broker: "ibkr",
+ oauth_token_present: true,
+ is_live_broker: true,
+ transport: "remote_mcp",
+ },
+ },
+ {
+ ...baseStatus.brokers[1],
+ auth: {
+ broker: "robinhood",
+ oauth_token_present: false,
+ is_live_broker: true,
+ transport: "remote_mcp",
+ },
+ },
+ ],
+ }));
+
+ render(<Runtime />);
+
+ expect(await screen.findByText("ibkr")).toBeInTheDocument();
+ expect(screen.getByText("robinhood")).toBeInTheDocument();
+ expect(screen.getAllByText("Authorization")).toHaveLength(2);
+ expect(screen.getAllByText("OAuth token")).toHaveLength(2);
+ expect(screen.getByText("auth present")).toBeInTheDocument();
+ expect(screen.getByText("auth missing")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Verify connection" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();
+ expect(apiMock.verifyConnector).not.toHaveBeenCalled();
+ });
});