"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(portfolio): isolate OAuth reconnect lifecycle
Yang4a68de8fd9c0
diff --git a/agent/src/api/portfolio_routes.py b/agent/src/api/portfolio_routes.pyindex 3b2c31f50..9a0c452b6 100644--- a/agent/src/api/portfolio_routes.py+++ b/agent/src/api/portfolio_routes.py@@ -2,8 +2,11 @@from __future__ import annotations+import subprocess+import sysimport threadingfrom copy import deepcopy+from datetime import datetime, timezonefrom fastapi import Depends, FastAPI, HTTPException, Query, Responsefrom pydantic import BaseModel, Field@@ -13,6 +16,17 @@ from src.portfolio.service import PortfolioService_REFRESH_LOCK = threading.Lock()_REFRESH_OPERATION_LOCK = threading.Lock()+_RECONNECT_OPERATION_LOCK = threading.Lock()+_RECONNECT_STATE_LOCK = threading.Lock()+_RECONNECT_TIMEOUT_SECONDS = 330+_RECONNECT_STATE = {+ "running": False,+ "source_id": None,+ "status": "idle",+ "error": None,+ "started_at": None,+ "finished_at": None,+}_REFRESH_STATE = {"running": False,"current": None,@@ -46,6 +60,64 @@ def _set_refresh_progress(source_id: str, status: str, error: str | None) -> Non_REFRESH_STATE["sources"][source_id] = {"status": status, "error": error}+def _reconnect_snapshot() -> dict:+ with _RECONNECT_STATE_LOCK:+ return deepcopy(_RECONNECT_STATE)+++def _set_reconnect_state(**updates) -> None:+ with _RECONNECT_STATE_LOCK:+ _RECONNECT_STATE.update(updates)+++def _stop_reconnect_process(process: subprocess.Popen) -> None:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++def _run_reconnect(source_id: str) -> None:+ process = None+ try:+ process = subprocess.Popen(+ [sys.executable, "-m", "src.portfolio.oauth_worker", source_id],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ return_code = process.wait(timeout=_RECONNECT_TIMEOUT_SECONDS)+ if return_code == 0:+ _set_reconnect_state(status="authorized", error=None)+ else:+ _set_reconnect_state(+ status="error",+ error="Authorization did not complete. Close the old broker authorization tab and reconnect.",+ )+ except subprocess.TimeoutExpired:+ if process is not None:+ _stop_reconnect_process(process)+ _set_reconnect_state(+ status="timeout",+ error="Authorization timed out. The callback server was closed and reconnect is safe to retry.",+ )+ except Exception:+ if process is not None and process.poll() is None:+ _stop_reconnect_process(process)+ _set_reconnect_state(+ status="error", error="Unable to start the local authorization process."+ )+ finally:+ _set_reconnect_state(+ running=False,+ finished_at=datetime.now(timezone.utc).isoformat(),+ )+ _RECONNECT_OPERATION_LOCK.release()++def register_portfolio_routes(app: FastAPI) -> None:"""Register the authenticated, read-only portfolio endpoints.@@ -106,12 +178,54 @@ def register_portfolio_routes(app: FastAPI) -> None:@app.post("/api/portfolio/sources/{source_id}/reconnect",dependencies=[Depends(require_auth)],+ status_code=202,)def reconnect_portfolio_source(source_id: str):+ if not _RECONNECT_OPERATION_LOCK.acquire(blocking=False):+ raise HTTPException(+ status_code=409, detail="portfolio reconnect already running"+ )try:- return service().reconnect_source(source_id)+ service().reconnect_target(source_id)except RuntimeError as exc:+ _RECONNECT_OPERATION_LOCK.release()raise HTTPException(status_code=503, detail=str(exc)) from exc+ except Exception as exc:+ _RECONNECT_OPERATION_LOCK.release()+ raise HTTPException(+ status_code=503, detail="Unable to load the local OAuth configuration"+ ) from exc+ _set_reconnect_state(+ running=True,+ source_id=source_id,+ status="authorizing",+ error=None,+ started_at=datetime.now(timezone.utc).isoformat(),+ finished_at=None,+ )+ try:+ threading.Thread(+ target=_run_reconnect,+ args=(source_id,),+ daemon=True,+ name=f"portfolio-oauth-{source_id}",+ ).start()+ except Exception:+ _RECONNECT_OPERATION_LOCK.release()+ _set_reconnect_state(+ running=False,+ status="error",+ error="Unable to start the local authorization task.",+ finished_at=datetime.now(timezone.utc).isoformat(),+ )+ raise HTTPException(+ status_code=503, detail="Unable to start the local authorization task"+ )+ return {"status": "started", "reconnect": _reconnect_snapshot()}++ @app.get("/api/portfolio/reconnect-status", dependencies=[Depends(require_auth)])+ def portfolio_reconnect_status():+ return {"status": "ok", "reconnect": _reconnect_snapshot()}@app.get("/api/portfolio/settings", dependencies=[Depends(require_auth)])def portfolio_settings():diff --git a/agent/src/portfolio/oauth_worker.py b/agent/src/portfolio/oauth_worker.pynew file mode 100644index 000000000..db2707df0--- /dev/null+++ b/agent/src/portfolio/oauth_worker.py@@ -0,0 +1,27 @@+"""Isolated worker for an interactive portfolio OAuth reconnect.++OAuth libraries may leave their loopback callback server alive after a failed+handshake. Running the flow in a short-lived process guarantees that the+callback port is released on success, failure, cancellation, or timeout.+"""++from __future__ import annotations++import argparse++from src.portfolio.service import PortfolioService+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("source_id")+ args = parser.parse_args()+ try:+ PortfolioService().reconnect_source(args.source_id)+ except BaseException: # The parent reports a redacted, actionable error.+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex bbbbf386b..a1b0a119f 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport csvimport ioimport json+import socketimport subprocessimport sysimport urllib.request@@ -58,6 +59,29 @@ def _now() -> str:return datetime.now(timezone.utc).isoformat()+def _ensure_callback_port_available(port: int) -> None:+ """Fail cleanly before an embedded OAuth callback server tries to bind."""+ try:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.bind(("127.0.0.1", port))+ except OSError as exc:+ raise RuntimeError(+ f"OAuth callback port {port} is already in use; close the old authorization flow and retry"+ ) from exc+++def _contains_system_exit(error: BaseException) -> bool:+ """Return whether an exception or nested exception group contains SystemExit."""+ if isinstance(error, SystemExit):+ return True+ nested = getattr(error, "exceptions", ())+ return any(+ _contains_system_exit(item)+ for item in nested+ if isinstance(item, BaseException)+ )++def _quote_price(payload: dict[str, Any]) -> Decimal | None:quote = payload.get("quote") or {}for key in ("last", "close"):@@ -399,9 +423,48 @@ class PortfolioService:RuntimeError: If the source is unknown, does not use OAuth, or itsMCP server is not configured."""- from src.config.loader import load_agent_config+ from src.config.accessor import get_env_configfrom src.tools.mcp import MCPServerAdapter+ source, profile, server = self.reconnect_target(source_id)+ authorize_timeout = float(+ get_env_config().agent_tuning.vibe_live_authorize_timeout_s or 300+ )+ if hasattr(server, "model_copy"):+ updates = {}+ if float(server.init_timeout or 0) < authorize_timeout:+ updates["init_timeout"] = authorize_timeout+ if float(server.tool_timeout or 0) < authorize_timeout:+ updates["tool_timeout"] = authorize_timeout+ if updates:+ server = server.model_copy(update=updates)+ callback_port = server.auth.callback_port if server.auth is not None else None+ if callback_port is not None:+ _ensure_callback_port_available(callback_port)+ try:+ tools = MCPServerAdapter(+ profile.connector,+ server,+ max_list_tools_attempts=1,+ interactive_oauth=True,+ ).discover_tools()+ except BaseException as exc:+ if not _contains_system_exit(exc):+ raise+ raise RuntimeError(+ "OAuth callback startup failed; authorization stopped safely"+ ) from exc+ return {+ "status": "ok",+ "authorized": True,+ "source_id": source.id,+ "enabled_read_tools": [item.remote_name for item in tools],+ }++ def reconnect_target(self, source_id: str):+ """Validate and return the local-only configuration for an OAuth source."""+ from src.config.loader import load_agent_config+source = next((item@@ -418,18 +481,11 @@ class PortfolioService:server = (load_agent_config().mcp_servers or {}).get(profile.connector)if server is None:raise RuntimeError(f"the {profile.connector} MCP connection is not configured")- tools = MCPServerAdapter(- profile.connector,- server,- max_list_tools_attempts=1,- interactive_oauth=True,- ).discover_tools()- return {- "status": "ok",- "authorized": True,- "source_id": source.id,- "enabled_read_tools": [item.remote_name for item in tools],- }+ if server.auth is None:+ raise RuntimeError(+ f"the {profile.connector} MCP connection does not configure OAuth"+ )+ return source, profile, serverdef history(self, limit: int = 180) -> list[dict[str, Any]]:"""Return the value series built only from complete snapshots.diff --git a/agent/tests/test_portfolio_routes.py b/agent/tests/test_portfolio_routes.pyindex 008945a85..81df981a3 100644--- a/agent/tests/test_portfolio_routes.py+++ b/agent/tests/test_portfolio_routes.py@@ -1,5 +1,7 @@from __future__ import annotations+import time+from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -31,8 +33,8 @@ class _Service:def history(self, limit):return [{"id": "one", "limit": limit}]- def reconnect_source(self, source_id):- return {"status": "ok", "authorized": True, "source_id": source_id}+ def reconnect_target(self, source_id):+ return object(), object(), object()def export_csv(self):return "broker,symbol\nibkr,AAPL\n"@@ -43,6 +45,16 @@ class _Service:def test_portfolio_routes_are_readonly_and_return_expected_shapes(monkeypatch):monkeypatch.setattr(portfolio_routes, "PortfolioService", _Service)++ class _SuccessfulProcess:+ def wait(self, timeout):+ return 0++ monkeypatch.setattr(+ portfolio_routes.subprocess,+ "Popen",+ lambda *args, **kwargs: _SuccessfulProcess(),+ )app = FastAPI()portfolio_routes.register_portfolio_routes(app)client = TestClient(app)@@ -77,10 +89,17 @@ def test_portfolio_routes_are_readonly_and_return_expected_shapes(monkeypatch):)assert saved.status_code == 200assert saved.json()["settings"]["display_currency"] == "CNY"- assert (- client.post("/api/portfolio/sources/ibkr/reconnect").json()["source_id"]- == "ibkr"- )+ reconnect = client.post("/api/portfolio/sources/ibkr/reconnect")+ assert reconnect.status_code == 202+ for _ in range(50):+ reconnect_status = client.get("/api/portfolio/reconnect-status").json()[+ "reconnect"+ ]+ if not reconnect_status["running"]:+ break+ time.sleep(0.01)+ assert reconnect_status["source_id"] == "ibkr"+ assert reconnect_status["status"] == "authorized"assert (client.get("/api/portfolio/analysis-context").json()["context"]["privacy"]== "sanitized"@@ -88,3 +107,54 @@ def test_portfolio_routes_are_readonly_and_return_expected_shapes(monkeypatch):exported = client.get("/api/portfolio/export.csv")assert exported.status_code == 200assert "ibkr,AAPL" in exported.text+++def test_concurrent_portfolio_reconnect_returns_conflict(monkeypatch):+ monkeypatch.setattr(portfolio_routes, "PortfolioService", _Service)+ app = FastAPI()+ portfolio_routes.register_portfolio_routes(app)+ client = TestClient(app)++ assert portfolio_routes._RECONNECT_OPERATION_LOCK.acquire(blocking=False)+ try:+ response = client.post("/api/portfolio/sources/ibkr/reconnect")+ finally:+ portfolio_routes._RECONNECT_OPERATION_LOCK.release()++ assert response.status_code == 409+ assert response.json()["detail"] == "portfolio reconnect already running"+++def test_reconnect_timeout_stops_worker_and_releases_operation_lock(monkeypatch):+ class _TimedOutProcess:+ def __init__(self):+ self.terminated = False++ def wait(self, timeout):+ if not self.terminated:+ raise portfolio_routes.subprocess.TimeoutExpired("oauth", timeout)+ return -15++ def terminate(self):+ self.terminated = True++ def kill(self):+ self.terminated = True++ def poll(self):+ return None++ process = _TimedOutProcess()+ monkeypatch.setattr(+ portfolio_routes.subprocess, "Popen", lambda *args, **kwargs: process+ )+ assert portfolio_routes._RECONNECT_OPERATION_LOCK.acquire(blocking=False)++ portfolio_routes._run_reconnect("ibkr")++ state = portfolio_routes._reconnect_snapshot()+ assert state["running"] is False+ assert state["status"] == "timeout"+ assert process.terminated is True+ assert portfolio_routes._RECONNECT_OPERATION_LOCK.acquire(blocking=False)+ portfolio_routes._RECONNECT_OPERATION_LOCK.release()diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.pyindex 7e21cb733..7a42f3322 100644--- a/agent/tests/test_portfolio_service.py+++ b/agent/tests/test_portfolio_service.py@@ -1,6 +1,8 @@from __future__ import annotations+import socketfrom decimal import Decimal+from types import SimpleNamespaceimport pytest@@ -476,3 +478,64 @@ def test_auth_metadata_describes_the_profile_without_claiming_key_permissions():"readonly": True,"detail": "Use credentials configured by the local operator.",}+++def _reconnect_service(tmp_path):+ return PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=_settings_store(tmp_path),+ get_account=lambda *_args, **_kwargs: {},+ get_positions=lambda *_args, **_kwargs: {},+ get_quote=lambda *_args, **_kwargs: {},+ )+++def _oauth_profile():+ return TradingProfile(+ id="ibkr-live-official-mcp-readonly",+ connector="ibkr",+ label="IBKR OAuth",+ environment="live",+ transport="remote_mcp",+ capabilities=("account.read", "positions.read"),+ readonly=True,+ )+++def test_reconnect_rejects_an_occupied_oauth_callback_port(monkeypatch, tmp_path):+ monkeypatch.setattr(portfolio_service, "profile_by_id", lambda *_: _oauth_profile())+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ callback_port = listener.getsockname()[1]+ server = SimpleNamespace(+ auth=SimpleNamespace(callback_port=callback_port),+ )+ monkeypatch.setattr(+ "src.config.loader.load_agent_config",+ lambda: SimpleNamespace(mcp_servers={"ibkr": server}),+ )++ with pytest.raises(RuntimeError, match=str(callback_port)):+ _reconnect_service(tmp_path).reconnect_source("ibkr")+++def test_reconnect_contains_callback_server_system_exit(monkeypatch, tmp_path):+ monkeypatch.setattr(portfolio_service, "profile_by_id", lambda *_: _oauth_profile())+ server = SimpleNamespace(auth=SimpleNamespace(callback_port=None))+ monkeypatch.setattr(+ "src.config.loader.load_agent_config",+ lambda: SimpleNamespace(mcp_servers={"ibkr": server}),+ )++ class FailingAdapter:+ def __init__(self, *_args, **_kwargs):+ pass++ def discover_tools(self):+ raise BaseExceptionGroup("callback startup", [SystemExit(3)])++ monkeypatch.setattr("src.tools.mcp.MCPServerAdapter", FailingAdapter)++ with pytest.raises(RuntimeError, match="stopped safely"):+ _reconnect_service(tmp_path).reconnect_source("ibkr")diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex b70e9f027..1d49b18b0 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -159,6 +159,15 @@ export interface PortfolioRefreshState {brokers?: Record<string, { status: "idle" | "pending" | "refreshing" | "ok" | "error"; error?: string | null }>;}+export interface PortfolioReconnectState {+ running: boolean;+ source_id: string | null;+ status: "idle" | "authorizing" | "authorized" | "error" | "timeout";+ error: string | null;+ started_at: string | null;+ finished_at: string | null;+}+export interface PortfolioSourceSettings {connection_id: string;label: string;@@ -322,7 +331,9 @@ export const api = {refreshPortfolio: () => request<{ status: string; snapshot: PortfolioSnapshot }>("/api/portfolio/refresh", { method: "POST" }),getPortfolioRefreshStatus: () => request<{ status: string; refresh: PortfolioRefreshState }>("/api/portfolio/refresh-status"),reconnectPortfolioSource: (sourceId: string) =>- request<{ status: string; authorized: boolean }>(`/api/portfolio/sources/${encodeURIComponent(sourceId)}/reconnect`, { method: "POST" }),+ request<{ status: string; reconnect: PortfolioReconnectState }>(`/api/portfolio/sources/${encodeURIComponent(sourceId)}/reconnect`, { method: "POST" }),+ getPortfolioReconnectStatus: () =>+ request<{ status: string; reconnect: PortfolioReconnectState }>("/api/portfolio/reconnect-status"),getPortfolioSettings: () => request<PortfolioSettingsResponse>("/api/portfolio/settings"),updatePortfolioSettings: (settings: PortfolioSettings) =>request<PortfolioSettingsResponse>("/api/portfolio/settings", {diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsxindex 517c55087..da4164e46 100644--- a/frontend/src/pages/Portfolio.tsx+++ b/frontend/src/pages/Portfolio.tsx@@ -120,7 +120,7 @@ export function Portfolio() {const [history, setHistory] = useState<PortfolioHistoryPoint[]>([]);const [loading, setLoading] = useState(true);const [refreshing, setRefreshing] = useState(false);- const [reconnecting, setReconnecting] = useState(false);+ const [reconnectingSource, setReconnectingSource] = useState<string | null>(null);const [refreshState, setRefreshState] = useState<PortfolioRefreshState | null>(null);const [portfolioSettings, setPortfolioSettings] = useState<PortfolioSettings | null>(null);const [sourceCatalog, setSourceCatalog] = useState<PortfolioSourceCatalogItem[]>([]);@@ -185,15 +185,24 @@ export function Portfolio() {}async function reconnectSource(sourceId: string) {- setReconnecting(true);+ setReconnectingSource(sourceId);setError(null);try {await api.reconnectPortfolioSource(sourceId);+ for (;;) {+ await new Promise((resolve) => window.setTimeout(resolve, 1_000));+ const result = await api.getPortfolioReconnectStatus();+ if (result.reconnect.running) continue;+ if (result.reconnect.status !== "authorized") {+ throw new Error(result.reconnect.error ?? "Account reconnect failed");+ }+ break;+ }await refresh();} catch (err) {setError(err instanceof Error ? err.message : t("portfolio.page.errorReconnect"));} finally {- setReconnecting(false);+ setReconnectingSource(null);}}@@ -320,7 +329,7 @@ export function Portfolio() {<button onClick={() => void download()} disabled={!snapshot} className="inline-flex items-center gap-2 rounded-md border bg-card px-4 py-2 text-sm disabled:opacity-50"><Download className="h-4 w-4" />{t("portfolio.page.exportCsv")}</button>- <button onClick={() => void refresh()} disabled={refreshing || reconnecting} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">+ <button onClick={() => void refresh()} disabled={refreshing || reconnectingSource !== null} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">{refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}{refreshing ? t("portfolio.page.refreshing") : t("portfolio.page.refreshAll")}</button>@@ -391,7 +400,7 @@ export function Portfolio() {</div><div className="grid gap-3 lg:grid-cols-3">{snapshot.accounts.map((account) => (- <AccountCard key={account.source_id ?? account.broker} account={account} active={sourceFilter === (account.source_id ?? account.broker)} displayCurrency={displayCurrency} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.auth?.method === "OAuth" && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} reconnecting={reconnecting} />+ <AccountCard key={account.source_id ?? account.broker} account={account} active={sourceFilter === (account.source_id ?? account.broker)} displayCurrency={displayCurrency} onClick={() => { const id = account.source_id ?? account.broker; setSourceFilter((current) => current === id ? "all" : id); }} onReconnect={account.auth?.method === "OAuth" && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} reconnecting={reconnectingSource === account.source_id} reconnectDisabled={reconnectingSource !== null} />))}</div></section>@@ -490,7 +499,7 @@ function RefreshProgress({ state, settings }: { state: PortfolioRefreshState; se* it renders the failure, the error text and the last successful read time* instead of a value, so nothing on the card suggests it is part of the total.*/-function AccountCard({ account, active, displayCurrency, onClick, onReconnect, reconnecting }: { account: PortfolioAccount; active: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; reconnecting: boolean }) {+function AccountCard({ account, active, displayCurrency, onClick, onReconnect, reconnecting, reconnectDisabled }: { account: PortfolioAccount; active: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; reconnecting: boolean; reconnectDisabled: boolean }) {const { t } = useTranslation();const failed = account.status === "error";return <div role="button" tabIndex={0} onClick={onClick} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") onClick(); }} className={`cursor-pointer rounded-xl border bg-card p-5 transition ${active ? "border-primary ring-1 ring-primary/20" : "hover:border-primary/40"}`}>@@ -511,7 +520,7 @@ function AccountCard({ account, active, displayCurrency, onClick, onReconnect, r</>)}{failed && account.error ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={account.error}>{account.error}</p> : null}- {failed && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={reconnecting} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{reconnecting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{t("portfolio.accounts.reconnect")}</button> : null}+ {failed && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={reconnectDisabled} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{reconnecting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{t("portfolio.accounts.reconnect")}</button> : null}</div>;}diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsxindex 801737e3f..d39d31cb7 100644--- a/frontend/src/pages/__tests__/Portfolio.test.tsx+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx@@ -14,6 +14,7 @@ vi.mock("@/lib/api", async () => {refreshPortfolio: vi.fn(),getPortfolioRefreshStatus: vi.fn(),reconnectPortfolioSource: vi.fn(),+ getPortfolioReconnectStatus: vi.fn(),getPortfolioSettings: vi.fn(),updatePortfolioSettings: vi.fn(),getConnections: vi.fn(),@@ -32,6 +33,7 @@ const mocked = api as unknown as {refreshPortfolio: ReturnType<typeof vi.fn>;getPortfolioRefreshStatus: ReturnType<typeof vi.fn>;reconnectPortfolioSource: ReturnType<typeof vi.fn>;+ getPortfolioReconnectStatus: ReturnType<typeof vi.fn>;getPortfolioSettings: ReturnType<typeof vi.fn>;updatePortfolioSettings: ReturnType<typeof vi.fn>;getConnections: ReturnType<typeof vi.fn>;@@ -86,6 +88,29 @@ const snapshotWithFailedSource = {warnings: ["Binance backup could not be read and is excluded from the totals."],};+const snapshotWithFailedOAuth = {+ ...snapshot,+ complete: false,+ accounts: [+ {+ source_id: "ibkr",+ broker: "ibkr",+ label: "IBKR",+ status: "error" as const,+ error_code: "AuthenticationError",+ error: "OAuth authorization expired",+ auth: {+ method: "OAuth",+ renewal: "automatic" as const,+ readonly: true,+ detail: "Interactive reauthorization is required.",+ },+ },+ ...snapshot.accounts.slice(1),+ ],+ warnings: ["IBKR could not be read and is excluded from the totals."],+};+const portfolioConfiguration = {status: "ok",settings: {@@ -111,6 +136,14 @@ describe("Portfolio page", () => {mocked.getPortfolioSettings.mockResolvedValue(portfolioConfiguration);mocked.updatePortfolioSettings.mockResolvedValue(portfolioConfiguration);mocked.refreshPortfolio.mockResolvedValue({ status: "ok", snapshot });+ mocked.reconnectPortfolioSource.mockResolvedValue({+ status: "started",+ reconnect: { running: true, source_id: "ibkr", status: "authorizing" },+ });+ mocked.getPortfolioReconnectStatus.mockResolvedValue({+ status: "ok",+ reconnect: { running: false, source_id: "ibkr", status: "authorized", error: null },+ });mocked.getPortfolioRefreshStatus.mockResolvedValue({status: "ok",refresh: {@@ -176,6 +209,18 @@ describe("Portfolio page", () => {await waitFor(() => expect(mocked.getPortfolioHistory).toHaveBeenCalledTimes(2));});+ it("polls an OAuth reconnect to completion before refreshing the portfolio", async () => {+ mocked.getPortfolio.mockResolvedValue({ status: "ok", snapshot: snapshotWithFailedOAuth });+ render(<Portfolio />);+ await screen.findByText("OAuth authorization expired");++ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.accounts.reconnect") }));++ await waitFor(() => expect(mocked.reconnectPortfolioSource).toHaveBeenCalledWith("ibkr"));+ await waitFor(() => expect(mocked.getPortfolioReconnectStatus).toHaveBeenCalled(), { timeout: 2_000 });+ await waitFor(() => expect(mocked.refreshPortfolio).toHaveBeenCalledTimes(1), { timeout: 2_000 });+ });+it("edits selected read-only accounts without collecting credentials", async () => {render(<Portfolio />);await screen.findByText("AAPL");