Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(portfolio): configure IBKR and Futu gateway endpoints

Terry Feng3fc3b393bc37
diff --git a/agent/src/api/connection_routes.py b/agent/src/api/connection_routes.py
index 866be20af..6311225c4 100644
--- a/agent/src/api/connection_routes.py
+++ b/agent/src/api/connection_routes.py
@@ -18,7 +18,7 @@ from src.trading.connections import (
)
from src.trading.local_plugins import plugin_root
from src.trading.profiles import profile_by_id
-from src.trading.service import check_connection
+from src.trading.service import _ibkr_config, _sdk_config, _sdk_module, check_connection
class ConnectionRequest(BaseModel):
@@ -41,6 +41,14 @@ class CredentialRequest(BaseModel):
values: dict[str, str] = Field(default_factory=dict)
+class SocketEndpointRequest(BaseModel):
+ """Host and socket port for a broker gateway; never broker credentials."""
+
+ model_config = {"extra": "forbid"}
+ host: str = Field(min_length=1, max_length=253)
+ port: int = Field(strict=True, ge=1, le=65535)
+
+
def register_connection_routes(app: FastAPI) -> None:
"""Register the auth-gated read-only connection endpoints.
@@ -65,6 +73,18 @@ def register_connection_routes(app: FastAPI) -> None:
}
for row in store().public_list()
]
+ for row in connections:
+ try:
+ if row["connector"] == "ibkr" and row["transport"] == "local_tws":
+ config = _ibkr_config(profile_by_id(row["profile_id"]), {"connection_id": row["id"]})
+ elif row["connector"] == "futu" and row["transport"] == "broker_sdk":
+ config = _sdk_config(profile_by_id(row["profile_id"]), _sdk_module("futu"), {"connection_id": row["id"]})
+ else:
+ continue
+ except (ValueError, TypeError, RuntimeError) as exc:
+ row["endpoint_error"] = str(exc)
+ continue
+ row["effective_endpoint"] = {"host": config.host, "port": config.port}
profiles = []
for row in readonly_profile_catalog():
if row.get("invalid_plugin"):
@@ -115,6 +135,20 @@ def register_connection_routes(app: FastAPI) -> None:
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ @app.put(
+ "/api/connections/{connection_id}/endpoint",
+ dependencies=[Depends(require_settings_write_auth)],
+ )
+ def save_connection_endpoint(connection_id: str, payload: SocketEndpointRequest):
+ """Save a connection's socket address without contacting the broker."""
+ try:
+ instance = store()
+ current = instance.get(connection_id)
+ updated = instance.save(replace(current, endpoint=payload.model_dump()))
+ return {"status": "ok", "connection": updated.to_dict()}
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
@app.get(
"/api/connections/{connection_id}/accounts",
dependencies=[Depends(require_auth)],
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index 8911c64f0..9f0fe4508 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -1002,7 +1002,7 @@ class PortfolioService:
f"Select a {broker} account for this connection before refreshing"
)
read_options["account"] = connection.account_ref
- elif profile.transport in {"broker_sdk", "local_plugin"} and (
+ elif profile.transport in {"broker_sdk", "local_plugin", "local_tws"} and (
profile.transport == "local_plugin" or self._use_connection_scoped_reads
):
read_options["connection_id"] = connection.id
@@ -1083,7 +1083,7 @@ class PortfolioService:
**(
{"connection_id": connection.id}
if profile.transport == "local_plugin"
- or (profile.transport == "broker_sdk" and self._use_connection_scoped_quotes)
+ or (profile.transport in {"broker_sdk", "local_tws"} and self._use_connection_scoped_quotes)
else {}
),
)
diff --git a/agent/src/trading/connections.py b/agent/src/trading/connections.py
index 43b8d73be..7c87206e6 100644
--- a/agent/src/trading/connections.py
+++ b/agent/src/trading/connections.py
@@ -6,6 +6,7 @@ import json
import os
import re
import tempfile
+from ipaddress import ip_address
from dataclasses import asdict, dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
@@ -137,8 +138,9 @@ class TradingConnection:
credential_ref: str
created_at: str
account_ref: str = ""
+ endpoint: dict[str, Any] | None = None
- def to_dict(self) -> dict[str, str]:
+ def to_dict(self) -> dict[str, Any]:
"""Return the connection as a JSON-serializable mapping.
Returns:
@@ -387,6 +389,32 @@ class ConnectionStore:
account_ref = validate_account_ref(raw.get("account_ref"))
if account_ref and not requires_account_selection(profile):
raise ValueError(f"connection profile does not take an account: {profile.id}")
+ endpoint = raw.get("endpoint")
+ if endpoint is not None:
+ if (profile.connector, profile.transport) not in {("ibkr", "local_tws"), ("futu", "broker_sdk")}:
+ raise ValueError("socket endpoint settings are only available for local IBKR and Futu connections")
+ if not isinstance(endpoint, dict) or set(endpoint) != {"host", "port"}:
+ raise ValueError("endpoint must contain host and port only")
+ host, port = endpoint["host"], endpoint["port"]
+ if (
+ not isinstance(host, str)
+ or not host.strip()
+ or len(host.strip()) > 253
+ or any(character.isspace() or ord(character) < 32 or character in "/\\@?#" for character in host.strip())
+ ):
+ raise ValueError("host must be a hostname or IP address without a scheme or path")
+ host = host.strip()
+ try:
+ ip_address(host)
+ except ValueError:
+ if not all(
+ re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label)
+ for label in host.removesuffix(".").split(".")
+ ):
+ raise ValueError("host must be a hostname or IP address without a scheme or path")
+ if type(port) is not int or not 1 <= port <= 65535:
+ raise ValueError("port must be an integer from 1 to 65535")
+ endpoint = {"host": host, "port": port}
return TradingConnection(
id=connection_id,
profile_id=profile.id,
@@ -394,6 +422,7 @@ class ConnectionStore:
credential_ref=credential_ref,
created_at=str(raw.get("created_at") or _now()),
account_ref=account_ref,
+ endpoint=endpoint,
)
def _write(self, connections: list[TradingConnection]) -> None:
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index a4216bd8b..6795ec484 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -107,6 +107,9 @@ def _sdk_config(
if connection.profile_id != profile.id:
raise ValueError("local connection profile does not match the requested SDK profile")
+ if profile.connector == "futu" and connection.endpoint is not None:
+ options = {**connection.endpoint, **{key: value for key, value in options.items() if value not in (None, "")}}
+
fields = credential_fields(profile.id)
direct_secret_fields = set(fields).intersection(options)
if direct_secret_fields:
@@ -1441,6 +1444,15 @@ def _ibkr_config(profile: TradingProfile, overrides: dict[str, Any]):
cfg = base
else:
cfg = default_cfg
+ connection_id = _clean(overrides.get("connection_id"))
+ if connection_id is not None:
+ from src.trading.connections import ConnectionStore
+
+ connection = ConnectionStore().get(connection_id)
+ if connection.profile_id != profile.id:
+ raise ValueError("local connection profile does not match the requested IBKR profile")
+ if connection.endpoint is not None:
+ cfg = cfg.with_overrides(**connection.endpoint)
return cfg.with_overrides(
host=_clean(overrides.get("host")),
port=_int_or_none(overrides.get("port")),
diff --git a/agent/tests/test_connection_routes.py b/agent/tests/test_connection_routes.py
index ad2e3250f..1c72c56c5 100644
--- a/agent/tests/test_connection_routes.py
+++ b/agent/tests/test_connection_routes.py
@@ -1,7 +1,10 @@
from __future__ import annotations
+import json
+
from fastapi import FastAPI
from fastapi.testclient import TestClient
+import pytest
from src.api import connection_routes
from src.trading.connections import ConnectionStore
@@ -93,3 +96,196 @@ def test_connection_routes_reject_credentials_not_declared_by_profile(tmp_path,
json={"values": {"withdrawal_token": "must-not-be-accepted"}},
)
assert response.status_code == 400
+
+
+def ibkr_endpoint_client(tmp_path, monkeypatch):
+ from src.trading import connections
+ from src.trading.connectors.ibkr import local
+ from src.trading.connectors.futu import sdk as futu
+
+ store = ConnectionStore(tmp_path / "connections.json", credential_store=CredentialStore(_MemoryCredentials()))
+ store.create("ibkr-paper", "ibkr-paper-local", "Paper")
+ store.create("ibkr-live", "ibkr-live-local-readonly", "Live")
+ store.create("ibkr-mcp", "ibkr-live-official-mcp-readonly", "Remote")
+ store.create("futu-paper", "futu-paper-sdk", "Futu Paper")
+ store.create("futu-live", "futu-live-sdk-readonly", "Futu Live")
+ monkeypatch.setattr(connection_routes, "ConnectionStore", lambda: store)
+ monkeypatch.setattr(connections, "ConnectionStore", lambda: store)
+ monkeypatch.setattr(local, "config_path", lambda: tmp_path / "ibkr-local.json")
+ monkeypatch.setattr(futu, "config_path", lambda: tmp_path / "futu.json")
+ monkeypatch.setattr(futu, "tcp_port_open", lambda *a, **k: pytest.fail("unexpected Futu access"))
+ # Any accidental socket access is a test failure, including saving/listing.
+ monkeypatch.setattr(local, "tcp_port_open", lambda *a, **k: pytest.fail("unexpected broker access"))
+ app = FastAPI()
+ connection_routes.register_connection_routes(app)
+ return TestClient(app), store
+
+
+def test_ibkr_endpoint_persists_per_connection_and_is_used_for_reads(ibkr_endpoint_client):
+ from src.trading.service import _ibkr_config
+ from src.trading.profiles import profile_by_id
+
+ client, store = ibkr_endpoint_client
+ defaults = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ assert defaults["ibkr-paper"]["effective_endpoint"] == {"host": "127.0.0.1", "port": 7497}
+ assert defaults["ibkr-live"]["effective_endpoint"] == {"host": "127.0.0.1", "port": 7496}
+ response = client.put("/api/connections/ibkr-paper/endpoint", json={"host": " host.docker.internal ", "port": 4002})
+ assert response.status_code == 200
+ # Re-read the persisted file; the other connection stays on its defaults.
+ assert store.get("ibkr-paper").endpoint == {"host": "host.docker.internal", "port": 4002}
+ listed = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ assert listed["ibkr-paper"]["effective_endpoint"] == {"host": "host.docker.internal", "port": 4002}
+ assert listed["ibkr-live"]["effective_endpoint"] == {"host": "127.0.0.1", "port": 7496}
+ assert "effective_endpoint" not in listed["ibkr-mcp"]
+ cfg = _ibkr_config(profile_by_id("ibkr-paper-local"), {"connection_id": "ibkr-paper"})
+ assert (cfg.host, cfg.port, cfg.profile, cfg.readonly) == ("host.docker.internal", 4002, "paper", True)
+ override = _ibkr_config(profile_by_id("ibkr-paper-local"), {"connection_id": "ibkr-paper", "port": 7497})
+ assert override.port == 7497
+ # Existing callers without a connection id keep the original defaults.
+ assert _ibkr_config(profile_by_id("ibkr-paper-local"), {}).port == 7497
+
+
[email protected]("host", ["", " ", "https://localhost", "localhost:4002", "host/path", "host name", "user@host", "a" * 254])
+def test_ibkr_endpoint_rejects_invalid_host(ibkr_endpoint_client, host):
+ client, store = ibkr_endpoint_client
+ response = client.put("/api/connections/ibkr-paper/endpoint", json={"host": host, "port": 4002})
+ assert response.status_code in {400, 422}
+ assert store.get("ibkr-paper").endpoint is None
+
+
[email protected]("port", [0, 65536, 1.5, True, "4002", None])
+def test_ibkr_endpoint_rejects_invalid_port(ibkr_endpoint_client, port):
+ client, store = ibkr_endpoint_client
+ assert client.put("/api/connections/ibkr-paper/endpoint", json={"host": "localhost", "port": port}).status_code == 422
+ assert store.get("ibkr-paper").endpoint is None
+
+
[email protected]("host,port", [("::1", 1), ("192.168.1.10", 65535), ("gateway.local", 4002)])
+def test_ibkr_endpoint_accepts_hosts_and_port_boundaries(ibkr_endpoint_client, host, port):
+ client, store = ibkr_endpoint_client
+ assert client.put("/api/connections/ibkr-paper/endpoint", json={"host": host, "port": port}).status_code == 200
+ assert store.get("ibkr-paper").endpoint == {"host": host, "port": port}
+
+
+def test_ibkr_endpoint_rejects_remote_profiles_and_extra_settings(ibkr_endpoint_client):
+ client, _ = ibkr_endpoint_client
+ assert client.put("/api/connections/ibkr-mcp/endpoint", json={"host": "localhost", "port": 4002}).status_code == 400
+ assert client.put("/api/connections/missing/endpoint", json={"host": "localhost", "port": 4002}).status_code == 400
+ assert client.put("/api/connections/ibkr-paper/endpoint", json={"host": "localhost", "port": 4002, "readonly": False}).status_code == 422
+
+
+def test_ibkr_endpoint_requires_settings_write_auth(ibkr_endpoint_client, monkeypatch):
+ from src.api import security
+
+ client, store = ibkr_endpoint_client
+ monkeypatch.setattr(security, "_configured_api_key", lambda: "test-settings-key")
+ assert client.put("/api/connections/ibkr-paper/endpoint", json={"host": "localhost", "port": 4002}).status_code == 401
+ assert store.get("ibkr-paper").endpoint is None
+
+
+def test_ibkr_endpoint_preserves_legacy_configuration_until_overridden(ibkr_endpoint_client, tmp_path):
+ from src.trading.connectors.ibkr import local
+ from src.trading.profiles import profile_by_id
+ from src.trading.service import _ibkr_config
+
+ client, _ = ibkr_endpoint_client
+ local.config_path().write_text('{"host":"legacy.local","port":4002,"profile":"paper","client_id":123}')
+ listed = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ assert listed["ibkr-paper"]["effective_endpoint"] == {"host": "legacy.local", "port": 4002}
+ assert listed["ibkr-live"]["effective_endpoint"]["port"] == 7496
+ assert client.put("/api/connections/ibkr-paper/endpoint", json={"host": "custom.local", "port": 7497}).status_code == 200
+ config = _ibkr_config(profile_by_id("ibkr-paper-local"), {"connection_id": "ibkr-paper"})
+ assert (config.host, config.port, config.client_id, config.readonly) == ("custom.local", 7497, 123, True)
+ with pytest.raises(ValueError, match="profile does not match"):
+ _ibkr_config(profile_by_id("ibkr-live-local-readonly"), {"connection_id": "ibkr-paper"})
+
+
+def test_futu_endpoint_defaults_persistence_and_native_read_dispatch(ibkr_endpoint_client, monkeypatch):
+ from src.trading import service
+ from src.trading.connectors.futu import sdk as futu
+ from src.trading.profiles import profile_by_id
+
+ client, store = ibkr_endpoint_client
+ listed = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ for name in ("futu-paper", "futu-live"):
+ assert listed[name]["effective_endpoint"] == {"host": "127.0.0.1", "port": 11111}
+ assert client.put("/api/connections/futu-paper/endpoint", json={"host": "opend.local", "port": 11112}).status_code == 200
+ assert store.get("futu-paper").endpoint == {"host": "opend.local", "port": 11112}
+ listed = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ assert listed["futu-paper"]["effective_endpoint"] == {"host": "opend.local", "port": 11112}
+ assert listed["futu-live"]["effective_endpoint"] == {"host": "127.0.0.1", "port": 11111}
+ assert listed["ibkr-paper"]["effective_endpoint"] == {"host": "127.0.0.1", "port": 7497}
+ calls = []
+
+ def read(config):
+ calls.append((config.host, config.port, config.profile))
+ return {"status": "ok"}
+
+ monkeypatch.setattr(futu, "check_status", read)
+ monkeypatch.setattr(futu, "get_account_snapshot", read)
+ monkeypatch.setattr(futu, "get_positions", read)
+ monkeypatch.setattr(futu, "get_quote", lambda symbol, *, config, **kwargs: read(config))
+ assert client.post("/api/connections/futu-paper/check").status_code == 200
+ service.get_account("futu-paper-sdk", connection_id="futu-paper")
+ service.get_positions("futu-paper-sdk", connection_id="futu-paper")
+ service.get_quote("AAPL", "futu-paper-sdk", connection_id="futu-paper")
+ assert calls == [("opend.local", 11112, "paper")] * 4
+ override = service._sdk_config(profile_by_id("futu-paper-sdk"), futu, {"connection_id": "futu-paper", "port": 11113})
+ assert override.port == 11113
+
+
+def test_futu_endpoint_keeps_legacy_gateway_settings_and_live_profile(ibkr_endpoint_client):
+ from src.trading import service
+ from src.trading.connectors.futu import sdk as futu
+ from src.trading.profiles import profile_by_id
+
+ client, _ = ibkr_endpoint_client
+ futu.config_path().write_text('{"host":"legacy.local","port":11114,"filter_trdmarket":"US","acc_id":123}')
+ listed = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ assert listed["futu-live"]["effective_endpoint"] == {"host": "legacy.local", "port": 11114}
+ assert client.put("/api/connections/futu-live/endpoint", json={"host": "opend.local", "port": 11115}).status_code == 200
+ config = service._sdk_config(profile_by_id("futu-live-sdk-readonly"), futu, {"connection_id": "futu-live"})
+ assert (config.host, config.port, config.profile, config.filter_trdmarket, config.acc_id) == ("opend.local", 11115, "live-readonly", "US", 123)
+ assert service._sdk_config(profile_by_id("futu-live-sdk-readonly"), futu, {}).host == "legacy.local"
+
+
[email protected]("connector,filename", [("ibkr", "ibkr-local.json"), ("futu", "futu.json")])
+def test_connection_list_isolates_invalid_gateway_config(ibkr_endpoint_client, tmp_path, connector, filename):
+ client, _ = ibkr_endpoint_client
+ before = {row["id"]: row for row in client.get("/api/connections").json()["connections"]}
+ (tmp_path / filename).write_text("{invalid json", encoding="utf-8")
+
+ response = client.get("/api/connections")
+
+ assert response.status_code == 200
+ after = {row["id"]: row for row in response.json()["connections"]}
+ assert after.keys() == before.keys()
+ for connection_id, row in after.items():
+ if row["connector"] == connector and row["transport"] != "remote_mcp":
+ assert filename in row["endpoint_error"]
+ assert "effective_endpoint" not in row
+ else:
+ assert row == before[connection_id]
+
+
[email protected]("overrides,expected_port", [({}, 11112), ({"port": 11113}, 11113)])
+def test_futu_tool_preserves_saved_endpoint_for_unsupplied_fields(ibkr_endpoint_client, monkeypatch, overrides, expected_port):
+ from src.tools.trading_connector_tool import TradingCheckTool
+ from src.trading.connectors.futu import sdk as futu
+
+ client, _ = ibkr_endpoint_client
+ assert client.put("/api/connections/futu-paper/endpoint", json={"host": "opend.local", "port": 11112}).status_code == 200
+ calls = []
+
+ def check(config):
+ calls.append((config.host, config.port, config.profile))
+ return {"status": "ok"}
+
+ monkeypatch.setattr(futu, "check_status", check)
+ result = json.loads(TradingCheckTool().execute(
+ connection="futu-paper-sdk", connection_id="futu-paper", **overrides,
+ ))
+
+ assert result["status"] == "ok"
+ assert calls == [("opend.local", expected_port, "paper")]
diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.py
index 8cb91db36..928e237dc 100644
--- a/agent/tests/test_portfolio_service.py
+++ b/agent/tests/test_portfolio_service.py
@@ -32,6 +32,50 @@ def _settings_store(tmp_path):
return store
+def test_refresh_uses_each_ibkr_connections_endpoint_for_account_positions_and_quotes(tmp_path, monkeypatch):
+ from dataclasses import replace
+ from src.trading import connections
+ from src.trading.connectors.ibkr import local
+
+ registry = connections.ConnectionStore(tmp_path / "connections.json")
+ for name, port in (("first", 4002), ("second", 7497)):
+ connection = registry.create(name, "ibkr-paper-local", name)
+ registry.save(replace(connection, endpoint={"host": f"{name}.local", "port": port}))
+ monkeypatch.setattr(connections, "ConnectionStore", lambda: registry)
+ monkeypatch.setattr(local, "config_path", lambda: tmp_path / "ibkr-local.json")
+ calls = []
+
+ def account(cfg):
+ calls.append(("account", cfg.host, cfg.port))
+ return {"summary": [{"tag": "NetLiquidation", "value": "1000", "currency": "USD"}]}
+
+ def positions(cfg):
+ calls.append(("positions", cfg.host, cfg.port))
+ return {"positions": [{"symbol": "AAPL", "sec_type": "STK", "exchange": "SMART", "currency": "USD", "position": 1, "avg_cost": 100}]}
+
+ def quote(symbol, *, config, **kwargs):
+ calls.append(("quote", config.host, config.port))
+ return {"quote": {"last": 150}}
+
+ monkeypatch.setattr(local, "get_account_snapshot", account)
+ monkeypatch.setattr(local, "get_positions", positions)
+ monkeypatch.setattr(local, "get_quote", quote)
+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json", connection_store=registry)
+ settings.save({"display_currency": "USD", "sources": [{"connection_id": name, "label": name} for name in ("first", "second")]})
+ service = PortfolioService(
+ PortfolioStore(tmp_path / "portfolio.sqlite3"),
+ settings_store=settings,
+ fx_fetcher=lambda: (Decimal("7.2"), Decimal("7.8"), "2026-08-09T00:00:00+00:00"),
+ )
+ snapshot = service.refresh()
+ assert snapshot["complete"] is True
+ assert calls == [
+ (operation, f"{name}.local", port)
+ for name, port in (("first", 4002), ("second", 7497))
+ for operation in ("account", "positions", "quote")
+ ]
+
+
def test_refresh_aggregates_three_readonly_connectors(tmp_path):
accounts = {
"ibkr-live-local-readonly": {"summary": [{"tag": "NetLiquidation", "value": "1000", "currency": "USD"}]},
diff --git a/frontend/src/components/portfolio/ConnectionCenter.tsx b/frontend/src/components/portfolio/ConnectionCenter.tsx
index 8d8acad76..4674eebc3 100644
--- a/frontend/src/components/portfolio/ConnectionCenter.tsx
+++ b/frontend/src/components/portfolio/ConnectionCenter.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { CheckCircle2, FolderCode, Loader2, PlugZap, Plus, ShieldCheck, Trash2, Wallet, X } from "lucide-react";
import { PortfolioCompatibilityBadge } from "@/components/portfolio/PortfolioCompatibilityBadge";
@@ -169,6 +169,45 @@ export function ConnectionCenter({ open, onClose, onChanged }: Props) {
function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSaved, setBusy, setMessage }: { connection: LocalConnection; busy: string | null; testResult?: TestResult; onTest: (connection: LocalConnection) => Promise<void>; onDelete: (connection: LocalConnection) => Promise<void>; onSaved: () => Promise<void>; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void }) {
const { t } = useTranslation();
const [values, setValues] = useState<Record<string, string>>({});
+ const socketConnection = (connection.connector === "ibkr" && connection.transport === "local_tws")
+ || (connection.connector === "futu" && connection.transport === "broker_sdk");
+ const endpoint = connection.effective_endpoint ?? connection.endpoint;
+ const [host, setHost] = useState(endpoint?.host ?? "");
+ const [port, setPort] = useState(String(endpoint?.port ?? ""));
+ const [endpointError, setEndpointError] = useState<string | null>(null);
+ const previousEndpoint = useRef(endpoint);
+ useEffect(() => {
+ const previous = previousEndpoint.current;
+ previousEndpoint.current = endpoint;
+ if (previous?.host === endpoint?.host && previous?.port === endpoint?.port) return;
+ setHost(endpoint?.host ?? "");
+ setPort(String(endpoint?.port ?? ""));
+ }, [endpoint?.host, endpoint?.port]);
+ const endpointDirty = socketConnection && (host.trim() !== (endpoint?.host ?? "") || port !== String(endpoint?.port ?? ""));
+ const endpointValid = host.trim().length > 0 && host.trim().length <= 253
+ && !/[\s/\\@?#]/.test(host.trim()) && /^\d+$/.test(port)
+ && Number(port) >= 1 && Number(port) <= 65535;
+ async function testConnection() {
+ if (!socketConnection) {
+ await onTest(connection);
+ return;
+ }
+ if (!endpointValid || busy !== null) return;
+ setBusy(`test:${connection.id}`);
+ setEndpointError(null);
+ setMessage(null);
+ try {
+ await api.saveConnectionEndpoint(connection.id, { host: host.trim(), port: Number(port) });
+ await onSaved();
+ setHost(host.trim());
+ setPort(String(Number(port)));
+ await onTest(connection);
+ } catch (error) {
+ setEndpointError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setBusy(null);
+ }
+ }
async function saveCredentials() {
setBusy(`credentials:${connection.id}`);
setMessage(null);
@@ -186,10 +225,15 @@ function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSave
return <article className="rounded-xl border bg-card p-4">
<div className="flex items-start justify-between gap-3"><div><div className="font-medium">{connection.label}</div><div className="mt-1 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection.connector.toUpperCase()}</span><span>·</span><span>{connection.environment === "live" ? t("portfolio.env.live") : t("portfolio.env.paper")}</span><span>·</span><span>{connection.transport}</span></div></div><div className="flex flex-col items-end gap-2"><span className="inline-flex items-center gap-1 rounded-full bg-positive/10 px-2 py-1 text-xs text-positive"><ShieldCheck className="h-3 w-3" />{t("portfolio.connections.readOnly")}</span><PortfolioCompatibilityBadge compatibility={connection.portfolio_compatibility} /></div></div>
{connection.onboarding ? <SetupContract onboarding={connection.onboarding} /> : null}
+ {socketConnection ? <fieldset disabled={busy !== null} className="mt-4 grid gap-2 sm:grid-cols-2">
+ <label className="text-xs text-muted-foreground">Host<input type="text" value={host} onChange={(event) => setHost(event.target.value)} required maxLength={253} className={`mt-1 ${fieldClass}`} placeholder="127.0.0.1" autoComplete="off" spellCheck={false} /></label>
+ <label className="text-xs text-muted-foreground">Port<input type="text" inputMode="numeric" pattern="[0-9]*" value={port} onChange={(event) => setPort(event.target.value)} required maxLength={5} className={`mt-1 ${fieldClass}`} autoComplete="off" /></label>
+ {endpointError || connection.endpoint_error ? <p role="alert" className="text-xs text-danger sm:col-span-2">{endpointError ?? connection.endpoint_error}</p> : null}
+ </fieldset> : null}
{connection.account_selection_required ? <AccountSelector connection={connection} busy={busy} setBusy={setBusy} setMessage={setMessage} onSaved={onSaved} /> : null}
{connection.credential_fields.length ? <div className="mt-4 grid gap-2 sm:grid-cols-2">{connection.credential_fields.map((field) => <label key={field.name} className="text-xs text-muted-foreground">{field.label}{field.required ? <span className="ml-1 text-danger">*</span> : <span className="ml-1">{t("portfolio.connections.optional")}</span>}{connection.credential_status[field.name] ? <span className="ml-1 text-positive">{t("portfolio.connections.credentialSaved")}</span> : null}<input type={field.secret ? "password" : "text"} value={values[field.name] ?? ""} onChange={(event) => setValues((current) => ({ ...current, [field.name]: event.target.value }))} className={`mt-1 ${fieldClass}`} placeholder={connection.credential_status[field.name] ? "••••••••" : ""} autoComplete="off" /></label>)}</div> : <p className="mt-3 text-xs text-muted-foreground">{connection.transport === "remote_mcp" ? t("portfolio.connections.oauthNote") : t("portfolio.connections.localNote")}</p>}
- <div className="mt-4 flex flex-wrap gap-2">{connection.credential_fields.length ? <button type="button" onClick={() => void saveCredentials()} disabled={busy === `credentials:${connection.id}` || !Object.values(values).some(Boolean)} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40"><ShieldCheck className="h-3.5 w-3.5" />{t("portfolio.connections.saveVault")}</button> : null}<button type="button" onClick={() => void onTest(connection)} disabled={busy === `test:${connection.id}`} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs">{busy === `test:${connection.id}` ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}{t("portfolio.connections.test")}</button><button type="button" onClick={() => void onDelete(connection)} disabled={busy === `delete:${connection.id}`} className="ml-auto inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs text-danger hover:bg-danger/10"><Trash2 className="h-3.5 w-3.5" />{t("portfolio.connections.delete")}</button></div>
- {testResult ? <div role="status" className={`mt-3 rounded-md border px-3 py-2 text-xs ${testResult.ok ? "border-positive/30 bg-positive/5 text-positive" : "border-danger/30 bg-danger/5 text-danger"}`}>{testResult.message}</div> : null}
+ <div className="mt-4 flex flex-wrap gap-2">{connection.credential_fields.length ? <button type="button" onClick={() => void saveCredentials()} disabled={busy === `credentials:${connection.id}` || !Object.values(values).some(Boolean)} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40"><ShieldCheck className="h-3.5 w-3.5" />{t("portfolio.connections.saveVault")}</button> : null}<button type="button" onClick={() => void testConnection()} disabled={socketConnection ? busy !== null || !endpointValid : busy === `test:${connection.id}`} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs">{busy === `test:${connection.id}` ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}{t("portfolio.connections.test")}</button><button type="button" onClick={() => void onDelete(connection)} disabled={busy === `delete:${connection.id}`} className="ml-auto inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs text-danger hover:bg-danger/10"><Trash2 className="h-3.5 w-3.5" />{t("portfolio.connections.delete")}</button></div>
+ {testResult && !endpointDirty ? <div role="status" className={`mt-3 rounded-md border px-3 py-2 text-xs ${testResult.ok ? "border-positive/30 bg-positive/5 text-positive" : "border-danger/30 bg-danger/5 text-danger"}`}>{testResult.message}</div> : null}
{connection.credentials_configured ? <div className="mt-3 flex items-center gap-1.5 text-xs text-positive"><CheckCircle2 className="h-3.5 w-3.5" />{t("portfolio.connections.configured")}</div> : null}
</article>;
}
diff --git a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx
index a38c07418..f911c9ad4 100644
--- a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx
+++ b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ConnectionCenter } from "@/components/portfolio/ConnectionCenter";
import { api, type LocalConnection } from "@/lib/api";
@@ -13,6 +13,8 @@ vi.mock("@/lib/api", async () => {
getConnections: vi.fn(),
getConnectionAccounts: vi.fn(),
selectConnectionAccount: vi.fn(),
+ saveConnectionEndpoint: vi.fn(),
+ checkConnection: vi.fn(),
},
};
});
@@ -21,6 +23,8 @@ const mocked = api as unknown as {
getConnections: ReturnType<typeof vi.fn>;
getConnectionAccounts: ReturnType<typeof vi.fn>;
selectConnectionAccount: ReturnType<typeof vi.fn>;
+ saveConnectionEndpoint: ReturnType<typeof vi.fn>;
+ checkConnection: ReturnType<typeof vi.fn>;
};
function robinhood(accountRef: string): LocalConnection {
@@ -113,4 +117,148 @@ describe("ConnectionCenter account selection", () => {
expect(await screen.findByRole("alert")).toHaveTextContent("token expired");
expect(mocked.selectConnectionAccount).not.toHaveBeenCalled();
});
+
+ it("keeps the original remote connection behavior while selecting an account", async () => {
+ let finishAccounts!: (value: unknown) => void;
+ mocked.getConnectionAccounts.mockImplementation(() => new Promise((resolve) => { finishAccounts = resolve; }));
+ mocked.checkConnection.mockResolvedValue({ status: "ok", report: { status: "ok" } });
+ const onChanged = renderCenter(robinhood(""));
+ const test = await screen.findByRole("button", { name: i18n.t("portfolio.connections.test") });
+ fireEvent.click(test);
+ expect(await screen.findByRole("status")).toHaveTextContent("Robinhood");
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.accountLoad") }));
+ expect(test).toBeEnabled();
+ finishAccounts({ accounts: [{ account_ref: "5QR12345", label: "Main", deactivated: false }] });
+ const select = await screen.findByLabelText(i18n.t("portfolio.connections.accountPicker"));
+ fireEvent.change(select, { target: { value: "5QR12345" } });
+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [robinhood("5QR12345")], profiles: [] });
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.accountSave") }));
+ await waitFor(() => expect(onChanged).toHaveBeenCalled());
+ expect(screen.getByRole("status")).toHaveTextContent("Robinhood");
+ });
+});
+
+function ibkr(): LocalConnection {
+ return {
+ ...robinhood(""),
+ id: "ibkr-paper",
+ profile_id: "ibkr-paper-local",
+ label: "IBKR Paper",
+ connector: "ibkr",
+ environment: "paper",
+ transport: "local_tws",
+ account_selection_required: false,
+ effective_endpoint: { host: "127.0.0.1", port: 7497 },
+ };
+}
+
+describe("ConnectionCenter IBKR address", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocked.saveConnectionEndpoint.mockResolvedValue({ status: "ok" });
+ mocked.checkConnection.mockResolvedValue({ status: "ok", report: { status: "ok" } });
+ });
+
+ it("saves the edited address before testing, without a separate save button", async () => {
+ const connection = ibkr();
+ const onChanged = renderCenter(connection);
+ expect(await screen.findByLabelText("Host")).toHaveValue("127.0.0.1");
+ expect(screen.getByLabelText("Port")).toHaveValue("7497");
+ expect(screen.queryByRole("button", { name: /Save address|保存地址/ })).not.toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText("Host"), { target: { value: "host.docker.internal" } });
+ fireEvent.change(screen.getByLabelText("Port"), { target: { value: "4002" } });
+ expect(mocked.saveConnectionEndpoint).not.toHaveBeenCalled();
+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [{ ...connection, effective_endpoint: { host: "host.docker.internal", port: 4002 } }], profiles: [] });
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.test") }));
+
+ await waitFor(() => expect(mocked.saveConnectionEndpoint).toHaveBeenCalledWith("ibkr-paper", { host: "host.docker.internal", port: 4002 }));
+ await waitFor(() => expect(mocked.checkConnection).toHaveBeenCalledWith("ibkr-paper"));
+ expect(mocked.saveConnectionEndpoint.mock.invocationCallOrder[0]).toBeLessThan(mocked.checkConnection.mock.invocationCallOrder[0]);
+ expect(onChanged).toHaveBeenCalled();
+ expect(await screen.findByRole("status")).toHaveTextContent(i18n.t("portfolio.connections.testOk", { label: "IBKR Paper" }));
+ });
+
+ it.each(["", "0", "65536", "1.5"])("disables testing invalid port %s", async (port) => {
+ renderCenter(ibkr());
+ fireEvent.change(await screen.findByLabelText("Port"), { target: { value: port } });
+ expect(screen.getByLabelText("Port")).toHaveValue(port);
+ expect(screen.getByRole("button", { name: i18n.t("portfolio.connections.test") })).toBeDisabled();
+ expect(mocked.checkConnection).not.toHaveBeenCalled();
+ });
+
+ it("keeps the draft and skips testing when saving fails", async () => {
+ mocked.saveConnectionEndpoint.mockRejectedValue(new Error("address rejected"));
+ await act(async () => { renderCenter(ibkr()); });
+ fireEvent.change(await screen.findByLabelText("Host"), { target: { value: "gateway.local" } });
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.test") }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("address rejected");
+ expect(screen.getByLabelText("Host")).toHaveValue("gateway.local");
+ expect(mocked.checkConnection).not.toHaveBeenCalled();
+ });
+
+ it("waits for persistence before testing and prevents duplicate clicks", async () => {
+ let finishSave!: () => void;
+ mocked.saveConnectionEndpoint.mockImplementation(() => new Promise<void>((resolve) => { finishSave = resolve; }));
+ renderCenter(ibkr());
+ const test = await screen.findByRole("button", { name: i18n.t("portfolio.connections.test") });
+ fireEvent.click(test);
+ expect(test).toBeDisabled();
+ fireEvent.click(test);
+ expect(mocked.saveConnectionEndpoint).toHaveBeenCalledTimes(1);
+ expect(mocked.checkConnection).not.toHaveBeenCalled();
+ finishSave();
+ await waitFor(() => expect(mocked.checkConnection).toHaveBeenCalledTimes(1));
+ });
+
+ it("keeps the saved address when the subsequent connection test fails", async () => {
+ const connection = ibkr();
+ renderCenter(connection);
+ fireEvent.change(await screen.findByLabelText("Port"), { target: { value: "4002" } });
+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [{ ...connection, effective_endpoint: { host: "127.0.0.1", port: 4002 } }], profiles: [] });
+ mocked.checkConnection.mockResolvedValue({ status: "ok", report: { status: "error", error: "gateway unavailable" } });
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.test") }));
+ expect(await screen.findByRole("status")).toHaveTextContent("gateway unavailable");
+ expect(mocked.saveConnectionEndpoint).toHaveBeenCalledWith("ibkr-paper", { host: "127.0.0.1", port: 4002 });
+ expect(screen.getByLabelText("Port")).toHaveValue("4002");
+ });
+
+ it("tests remote MCP connections without saving a socket address", async () => {
+ renderCenter({ ...ibkr(), transport: "remote_mcp" });
+ fireEvent.click(await screen.findByRole("button", { name: i18n.t("portfolio.connections.test") }));
+ await waitFor(() => expect(mocked.checkConnection).toHaveBeenCalledWith("ibkr-paper"));
+ expect(screen.queryByLabelText("Host")).not.toBeInTheDocument();
+ expect(mocked.saveConnectionEndpoint).not.toHaveBeenCalled();
+ });
+});
+
+describe("Futu socket configuration", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocked.saveConnectionEndpoint.mockResolvedValue({ status: "ok" });
+ mocked.checkConnection.mockResolvedValue({ status: "ok", report: { status: "ok" } });
+ });
+
+ it.each(["paper", "live"] as const)("shows original Futu %s defaults and saves before testing", async (environment) => {
+ const connection: LocalConnection = {
+ ...ibkr(), id: `futu-${environment}`, connector: "futu", environment,
+ profile_id: environment === "paper" ? "futu-paper-sdk" : "futu-live-sdk-readonly",
+ label: "Futu", transport: "broker_sdk", effective_endpoint: { host: "127.0.0.1", port: 11111 },
+ };
+ renderCenter(connection);
+ expect(await screen.findByLabelText("Host")).toHaveValue("127.0.0.1");
+ const port = screen.getByRole("textbox", { name: "Port" });
+ expect(port).toHaveValue("11111");
+ expect(port).toHaveAttribute("inputmode", "numeric");
+ expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();
+ fireEvent.wheel(port, { deltaY: -100 });
+ expect(port).toHaveValue("11111");
+ fireEvent.change(screen.getByLabelText("Host"), { target: { value: "host.docker.internal" } });
+ fireEvent.change(port, { target: { value: "11112" } });
+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [{ ...connection, effective_endpoint: { host: "host.docker.internal", port: 11112 } }], profiles: [] });
+ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.connections.test") }));
+ await waitFor(() => expect(mocked.checkConnection).toHaveBeenCalledWith(connection.id));
+ expect(mocked.saveConnectionEndpoint).toHaveBeenCalledWith(connection.id, { host: "host.docker.internal", port: 11112 });
+ expect(mocked.saveConnectionEndpoint.mock.invocationCallOrder[0]).toBeLessThan(mocked.checkConnection.mock.invocationCallOrder[0]);
+ });
});
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index b7c083f3b..9d60e4dc5 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -324,6 +324,11 @@ export interface ConnectorOnboarding {
secret_storage: "os_keyring" | null;
}
+export interface SocketEndpoint {
+ host: string;
+ port: number;
+}
+
export interface LocalConnection {
portfolio_eligible?: boolean;
id: string;
@@ -333,6 +338,9 @@ export interface LocalConnection {
account_ref: string;
/** True when this connection reads nothing until an account is selected. */
account_selection_required: boolean;
+ endpoint?: SocketEndpoint | null;
+ effective_endpoint?: SocketEndpoint;
+ endpoint_error?: string;
connector: string;
environment: "paper" | "live";
transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin";
@@ -503,6 +511,11 @@ export const api = {
`/api/connections/${encodeURIComponent(connectionId)}/credentials`,
{ method: "POST", body: JSON.stringify({ values }) },
),
+ saveConnectionEndpoint: (connectionId: string, endpoint: SocketEndpoint) =>
+ request<{ status: string }>(
+ `/api/connections/${encodeURIComponent(connectionId)}/endpoint`,
+ { method: "PUT", body: JSON.stringify(endpoint) },
+ ),
checkConnection: (connectionId: string) =>
request<{ status: string; connection_id: string; report: Record<string, unknown> }>(
`/api/connections/${encodeURIComponent(connectionId)}/check`,