"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(portfolio): classify OAuth reconnect failures
Yangb8900d216af7
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex 430b284dd..e2e250113 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -42,6 +42,30 @@ _LOADER_MARKET_SUFFIXES = frozenset(_NON_EQUITY_ASSET_TYPES = frozenset({"crypto", "stablecoin", "cash"})+_AUTH_REQUIRED_MARKERS = (+ "not_authorized",+ "not authorized",+ "authorization required",+ "oauth authorization required",+ "invalid_grant",+ "token expired",+ "oauth token missing",+ "connector authorize",+)+++def _authorization_required(payload: dict[str, Any]) -> bool:+ """Return whether a connector failure explicitly asks for OAuth renewal."""+ status = str(payload.get("status") or "").strip().lower()+ if status in {"not_authorized", "unauthorized"}:+ return True+ message = " ".join(+ str(payload.get(key) or "")+ for key in ("error", "error_code", "error_type")+ ).lower()+ return any(marker in message for marker in _AUTH_REQUIRED_MARKERS)++def _decimal(value: Any, default: Decimal = Decimal("0")) -> Decimal:try:if value is None or value == "":@@ -233,10 +257,19 @@ class PortfolioService:if self._progress_callback is not None:self._progress_callback(source.id, "ok", None)except Exception as exc: # read failures are isolated per connector+ try:+ _, failed_profile = self._connection_profile(source)+ auth_required = failed_profile.transport == "remote_mcp" and _authorization_required(+ {"error": str(exc)}+ )+ except Exception:+ auth_required = Falseresults[source.id] = {"status": "error","error_code": type(exc).__name__,"error": str(exc)[:300],+ "failure_kind": "authorization" if auth_required else "transient",+ "reconnect_required": auth_required,}if self._progress_callback is not None:self._progress_callback(source.id, "error", str(exc)[:160])@@ -383,6 +416,8 @@ class PortfolioService:"status": "error","error": result.get("error"),"error_code": result.get("error_code"),+ "failure_kind": result.get("failure_kind", "transient"),+ "reconnect_required": bool(result.get("reconnect_required")),"last_success_at": cached["created_at"] if cached is not None else None,"total_usd": None,"total_cny": None,diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.pyindex 7a42f3322..58bfdf7f1 100644--- a/agent/tests/test_portfolio_service.py+++ b/agent/tests/test_portfolio_service.py@@ -195,6 +195,8 @@ def test_failed_source_is_excluded_from_totals_and_reports_its_last_success(tmp_assert partial["totals"]["cny"] == 0.0assert ibkr["status"] == "error"assert ibkr["error_code"] == "ConnectionError"+ assert ibkr["failure_kind"] == "transient"+ assert ibkr["reconnect_required"] is Falseassert ibkr["total_usd"] is Noneassert ibkr["total_cny"] is Noneassert ibkr["position_count"] == 0@@ -306,6 +308,54 @@ def test_remote_mcp_sources_are_read_without_an_interactive_oauth_prompt(]+def test_remote_mcp_authorization_failure_is_the_only_reconnectable_failure(+ tmp_path, monkeypatch+):+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")+ settings.connection_store.ensure("remote", "alpaca-live-sdk-readonly", "Remote")+ settings.save(+ {+ "display_currency": "USD",+ "sources": [+ {"connection_id": "remote", "label": "Remote", "order": 0}+ ],+ }+ )+ remote = TradingProfile(+ id="alpaca-live-sdk-readonly",+ connector="examplebroker",+ label="Example remote MCP",+ environment="live",+ transport="remote_mcp",+ capabilities=("account.read", "positions.read"),+ readonly=True,+ )+ monkeypatch.setattr(portfolio_service, "profile_by_id", lambda _: remote)++ service = PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=settings,+ get_account=lambda *args, **kwargs: {+ "status": "not_authorized",+ "error": "OAuth authorization required",+ },+ get_positions=lambda *args, **kwargs: {"positions": []},+ get_quote=lambda *args, **kwargs: {},+ fx_fetcher=lambda: (+ Decimal("7.2"),+ Decimal("7.8"),+ "2026-08-09T00:00:00+00:00",+ ),+ )++ snapshot = service.refresh()+ account = snapshot["accounts"][0]++ assert account["status"] == "error"+ assert account["failure_kind"] == "authorization"+ assert account["reconnect_required"] is True++def test_analysis_context_supplies_risk_xray_arguments(tmp_path):"""The portfolio feeds the existing risk x-ray; it does not reimplement it."""accounts = {diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 75a9fd3bd..122f7b5e4 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -1477,6 +1477,7 @@"errorLoad": "تعذّر عرض المحفظة","errorRefresh": "فشل التحديث","errorReconnect": "فشلت إعادة ربط الحساب",+ "errorReconnectTimeout": "انتهت مهلة تفويض المتصفح. أعد الاتصال وأكمل تفويض الوسيط سريعًا.","errorSaveSettings": "تعذّر حفظ إعدادات المحفظة","errorExport": "فشل التصدير"},@@ -1507,7 +1508,8 @@"failed": "تعذّرت قراءته — غير محتسب في الإجمالي","lastSuccess": "آخر قراءة ناجحة {{time}}","noSuccess": "لا توجد قراءة ناجحة بعد",- "reconnect": "إعادة الاتصال"+ "reconnect": "إعادة الاتصال",+ "retryRead": "إعادة محاولة القراءة"},"holdings": {"title": "تفاصيل الحيازات",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex 58fa97229..82f71e54b 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -1477,6 +1477,7 @@"errorLoad": "Portfolio nicht verfügbar","errorRefresh": "Aktualisierung fehlgeschlagen","errorReconnect": "Erneutes Verbinden des Kontos fehlgeschlagen",+ "errorReconnectTimeout": "Die Browser-Autorisierung ist abgelaufen. Verbinden Sie sich erneut und schließen Sie die Broker-Autorisierung zeitnah ab.","errorSaveSettings": "Portfolio-Einstellungen konnten nicht gespeichert werden","errorExport": "Export fehlgeschlagen"},@@ -1507,7 +1508,8 @@"failed": "Konnte nicht gelesen werden — nicht in der Summe enthalten","lastSuccess": "Letzter erfolgreicher Abruf {{time}}","noSuccess": "Noch kein erfolgreicher Abruf",- "reconnect": "Neu verbinden"+ "reconnect": "Neu verbinden",+ "retryRead": "Lesen wiederholen"},"holdings": {"title": "Positionen",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 8a7e5d57a..37588fdaa 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -1477,6 +1477,7 @@"errorLoad": "Portfolio unavailable","errorRefresh": "Refresh failed","errorReconnect": "Account reconnect failed",+ "errorReconnectTimeout": "Browser authorization timed out. Reconnect and complete the broker authorization promptly.","errorSaveSettings": "Unable to save portfolio settings","errorExport": "Export failed"},@@ -1507,7 +1508,8 @@"failed": "Could not be read — not counted in the total","lastSuccess": "Last successful read {{time}}","noSuccess": "No successful read yet",- "reconnect": "Reconnect"+ "reconnect": "Reconnect",+ "retryRead": "Retry read"},"holdings": {"title": "Holdings",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex eff7195a1..c41df0903 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -1477,6 +1477,7 @@"errorLoad": "Cartera no disponible","errorRefresh": "Fallo al actualizar","errorReconnect": "No se pudo volver a conectar la cuenta",+ "errorReconnectTimeout": "La autorización del navegador agotó el tiempo. Vuelve a conectar y completa pronto la autorización del bróker.","errorSaveSettings": "No se pudieron guardar los ajustes de la cartera","errorExport": "Fallo al exportar"},@@ -1507,7 +1508,8 @@"failed": "No se pudo leer: no cuenta en el total","lastSuccess": "Última lectura correcta {{time}}","noSuccess": "Todavía sin ninguna lectura correcta",- "reconnect": "Volver a conectar"+ "reconnect": "Volver a conectar",+ "retryRead": "Reintentar lectura"},"holdings": {"title": "Posiciones",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 32b96df63..a7f15cb49 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -1477,6 +1477,7 @@"errorLoad": "ポートフォリオを取得できません","errorRefresh": "更新に失敗しました","errorReconnect": "口座の再接続に失敗しました",+ "errorReconnectTimeout": "ブラウザー認証がタイムアウトしました。再接続し、ブローカー認証を速やかに完了してください。","errorSaveSettings": "ポートフォリオ設定を保存できません","errorExport": "書き出しに失敗しました"},@@ -1507,7 +1508,8 @@"failed": "読み取れませんでした — 合計に含まれていません","lastSuccess": "最後に読み取れたのは {{time}}","noSuccess": "まだ一度も読み取れていません",- "reconnect": "再接続"+ "reconnect": "再接続",+ "retryRead": "再読み込み"},"holdings": {"title": "保有明細",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 37d0ea707..4f00520f8 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -1477,6 +1477,7 @@"errorLoad": "포트폴리오를 불러올 수 없습니다","errorRefresh": "새로고침에 실패했습니다","errorReconnect": "계좌 재연결에 실패했습니다",+ "errorReconnectTimeout": "브라우저 인증 시간이 초과되었습니다. 다시 연결하고 브로커 인증을 신속히 완료하세요.","errorSaveSettings": "포트폴리오 설정을 저장할 수 없습니다","errorExport": "내보내기에 실패했습니다"},@@ -1507,7 +1508,8 @@"failed": "읽지 못했습니다 — 합계에 포함되지 않음","lastSuccess": "마지막으로 성공한 읽기 {{time}}","noSuccess": "아직 성공한 읽기가 없습니다",- "reconnect": "다시 연결"+ "reconnect": "다시 연결",+ "retryRead": "다시 읽기"},"holdings": {"title": "보유 내역",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 41033eb10..03f9c2074 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -1477,6 +1477,7 @@"errorLoad": "无法读取持仓","errorRefresh": "刷新失败","errorReconnect": "账户重新连接失败",+ "errorReconnectTimeout": "等待浏览器授权超时,请重新连接并及时完成券商授权","errorSaveSettings": "无法保存持仓设置","errorExport": "导出失败"},@@ -1507,7 +1508,8 @@"failed": "读取失败 — 未计入合计","lastSuccess": "上一次成功读取于 {{time}}","noSuccess": "尚未成功读取过",- "reconnect": "重新连接"+ "reconnect": "重新连接",+ "retryRead": "重试读取"},"holdings": {"title": "持仓明细",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 70b163651..ddc3ab0e0 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -109,6 +109,8 @@ export interface PortfolioAccount {unpriced_position_count?: number;error_code?: string;error?: string;+ failure_kind?: "authorization" | "transient";+ reconnect_required?: boolean;auth?: {method: string;renewal: "automatic" | "session" | "provider_managed";diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsxindex da4164e46..539748e18 100644--- a/frontend/src/pages/Portfolio.tsx+++ b/frontend/src/pages/Portfolio.tsx@@ -41,6 +41,10 @@ const HOLDING_COLORS = ["#2d9cdb", "#d96c9d", "#7f8c8d", "#b5c83b", "#f05a47",];+// Backend OAuth workers time out after 330 seconds. Keep a slightly longer+// client-side guard so a lost polling response can never spin forever.+const PORTFOLIO_RECONNECT_DEADLINE_MS = 360_000;+/*** Locale used by every Intl formatter on this page. The formatters live at* module scope (chart option builders need them outside React), so they read@@ -189,8 +193,12 @@ export function Portfolio() {setError(null);try {await api.reconnectPortfolioSource(sourceId);+ const deadline = Date.now() + PORTFOLIO_RECONNECT_DEADLINE_MS;for (;;) {await new Promise((resolve) => window.setTimeout(resolve, 1_000));+ if (Date.now() >= deadline) {+ throw new Error(t("portfolio.page.errorReconnectTimeout"));+ }const result = await api.getPortfolioReconnectStatus();if (result.reconnect.running) continue;if (result.reconnect.status !== "authorized") {@@ -400,7 +408,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={reconnectingSource === account.source_id} reconnectDisabled={reconnectingSource !== null} />+ <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.reconnect_required && account.source_id ? () => void reconnectSource(account.source_id!) : undefined} onRetry={!account.reconnect_required ? () => void refresh() : undefined} busy={refreshing || reconnectingSource === (account.source_id ?? account.broker)} actionsDisabled={refreshing || reconnectingSource !== null} />))}</div></section>@@ -499,7 +507,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, reconnectDisabled }: { account: PortfolioAccount; active: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; reconnecting: boolean; reconnectDisabled: boolean }) {+function AccountCard({ account, active, displayCurrency, onClick, onReconnect, onRetry, busy, actionsDisabled }: { account: PortfolioAccount; active: boolean; displayCurrency: "USD" | "CNY"; onClick: () => void; onReconnect?: () => void; onRetry?: () => void; busy: boolean; actionsDisabled: 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"}`}>@@ -520,7 +528,8 @@ 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={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}+ {failed && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={actionsDisabled} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{busy ? <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 && onRetry ? <button onClick={(event) => { event.stopPropagation(); onRetry(); }} disabled={actionsDisabled} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{t("portfolio.accounts.retryRead")}</button> : null}</div>;}diff --git a/frontend/src/pages/__tests__/Portfolio.test.tsx b/frontend/src/pages/__tests__/Portfolio.test.tsxindex d39d31cb7..6e1936de1 100644--- a/frontend/src/pages/__tests__/Portfolio.test.tsx+++ b/frontend/src/pages/__tests__/Portfolio.test.tsx@@ -82,6 +82,8 @@ const snapshotWithFailedSource = {status: "error" as const,error_code: "ConnectionError",error: "Read timed out after 30s",+ failure_kind: "transient" as const,+ reconnect_required: false,last_success_at: FAILED_LAST_SUCCESS,},],@@ -99,6 +101,8 @@ const snapshotWithFailedOAuth = {status: "error" as const,error_code: "AuthenticationError",error: "OAuth authorization expired",+ failure_kind: "authorization" as const,+ reconnect_required: true,auth: {method: "OAuth",renewal: "automatic" as const,@@ -273,5 +277,36 @@ describe("Portfolio page", () => {expect(screen.getByText("$1,000.00")).toBeInTheDocument();expect(screen.getByText(i18n.t("portfolio.metrics.excluded", { count: 1 }))).toBeInTheDocument();expect(screen.getByText(snapshotWithFailedSource.warnings[0])).toBeInTheDocument();+ expect(screen.getByRole("button", { name: i18n.t("portfolio.accounts.retryRead") })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: i18n.t("portfolio.accounts.reconnect") })).not.toBeInTheDocument();+ });++ it("offers reconnect only when an OAuth source explicitly needs authorization", async () => {+ mocked.getPortfolio.mockResolvedValue({+ status: "ok",+ snapshot: {+ ...snapshotWithFailedSource,+ accounts: [+ ...snapshot.accounts,+ {+ source_id: "ibkr-auth",+ broker: "ibkr",+ label: "IBKR authorization",+ status: "error" as const,+ error: "OAuth authorization required",+ failure_kind: "authorization" as const,+ reconnect_required: true,+ auth: { method: "OAuth", renewal: "automatic" as const, readonly: true, detail: "" },+ },+ ],+ },+ });+ render(<Portfolio />);+ expect((await screen.findAllByText("IBKR authorization")).length).toBeGreaterThan(0);++ fireEvent.click(screen.getByRole("button", { name: i18n.t("portfolio.accounts.reconnect") }));++ await waitFor(() => expect(mocked.reconnectPortfolioSource).toHaveBeenCalledWith("ibkr-auth"));+ expect(screen.queryByRole("button", { name: i18n.t("portfolio.accounts.retryRead") })).not.toBeInTheDocument();});});