"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(robinhood): read-only portfolio source and account-bound live trading (#1428, #1442)
Haozhe Wu1b888f8c3fff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8ca6fc383..ecde2fb9f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,21 @@ This project adheres to [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **A Robinhood account can be a read-only portfolio source** (#1428). The new+ `robinhood-live-mcp-readonly` profile uses the same MCP server and OAuth+ grant as the trading profile. Its connection reads exactly one account,+ picked from Robinhood's own `get_accounts` list in the connection center or+ with `vibe-trading connector select-account <id>`. Nothing is preselected,+ and a source with no account errors before any broker call. Holdings come+ from `get_portfolio` and `get_equity_positions` and are mapped only from the+ shapes the reporter posted. A second page of positions, a null list or item,+ or an unknown field is an error, not a shorter account. Positions show+ quantity and cost but no price until the quote reply is mapped. An account+ that also holds options, crypto, futures, event contracts, mutual funds or+ fixed income fails the source instead of showing an equity-only view.+### Changed- **The final-answer grounding gate no longer guesses what a number is from the@@ -61,6 +76,22 @@ This project adheres to [Semantic Versioning](https://semver.org/).### Fixed+- **Robinhood live trading reads and trades the account the mandate names**+ (#1442). The runner, the pre-trade gate and the commit-time ceiling fetch+ called Robinhood with no `account_number`, and read replies one level too+ shallow (`data.positions` where Robinhood nests `data.data.positions`). So+ every reconciliation aborted, and the gate refused every order because it+ could not read positions. The tests stayed green only because their fake+ replies had a shape Robinhood never sends. A Robinhood mandate is now bound+ at commit to one account from `get_accounts`: listed, not deactivated, and+ open to agentic trading. The Web confirm dialog and the CLI both ask for+ it, and never take it from the agent-written proposal. Every runner and gate+ call sends that account, and an order naming another account is refused.+ Held positions, which Robinhood reports without a price, are priced the way+ a quantity order already was, and one that cannot be priced fails the+ exposure check closed. Existing Robinhood mandates must be committed again+ with an account.+- **Plain integers in prose are not price claims.** A list number ("输出原则4"), a window length or a count was checked like a quoted price and could becut from a released answer.diff --git a/README.md b/README.mdindex 75690369b..495ece778 100644--- a/README.md+++ b/README.md@@ -388,7 +388,7 @@ Broker-reported source currencies are preserved during valuation: HKD account to| **Contract-tested** | Recorded connector-shaped fixtures pass the common account/position contract, but this is not a promise that every broker account variant has been live-tested. || **Experimental** | The profile is structurally read-only and can be selected, but its currencies, account totals, or instrument semantics still need broker-specific verification. |-Every position row must provide a symbol and quantity. Unsupported currencies fail the source explicitly instead of being silently treated as USD. The current valuation core supports USD, HKD and CNY; IBKR, Longbridge and Binance use native handling, while Alpaca and OKX have common-contract coverage. OKX account balance details are adapted into spot holdings alongside any open positions. A new built-in connector or local plugin defaults to **Experimental** until its portfolio contract fixtures are added.+Every position row must provide a symbol and quantity. Unsupported currencies fail the source explicitly instead of being silently treated as USD. The current valuation core supports USD, HKD and CNY; IBKR, Longbridge and Binance use native handling, while Alpaca and OKX have common-contract coverage. OKX account balance details are adapted into spot holdings alongside any open positions. Robinhood reads the one account you pick from the broker's own list (`vibe-trading connector select-account <id>` or the connection center) and never falls back to a default account; its equity positions are listed unpriced until the quote reply is mapped, and an account that also holds options, crypto, futures, event contracts, mutual funds or fixed income fails the source instead of showing an equity-only view. A new built-in connector or local plugin defaults to **Experimental** until its portfolio contract fixtures are added.### AI-friendly connector onboardingdiff --git a/README_ar.md b/README_ar.mdindex de71202ff..f53352c46 100644--- a/README_ar.md+++ b/README_ar.md@@ -370,7 +370,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an## 💼 محفظة محلية متعددة الوسطاء-تضيف واجهة الويب صفحة **المحفظة** للقراءة فقط، وهي تجمّع مراكزك عبر اتصالات الوسطاء التي تختارها. المصادر هي نسخ اتصال من ملفات تعريف للقراءة فقط تعلن `account.read` و`positions.read` — تُضبط من **موصّلات الوسطاء** في [القدرات التفصيلية](#-القدرات-التفصيلية). أما ملف تعريف IBKR الرسمي عبر MCP فلا يصلح مصدراً بعد.+تضيف واجهة الويب صفحة **المحفظة** للقراءة فقط، وهي تجمّع مراكزك عبر اتصالات الوسطاء التي تختارها. المصادر هي نسخ اتصال من ملفات تعريف للقراءة فقط تعلن `account.read` و`positions.read` — تُضبط من **موصّلات الوسطاء** في [القدرات التفصيلية](#-القدرات-التفصيلية). أما ملف تعريف IBKR الرسمي عبر MCP فلا يصلح مصدراً بعد. يقرأ Robinhood الحساب الوحيد الذي تختاره من قائمة حسابات الوسيط نفسه (`vibe-trading connector select-account <id>` أو مركز الاتصالات) ولا يرجع أبدًا إلى حساب افتراضي؛ تُعرض مراكز الأسهم بلا تسعير إلى أن يُربط رد الأسعار، والحساب الذي يحتفظ أيضًا بخيارات أو عملات مشفرة أو عقود آجلة أو عقود أحداث أو صناديق استثمار مشتركة أو دخل ثابت يُعلَّم مصدره كخطأ بدل عرض الأسهم وحدها.| السلوك | ما تحصل عليه ||--------|--------------|diff --git a/README_es.md b/README_es.mdindex ad2c52ef2..ab6ca45ea 100644--- a/README_es.md+++ b/README_es.md@@ -369,7 +369,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an## 💼 Cartera Local Multi-Broker-La Web UI añade una página **Cartera** de solo lectura que agrega las posiciones de las conexiones de broker que elijas. Las fuentes son instancias de conexión de perfiles de solo lectura que declaran `account.read` y `positions.read` — configúralas en **Conectores de Broker** dentro de [Detailed Capabilities](#-detailed-capabilities). El perfil MCP oficial de IBKR aún no puede usarse como fuente.+La Web UI añade una página **Cartera** de solo lectura que agrega las posiciones de las conexiones de broker que elijas. Las fuentes son instancias de conexión de perfiles de solo lectura que declaran `account.read` y `positions.read` — configúralas en **Conectores de Broker** dentro de [Detailed Capabilities](#-detailed-capabilities). El perfil MCP oficial de IBKR aún no puede usarse como fuente. Robinhood lee solo la cuenta que eliges de la propia lista del bróker (`vibe-trading connector select-account <id>` o el centro de conexiones) y nunca recurre a una cuenta predeterminada; sus posiciones en acciones se muestran sin precio hasta que se mapee la respuesta de cotizaciones, y una cuenta que además tenga opciones, cripto, futuros, contratos de eventos, fondos mutuos o renta fija marca la fuente como error en lugar de mostrar solo las acciones.| Comportamiento | Qué obtienes ||----------------|--------------|diff --git a/README_ja.md b/README_ja.mdindex 84b58da89..83e1a26b9 100644--- a/README_ja.md+++ b/README_ja.md@@ -370,7 +370,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an## 💼 ローカル・マルチブローカー Portfolio-Web UI に、選んだブローカー接続の保有を横断してまとめる読み取り専用の **Portfolio** ページが加わりました。データソースは `account.read` と `positions.read` を宣言する読み取り専用 profile の接続インスタンスで、[詳細な機能](#-詳細な機能) の **ブローカー connectors** で設定します。IBKR の公式 MCP profile はまだデータソースとして使えません。+Web UI に、選んだブローカー接続の保有を横断してまとめる読み取り専用の **Portfolio** ページが加わりました。データソースは `account.read` と `positions.read` を宣言する読み取り専用 profile の接続インスタンスで、[詳細な機能](#-詳細な機能) の **ブローカー connectors** で設定します。IBKR の公式 MCP profile はまだデータソースとして使えません。 Robinhood はブローカー自身の口座一覧から選んだ 1 口座だけを読み取り(`vibe-trading connector select-account <id>` または接続センター)、既定の口座にフォールバックしません。株式ポジションは気配値の対応付けが済むまで評価額なしで表示され、オプション・暗号資産・先物・イベント契約・投資信託・債券も保有する口座は、株式だけの表示ではなくソースのエラーになります。| 挙動 | 得られるもの ||------|--------------|diff --git a/README_ko.md b/README_ko.mdindex 57d2e7f5b..a5952f124 100644--- a/README_ko.md+++ b/README_ko.md@@ -370,7 +370,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an## 💼 로컬 멀티 브로커 포트폴리오-Web UI에 선택한 브로커 연결의 보유 종목을 한데 모아 보여주는 읽기 전용 **포트폴리오** 페이지가 추가됐습니다. 소스는 `account.read`와 `positions.read`를 선언한 읽기 전용 profile의 연결 인스턴스이며, [상세 기능](#-상세-기능)의 **브로커 커넥터**에서 설정합니다. IBKR 공식 MCP profile은 아직 소스로 사용할 수 없습니다.+Web UI에 선택한 브로커 연결의 보유 종목을 한데 모아 보여주는 읽기 전용 **포트폴리오** 페이지가 추가됐습니다. 소스는 `account.read`와 `positions.read`를 선언한 읽기 전용 profile의 연결 인스턴스이며, [상세 기능](#-상세-기능)의 **브로커 커넥터**에서 설정합니다. IBKR 공식 MCP profile은 아직 소스로 사용할 수 없습니다. Robinhood는 브로커의 계좌 목록에서 직접 고른 계좌 하나만 읽으며(`vibe-trading connector select-account <id>` 또는 연결 센터) 기본 계좌로 대체하지 않습니다. 주식 포지션은 시세 응답이 매핑될 때까지 평가액 없이 표시되고, 옵션·암호화폐·선물·이벤트 계약·뮤추얼 펀드·채권을 함께 보유한 계좌는 주식만 보여주는 대신 소스 오류로 처리됩니다.| 동작 | 제공되는 것 ||------|-------------|diff --git a/README_zh.md b/README_zh.mdindex 9d7d5c49d..8f7522e8e 100644--- a/README_zh.md+++ b/README_zh.md@@ -369,7 +369,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an## 💼 本地多账户持仓-Web UI 新增只读的 **持仓** 页面,把你选中的券商连接的持仓汇总到一起。数据源是声明了 `account.read` 与 `positions.read` 的只读 profile 的连接实例——在 [Detailed Capabilities](#-detailed-capabilities) 的 **Broker Connectors** 中配置。IBKR 官方 MCP profile 暂时还不能作为数据源。+Web UI 新增只读的 **持仓** 页面,把你选中的券商连接的持仓汇总到一起。数据源是声明了 `account.read` 与 `positions.read` 的只读 profile 的连接实例——在 [Detailed Capabilities](#-detailed-capabilities) 的 **Broker Connectors** 中配置。IBKR 官方 MCP profile 暂时还不能作为数据源。 Robinhood 只读取你从券商账户列表中选定的那一个账户(`vibe-trading connector select-account <id>` 或连接中心),不会回退到默认账户;其股票持仓在报价映射完成前不计价,而同时持有期权、加密货币、期货、事件合约、共同基金或固定收益的账户会被标记为读取失败,而不是只显示股票部分。| 行为 | 你得到什么 ||------|------------|diff --git a/agent/api_server.py b/agent/api_server.pyindex 220649eb2..bb6757d7d 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -277,6 +277,8 @@ from src.api.live_routes import ( # noqa: F401, E402_runner_factory,_emit_live_event,_fetch_broker_ceilings,+ _live_account_choices,+ _mandate_account_ref,_known_live_brokers,_oauth_token_present,_active_mandate_state,diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex c0befd8b1..f52167a1a 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -4264,9 +4264,18 @@ def cmd_portfolio_sources(service: Any | None = None) -> int:table.add_column("Transport")table.add_column("Credentials", justify="center")for row in rows:+ connection_cell = (+ f"[cyan]{rich_escape(str(row.get('connection_id') or row.get('id')))}[/cyan]"+ f"\n[dim]{rich_escape(str(row.get('label') or ''))}[/dim]"+ )+ account_ref = str(row.get("account_ref") or "")+ if account_ref:+ connection_cell += f"\n[dim]account ····{rich_escape(account_ref[-4:])}[/dim]"+ elif row.get("account_selection_required"):+ connection_cell += "\n[yellow]no account selected[/yellow]"table.add_row("[green]*[/green]" if row.get("selected") else "",- f"[cyan]{rich_escape(str(row.get('connection_id') or row.get('id')))}[/cyan]\n[dim]{rich_escape(str(row.get('label') or ''))}[/dim]",+ connection_cell,rich_escape(str(row.get("connector") or "")),rich_escape(str(row.get("environment") or "")),rich_escape(str(row.get("transport") or "")),@@ -4455,12 +4464,27 @@ def cmd_connector_setup(connection_id: str | None = None,label: str | None = None,skip_check: bool = False,+ account: str | None = None,) -> int:- """Create a local read-only connection and collect secrets outside AI prompts."""+ """Create a local read-only connection and collect secrets outside AI prompts.++ Args:+ profile_id: Read-only portfolio profile to connect through.+ connection_id: Local id; defaults to ``<connector>-<environment>``.+ label: Display name; defaults to the profile label.+ skip_check: Skip the connectivity check (and, for an account-scoped+ profile, the account selection that needs the broker).+ account: Account to scope an account-scoped connection to; without it+ the user picks from the broker's account list.++ Returns:+ The process exit code.+ """from src.trading.connections import (ConnectionStore,credential_field_catalog,is_portfolio_connection_profile,+ requires_account_selection,)from src.trading.profiles import profile_by_idfrom src.trading.service import check_connection@@ -4504,7 +4528,13 @@ def cmd_connector_setup(f"[green]Local read-only connection ready[/green] "f"{connection.id} [dim]({connection.profile_id})[/dim]")+ needs_account = requires_account_selection(profile)if skip_check:+ if needs_account and not connection.account_ref:+ console.print(+ f"[yellow]Select the account this connection reads:[/yellow] "+ f"vibe-trading connector select-account {connection.id}"+ )return EXIT_SUCCESStry:report = check_connection(profile.id, connection_id=connection.id)@@ -4518,6 +4548,69 @@ def cmd_connector_setup()return EXIT_RUN_FAILEDconsole.print("[green]Connection test passed.[/green]")+ if needs_account and (account is not None or not connection.account_ref):+ return cmd_connector_select_account(connection.id, account=account)+ return EXIT_SUCCESS+++def cmd_connector_select_account(+ connection_id: str,+ *,+ account: str | None = None,+ clear: bool = False,+) -> int:+ """Scope an account-scoped connection to one account from the broker's list.++ There is no default: without ``account`` the user picks from the list, and+ an account the broker does not list is refused.++ Args:+ connection_id: Connection to update.+ account: Account reference to select; prompts when omitted.+ clear: Remove the selection instead.++ Returns:+ The process exit code.+ """+ from src.trading.accounts import AccountListUnavailable, choose_account, connection_accounts+ from src.trading.connections import ConnectionStore++ store = ConnectionStore()+ try:+ connection = store.get(connection_id)+ if clear:+ store.select_account(connection.id, "")+ console.print(f"[green]Cleared the account selection of[/green] {connection.id}")+ return EXIT_SUCCESS+ choices = connection_accounts(connection)+ if account is None:+ usable = [row for row in choices if not row.get("deactivated")]+ if not usable:+ raise ValueError("this login reaches no active account")+ table = Table(title="Accounts", box=box.SIMPLE_HEAVY)+ table.add_column("#", justify="right")+ table.add_column("Account")+ table.add_column("Broker default", justify="center")+ table.add_column("Agentic trading", justify="center")+ for index, row in enumerate(usable, start=1):+ table.add_row(+ str(index),+ rich_escape(str(row.get("label") or "")),+ "yes" if row.get("is_default") else "",+ "allowed" if row.get("agentic_allowed") else "[dim]not allowed[/dim]",+ )+ console.print(table)+ pick = Prompt.ask("Account", choices=[str(index) for index in range(1, len(usable) + 1)])+ account = str(usable[int(pick) - 1]["account_ref"])+ chosen = choose_account(choices, account.strip())+ store.select_account(connection.id, str(chosen["account_ref"]))+ except AccountListUnavailable as exc:+ console.print(f"[red]Could not read the account list:[/red] {rich_escape(str(exc))}")+ return EXIT_RUN_FAILED+ except (RuntimeError, ValueError) as exc:+ console.print(f"[red]Account selection failed:[/red] {rich_escape(str(exc))}")+ return EXIT_USAGE_ERROR+ console.print(f"[green]{connection.id} now reads[/green] {rich_escape(str(chosen.get('label') or ''))}")return EXIT_SUCCESS@@ -5120,6 +5213,13 @@ def _dispatch_connector(args: argparse.Namespace) -> int:connection_id=args.connection_id,label=args.label,skip_check=args.skip_check,+ account=args.account,+ )+ if sub == "select-account":+ return cmd_connector_select_account(+ args.connection_id,+ account=args.account,+ clear=args.clear,)if sub == "check":options = {@@ -5438,6 +5538,19 @@ def _build_parser() -> argparse.ArgumentParser:connector_setup.add_argument("--connection-id", default=None)connector_setup.add_argument("--label", default=None)connector_setup.add_argument("--skip-check", action="store_true")+ connector_setup.add_argument(+ "--account",+ default=None,+ help="Account to scope an account-scoped connection (Robinhood) to; prompts when omitted",+ )++ connector_select_account = connector_subparsers.add_parser(+ "select-account",+ help="Choose the broker account an account-scoped connection reads",+ )+ connector_select_account.add_argument("connection_id", help="Local connection id")+ connector_select_account.add_argument("--account", default=None, help="Account reference; prompts when omitted")+ connector_select_account.add_argument("--clear", action="store_true", help="Remove the selection")connector_check = connector_subparsers.add_parser("check", help="Check selected connector readiness")_add_connector_profile_arg(connector_check)diff --git a/agent/cli/main.py b/agent/cli/main.pyindex 6d5bc0cb1..3c4fae044 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -1126,7 +1126,43 @@ def _handle_scheduled_proposal_reply(text: str, ctx: InteractiveContext) -> boolreturn True-def _commit_mandate(proposal: Dict[str, Any], selected_ordinal: int) -> Dict[str, Any]:+def _choose_mandate_account(accounts: List[Dict[str, Any]]) -> str:+ """Ask the user which broker account a mandate may trade.++ Only accounts the broker lists as active and open to agentic trading are+ offered, and nothing is preselected: an empty reply commits nothing.++ Args:+ accounts: Picker rows from ``GET /live/accounts``.++ Returns:+ The chosen ``account_ref``, or ``""`` when the user chose none or no+ account is usable.+ """+ console = get_console()+ usable = [row for row in accounts if not row.get("deactivated") and row.get("agentic_allowed")]+ if not usable:+ console.print("[yellow]The broker lists no active account that allows agentic trading.[/yellow]")+ return ""+ console.print("[bold]Which account may this mandate trade?[/bold]")+ for index, row in enumerate(usable, start=1):+ default = " [dim](broker default)[/dim]" if row.get("is_default") else ""+ console.print(f" [{index}] {row.get('label')}{default}")+ try:+ raw = input("account > ").strip()+ except (EOFError, KeyboardInterrupt):+ return ""+ if not raw.isdigit() or not 1 <= int(raw) <= len(usable):+ return ""+ return str(usable[int(raw) - 1]["account_ref"])+++def _commit_mandate(+ proposal: Dict[str, Any],+ selected_ordinal: int,+ *,+ choose_account: Any = None,+) -> Dict[str, Any]:"""Commit a mandate selection via the surface commit endpoint.This is the single privileged write that activates a mandate. The pick is a@@ -1142,6 +1178,10 @@ def _commit_mandate(proposal: Dict[str, Any], selected_ordinal: int) -> Dict[strproposal: The outstanding ``mandate.proposal`` payload (binds the committo the exact rendered options via ``proposal_id``).selected_ordinal: The 1-based profile the user picked.+ choose_account: Account chooser taking the ``/live/accounts`` rows;+ defaults to :func:`_choose_mandate_account`. Used only for a broker+ whose mandate must be bound to one account, and never fed an+ account the proposal carries: the agent does not choose it.Returns:The decoded commit response (``mandate_id`` / ``consent_record_id`` on@@ -1171,6 +1211,20 @@ def _commit_mandate(proposal: Dict[str, Any], selected_ordinal: int) -> Dict[str}).model_dump(mode="json")+ listing = httpx.get(+ f"{base}/live/accounts",+ params={"broker": body["broker"]},+ headers=headers,+ timeout=30.0,+ )+ listing.raise_for_status()+ accounts = listing.json()+ if accounts.get("account_selection_required"):+ chooser = choose_account or _choose_mandate_account+ body["account_ref"] = chooser(list(accounts.get("accounts") or []))+ if not body["account_ref"]:+ return {"status": "error", "error": "no account was chosen for this mandate"}+response = httpx.post(f"{base}/mandate/commit",json=body,diff --git a/agent/src/api/connection_routes.py b/agent/src/api/connection_routes.pyindex 3345a0357..866be20af 100644--- a/agent/src/api/connection_routes.py+++ b/agent/src/api/connection_routes.py@@ -2,15 +2,17 @@from __future__ import annotations+from dataclasses import replace+from fastapi import Depends, FastAPI, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom src.api.security import require_auth, require_settings_write_authfrom src.portfolio.compatibility import profile_compatibilityfrom src.portfolio.config import PortfolioSettingsStore+from src.trading.accounts import AccountListUnavailable, choose_account, connection_accountsfrom src.trading.connections import (ConnectionStore,- TradingConnection,credential_fields,readonly_profile_catalog,)@@ -27,6 +29,12 @@ class ConnectionRequest(BaseModel):label: str = Field(min_length=1, max_length=80)+class AccountSelectionRequest(BaseModel):+ """Payload selecting the broker account a connection reads; empty clears it."""++ account_ref: str = Field("", max_length=128)++class CredentialRequest(BaseModel):"""Payload carrying credential values for one connection instance."""@@ -100,19 +108,52 @@ def register_connection_routes(app: FastAPI) -> None:current = instance.get(connection_id)if payload.profile_id.strip().lower() != current.profile_id:raise ValueError("connection profile cannot be changed")- updated = instance.save(- TradingConnection(- id=current.id,- profile_id=current.profile_id,- label=payload.label,- credential_ref=current.credential_ref,- created_at=current.created_at,- )- )+ # replace() keeps every field the rename does not name, including+ # the selected account.+ updated = instance.save(replace(current, label=payload.label))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)],+ )+ def list_connection_accounts(connection_id: str):+ """List the broker accounts a connection's login can reach."""+ try:+ connection = store().get(connection_id)+ accounts = connection_accounts(connection)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except AccountListUnavailable as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ return {+ "status": "ok",+ "connection_id": connection.id,+ "account_ref": connection.account_ref,+ "accounts": accounts,+ }++ @app.put(+ "/api/connections/{connection_id}/account",+ dependencies=[Depends(require_settings_write_auth)],+ )+ def select_connection_account(connection_id: str, payload: AccountSelectionRequest):+ """Scope a connection's reads to one account from the broker's own list."""+ account_ref = payload.account_ref.strip()+ try:+ instance = store()+ connection = instance.get(connection_id)+ if account_ref:+ choose_account(connection_accounts(connection), account_ref)+ updated = instance.select_account(connection.id, account_ref)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except AccountListUnavailable as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ return {"status": "ok", "connection": updated.to_dict()}+@app.post("/api/connections/{connection_id}/credentials",dependencies=[Depends(require_settings_write_auth)],diff --git a/agent/src/api/live_routes.py b/agent/src/api/live_routes.pyindex 2353f3122..0b7e066ce 100644--- a/agent/src/api/live_routes.py+++ b/agent/src/api/live_routes.py@@ -12,6 +12,7 @@ These are the privileged SURFACE actions of the live-trading channel- ``POST /live/authorize`` — discover-only OAuth bootstrap on-ramp (C2)- ``POST /live/runner/start`` — start the persistent §7.5 runner- ``POST /live/runner/stop`` — stop the persistent §7.5 runner+- ``GET /live/accounts`` — the broker accounts a mandate can be bound toEach best-effort relays a ``mandate.committed`` / ``live.halted`` / ``live.action``event through the EXISTING session EventBus, so the frontend's already-wired@@ -382,11 +383,40 @@ def _live_broker_adapter(broker: str) -> Any:raise LiveRunnerUnavailable(f"no MCP server configured for live broker {broker!r}")-def _fetch_broker_ceilings(broker: str) -> Optional[Dict[str, Any]]:+def _mandate_account_ref(broker: str) -> str:+ """Return the account the broker's committed mandate is bound to, or ``""``."""+ from src.live.mandate.store import load_mandate++ mandate = load_mandate(broker)+ return mandate.consent.account_ref.strip() if mandate is not None else ""+++def _live_account_choices(broker: str) -> List[Dict[str, Any]]:+ """Read the accounts a live broker's login can reach, as picker rows.++ Raises:+ LiveRunnerUnavailable: When the broker channel is not configured.+ ValueError: When the broker lists no accounts, the read failed, or the+ reply could not be mapped.+ """+ from src.trading.service import runner_account_choices, runner_tool_name++ accounts_tool = runner_tool_name(broker, "accounts")+ if accounts_tool is None:+ raise ValueError(f"{broker} does not list accounts")+ adapter = _host()._live_broker_adapter(broker)+ choices = runner_account_choices(broker, adapter.call_tool(accounts_tool, {}))+ if choices is None:+ raise ValueError(f"{broker} does not list accounts")+ return choices+++def _fetch_broker_ceilings(broker: str, account_ref: str = "") -> Optional[Dict[str, Any]]:"""Best-effort fetch of broker-side account ceilings for the commit re-check.- Returns ``None`` on any failure so the caller falls back to the proposal's- own snapshot — a commit is never blocked on a broker read.+ The read is scoped to the account the mandate is being bound to. Returns+ ``None`` on any failure so the caller falls back to the proposal's own+ snapshot — a commit is never blocked on a broker read."""h = _host()try:@@ -394,16 +424,24 @@ def _fetch_broker_ceilings(broker: str) -> Optional[Dict[str, Any]]:except LiveRunnerUnavailable:return Nonetry:- from src.trading.service import runner_tool_name+ from src.trading.service import runner_account_summary, runner_arguments, runner_tool_nameaccount_tool = runner_tool_name(broker, "account") or "get_account"- result = adapter.call_tool(account_tool, {})+ result = adapter.call_tool(account_tool, runner_arguments(broker, "account", account_ref))except Exception: # pragma: no cover - status/commit must never raise herelogger.debug("broker ceiling fetch failed for %s", broker, exc_info=True)return Noneif not isinstance(result, dict) or result.get("status") == "error":return None- payload = result.get("result") if isinstance(result.get("result"), dict) else result+ try:+ summary = runner_account_summary(broker, result)+ except ValueError:+ logger.debug("broker ceiling reply for %s could not be mapped", broker, exc_info=True)+ return None+ if summary is not None:+ payload: Any = summary+ else:+ payload = result.get("result") if isinstance(result.get("result"), dict) else resultfunding: Optional[float] = Nonefor key in ("account_funding_usd", "buying_power", "cash", "portfolio_value", "equity"):raw = payload.get(key) if isinstance(payload, dict) else None@@ -546,7 +584,33 @@ def _build_live_runner(broker: str) -> Any:from src.live.runtime.runner import LiveRunnerfrom src.live.runtime.scheduler import Schedulerfrom src.live.runtime.triggers import Trigger- from src.trading.service import runner_tool_name+ from src.trading.service import (+ runner_account_summary,+ runner_arguments,+ runner_records,+ runner_requires_account,+ runner_tool_name,+ )++ requires_account = runner_requires_account(broker)+ if requires_account and not h._mandate_account_ref(broker):+ raise LiveRunnerUnavailable(+ f"the {broker} mandate is not bound to an account; commit it again with an account"+ )++ def _account() -> str:+ """Resolve the mandate's account on every broker call.++ Re-reading it per call means a mandate re-committed to another account+ is followed at once, and one whose account disappeared stops the+ runner's broker calls instead of falling back to a default account.+ """+ if not requires_account:+ return ""+ account_ref = h._mandate_account_ref(broker)+ if not account_ref:+ raise RuntimeError(f"the {broker} mandate is not bound to an account")+ return account_refdef _tool(operation: str) -> str:remote_tool = runner_tool_name(broker, operation)@@ -565,7 +629,7 @@ def _build_live_runner(broker: str) -> Any:# _live_broker_adapter is monkeypatched on host by testsadapter = h._live_broker_adapter(broker)- def _read(remote_tool: str, record_key: str | None = None):+ def _read(remote_tool: str, operation: str, record_key: str | None = None):"""Wrap adapter.call_tool into a READ callable with a normalized payload.The MCP adapter returns ``{"status": "error", ...}`` envelopes instead@@ -575,17 +639,27 @@ def _build_live_runner(broker: str) -> Any:envelopes: error envelopes raise, success payloads unwrap to ``data``(with the pinned ``record_key`` extracted for positions/orders recordreads, e.g. ``data.positions`` / ``data.orders``). Bare values pass- through unchanged.+ through unchanged. A connector with a mapped reply shape (Robinhood,+ whose records sit under ``data.data``) is unwrapped by that mapping+ instead, and a reply that does not match it raises."""def read() -> Any:- payload = adapter.call_tool(remote_tool, {})+ payload = adapter.call_tool(remote_tool, runner_arguments(broker, operation, _account()))if isinstance(payload, list):return payload # injected/legacy bare response+ if isinstance(payload, dict) and payload.get("status") == "error":+ raise RuntimeError(str(payload.get("error") or "broker read failed"))+ try:+ mapped = (+ runner_records(broker, operation, payload)+ if record_key is not None+ else runner_account_summary(broker, payload)+ )+ except ValueError as exc:+ raise RuntimeError(f"{remote_tool}: {exc}") from exc+ if mapped is not None:+ return mappedif not isinstance(payload, dict) or payload.get("status") != "ok":- if isinstance(payload, dict) and payload.get("status") == "error":- raise RuntimeError(- str(payload.get("error") or "broker read failed")- )return payloaddata = payload.get("data")if record_key is None:@@ -603,9 +677,11 @@ def _build_live_runner(broker: str) -> Any:return readdef _submit(order: Dict[str, Any]) -> Dict[str, Any]:+ # The mandate's account wins over anything the order dict carries.+ bound = {**order, **runner_arguments(broker, "orders", _account())}if order.get("action") == "cancel":- return adapter.call_tool(cancel_order_tool, order)- return adapter.call_tool(submit_order_tool, order)+ return adapter.call_tool(cancel_order_tool, bound)+ return adapter.call_tool(submit_order_tool, bound)svc = h._get_session_service()session = svc.create_session(title=f"live-runner:{broker}")@@ -633,9 +709,9 @@ def _build_live_runner(broker: str) -> Any:broker,agent_caller=_agent_caller,reconcile_fn=reconcile,- read_positions=_read(positions_tool, "positions"),- read_balance=_read(balance_tool),- read_open_orders=_read(open_orders_tool, "orders"),+ read_positions=_read(positions_tool, "positions", "positions"),+ read_balance=_read(balance_tool, "account"),+ read_open_orders=_read(open_orders_tool, "orders", "orders"),submit_fn=_submit,write_audit_fn=_audit_with_bus,scheduler=scheduler,@@ -688,8 +764,33 @@ def register_live_routes(raise HTTPException(status_code=400, detail="consent_ack must be true to commit a mandate")from src.live.mandate.commit import CommitError, commit_mandate+ from src.trading.accounts import choose_account+ from src.trading.service import runner_requires_account++ account_ref = payload.account_ref.strip()+ if runner_requires_account(payload.broker):+ # A live broker whose login reaches several accounts trades only the+ # one the user picked here, checked against the broker's own list.+ if not account_ref:+ raise HTTPException(+ status_code=400,+ detail=f"choose the {payload.broker} account this mandate may trade",+ )+ try:+ choices = _host()._live_account_choices(payload.broker)+ except LiveRunnerUnavailable as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ except (RuntimeError, ValueError) as exc:+ raise HTTPException(+ status_code=503,+ detail=f"the {payload.broker} account list could not be read: {exc}",+ ) from exc+ try:+ choose_account(choices, account_ref, require_agentic=True)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc- broker_ceilings = _host()._fetch_broker_ceilings(payload.broker)+ broker_ceilings = _host()._fetch_broker_ceilings(payload.broker, account_ref)try:result = commit_mandate(@@ -698,7 +799,7 @@ def register_live_routes(adjustments=payload.adjustments,consent_ack=payload.consent_ack,broker=payload.broker,- account_ref=payload.account_ref,+ account_ref=account_ref,session_id=payload.session_id,ceilings_ref=broker_ceilings,lifetime_days=payload.lifetime_days,@@ -716,6 +817,27 @@ def register_live_routes()return result+ @app.get("/live/accounts", dependencies=[Depends(require_auth)])+ async def list_live_accounts_endpoint(broker: str = Query(..., min_length=1, max_length=64)):+ """List the accounts a live broker's login can reach, for binding a mandate."""+ from src.trading.service import runner_requires_account++ key = broker.strip().lower()+ if not runner_requires_account(key):+ return {"status": "ok", "broker": key, "account_selection_required": False, "accounts": []}+ try:+ choices = await asyncio.get_running_loop().run_in_executor(+ None, lambda: _host()._live_account_choices(key)+ )+ except LiveRunnerUnavailable as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from exc+ except (RuntimeError, ValueError) as exc:+ raise HTTPException(+ status_code=503,+ detail=f"the {key} account list could not be read: {exc}",+ ) from exc+ return {"status": "ok", "broker": key, "account_selection_required": True, "accounts": choices}+@app.post("/live/halt", dependencies=[Depends(require_auth)])async def halt_live_endpoint(payload: LiveHaltRequest):"""Trip the live kill switch (privileged surface action, Consent §4)."""diff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.pyindex 0bbd983e4..c7213a58c 100644--- a/agent/src/live/order_guard.py+++ b/agent/src/live/order_guard.py@@ -11,9 +11,13 @@ broker call:1. ``load_mandate`` — no valid mandate / unknown schema version → DENY.2. expiry — past ``consent.expires_at`` → DENY (routes to re-auth).3. ``halt_flag_set`` — kill switch tripped → DENY, NO remote call.-4. ``extract_order_intent`` — unparseable order → DENY.-5. read positions + balance via the broker's READ MCP tools (plain path).-6. ``check_mandate`` — ALLOW (forward via ``super().execute``) / DENY+4. account binding — for a broker whose login reaches several accounts+ (Robinhood), a mandate bound to no account, or an order naming a different+ account, → DENY; otherwise the mandate's account is stamped onto the order.+5. ``extract_order_intent`` — unparseable order → DENY.+6. read positions + balance via the broker's READ MCP tools (plain path),+ scoped to the mandate's account.+7. ``check_mandate`` — ALLOW (forward via ``super().execute``) / DENY(structural: universe|instrument) / PAUSE_FOR_REAUTH (quantitative).The daily ``trade_counter.json`` is incremented only on a confirmed ALLOW whose@@ -61,7 +65,7 @@ from src.live.enforcement import ()from src.live.extractors import get_extractorfrom src.live.halt import halt_flag_set-from src.live.mandate.model import MANDATE_SCHEMA_VERSION, Mandate+from src.live.mandate.model import MANDATE_SCHEMA_VERSION, InstrumentType, Mandatefrom src.live.mandate.store import load_mandatefrom src.live.daily_count import (DailyOrderLockUnavailable,@@ -161,6 +165,19 @@ class LiveOrderGuardTool(MCPRemoteTool):mandate=mandate,)+ account_ref, refusal = self._bind_account(mandate, kwargs)+ if refusal is not None:+ return self._deny(+ reason=refusal,+ checked=["mandate", "expiry", "halt_flag", "account"],+ mandate=mandate,+ )+ if account_ref:+ from src.trading.service import runner_arguments++ kwargs = {key: value for key, value in kwargs.items() if key != "account"}+ kwargs.update(runner_arguments(self.broker, "orders", account_ref))+extractor = get_extractor(self.broker)intent = extractor(self.remote_name, kwargs) if extractor is not None else Noneif intent is None:@@ -181,8 +198,8 @@ class LiveOrderGuardTool(MCPRemoteTool):mandate=mandate,)- positions = self._read_first(self._read_tools("positions", _POSITIONS_TOOLS))- balance = self._read_first(self._read_tools("account", _BALANCE_TOOLS))+ positions = self._read_first(self._read_tools("positions", _POSITIONS_TOOLS), "positions", account_ref)+ balance = self._read_first(self._read_tools("account", _BALANCE_TOOLS), "account", account_ref)try:with daily_order_lock(self.broker):@@ -277,6 +294,17 @@ class LiveOrderGuardTool(MCPRemoteTool):def _quote_price(self, intent: OrderIntent) -> float | None:"""Return a live USD price for the intent's symbol, fail-closed.+ Args:+ intent: The order intent whose symbol is priced.++ Returns:+ A positive USD price, or ``None`` (→ fail-closed DENY upstream).+ """+ return self._symbol_price(intent.symbol, intent.instrument_type)++ def _symbol_price(self, symbol: str, instrument_type: InstrumentType) -> float | None:+ """Return a live USD price for one symbol, fail-closed.+Prefers the broker's mapped READ quote tool so the price is the broker'sown; falls back to Vibe-Trading's data loaders(:func:`src.live.enforcement.last_price_usd`, standard auto-fallback)@@ -284,21 +312,22 @@ class LiveOrderGuardTool(MCPRemoteTool):yields a usable price.Args:- intent: The order intent whose symbol is priced.+ symbol: Normalized upper-case symbol.+ instrument_type: Instrument type selecting the loader asset class.Returns:- A positive USD price, or ``None`` (→ fail-closed DENY upstream).+ A positive USD price, or ``None``."""- broker_price = self._broker_quote_price(intent.symbol)+ broker_price = self._broker_quote_price(symbol)if broker_price is not None:return broker_price- asset_class = instrument_asset_class(intent.instrument_type)+ asset_class = instrument_asset_class(instrument_type)if asset_class is None:return Nonetry:- return last_price_usd(intent.symbol, asset_class)+ return last_price_usd(symbol, asset_class)except Exception as exc: # loader chain failure → fail-closed- logger.warning("loader quote failed for %s: %s", intent.symbol, exc)+ logger.warning("loader quote failed for %s: %s", symbol, exc)return Nonedef _broker_quote_price(self, symbol: str) -> float | None:@@ -588,30 +617,118 @@ class LiveOrderGuardTool(MCPRemoteTool):# -- read snapshot ------------------------------------------------------- def _read_first(self, candidates: tuple[str, ...]) -> object:+ def _bind_account(self, mandate: Mandate, kwargs: dict) -> tuple[str, str | None]:+ """Resolve the account this order may trade, or the reason it may not.++ A broker whose one login reaches several accounts (Robinhood) trades+ only the account the user bound the mandate to at commit. There is no+ fallback to a default account: an unbound mandate refuses every order,+ and an order naming another account is refused rather than rerouted.++ Args:+ mandate: The loaded, unexpired mandate.+ kwargs: The order-tool arguments from the agent loop.++ Returns:+ ``(account_ref, None)`` when the order may proceed (``account_ref``+ is ``""`` for a broker that takes no account), else+ ``("", reason)``.+ """+ try:+ from src.trading.service import runner_requires_account++ required = runner_requires_account(self.broker)+ except Exception: # pragma: no cover - fail closed on registry failure+ return "", "could not determine whether this broker's orders need an account (fail-closed)"+ if not required:+ return "", None+ bound = mandate.consent.account_ref.strip()+ if not bound:+ return "", "the mandate is not bound to an account — commit it again with an account"+ for key in ("account_number", "account"):+ named = str(kwargs.get(key) or "").strip()+ if named and named != bound:+ return "", "the order names a different account than the one the mandate is bound to"+ return bound, None++ def _read_first(self, candidates: tuple[str, ...], operation: str, account_ref: str = "") -> object:"""Read the first responsive broker read tool, fail-closed.Routes through the plain ``MCPServerAdapter.call_tool`` path (NOT the- guard) so reads are never gated. Returns ``None`` on any error envelope- or exception so the downstream check fail-closes.+ guard) so reads are never gated. The read is scoped to the mandate's+ account. A connector with a mapped reply shape (Robinhood) is unwrapped+ by that mapping, and its position rows, which carry no price, are+ priced through :meth:`_symbol_price`. Returns ``None`` on any error+ envelope, exception, unmappable reply or unpriceable position so the+ downstream check fail-closes.Args:candidates: Ordered remote read-tool names to try.+ operation: ``positions`` or ``account``.+ account_ref: The mandate's account; ``""`` for a broker without one.Returns:- The first successful tool result payload, or ``None``.+ The first successful read, or ``None``."""+ from src.trading.service import runner_account_summary, runner_arguments, runner_records+for remote in candidates:try:- result = self._adapter.call_tool(remote, {}, local_name=remote)+ result = self._adapter.call_tool(+ remote, runner_arguments(self.broker, operation, account_ref), local_name=remote+ )except Exception as exc:logger.warning("live read tool %s failed: %s", remote, exc)continueif isinstance(result, dict) and result.get("status") == "error":continue- return result+ try:+ mapped = (+ runner_records(self.broker, operation, result)+ if operation == "positions"+ else runner_account_summary(self.broker, result)+ )+ except ValueError as exc:+ logger.warning("live read tool %s reply could not be mapped: %s", remote, exc)+ return None+ if mapped is None:+ return result+ if operation == "positions":+ return self._priced_rows(mapped)+ return mappedreturn None+ def _priced_rows(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]] | None:+ """Attach a market value to position rows the broker reports unpriced.++ The exposure check needs each position's value. A row with no price is+ priced the way a quantity order is, and a row that cannot be priced+ makes the whole snapshot unreadable, so exposure fails closed instead+ of counting that position as worth nothing.++ Args:+ rows: Mapped position rows (``symbol``, ``quantity``).++ Returns:+ The rows with ``market_price`` and ``market_value`` set, or ``None``+ when any row cannot be priced.+ """+ priced = []+ for row in rows:+ try:+ quantity = float(row["quantity"])+ except (KeyError, TypeError, ValueError):+ return None+ if quantity == 0:+ priced.append({**row, "market_value": 0.0})+ continue+ price = self._symbol_price(str(row.get("symbol") or ""), InstrumentType.EQUITY)+ if price is None or price != price or price <= 0:+ logger.warning("position %s could not be priced; exposure fails closed", row.get("symbol"))+ return None+ priced.append({**row, "market_price": price, "market_value": abs(quantity) * price})+ return priced+def _read_tools(self, operation: str, fallback: tuple[str, ...]) -> tuple[str, ...]:"""Return connector-specific read tools, falling back to legacy names."""try:diff --git a/agent/src/portfolio/compatibility.py b/agent/src/portfolio/compatibility.pyindex 7dca65697..178ecb96b 100644--- a/agent/src/portfolio/compatibility.py+++ b/agent/src/portfolio/compatibility.py@@ -99,6 +99,12 @@ _CONNECTOR_COMPATIBILITY: dict[str, PortfolioCompatibility] = {"Account totals and instrument quote resolution require verification.",),"toss": PortfolioCompatibility("experimental", 1, "positions", "KRW valuation is not supported yet."),+ "robinhood": PortfolioCompatibility(+ "experimental",+ 1,+ "stocks_etfs",+ "Equity positions for one selected account, unpriced until the quote reply is mapped.",+ ),# No "scalable" entry: its profile does not declare account.read /# positions.read, so it is not a portfolio-eligible connection. The# holdings reply shape is unverified (no published tool argument schemas),@@ -138,8 +144,13 @@ def adapt_and_validate_payloads(if not isinstance(positions_payload, dict):raise PortfolioContractError("positions read must return an object")+ for label, payload in (("account", account_payload), ("positions", positions_payload)):+ if payload.get("mapping_error"):+ raise PortfolioContractError(f"{label} read could not be mapped: {payload['mapping_error']}")account = dict(account_payload)positions = dict(positions_payload)+ if connector == "robinhood":+ _require_equity_only_robinhood_account(account)# No default: a read that never produced a positions list (an unmapped MCP# envelope, a text-only reply) is not an empty portfolio. Reading it as one# would store a complete snapshot of a source that holds nothing.@@ -167,6 +178,39 @@ def adapt_and_validate_payloads(return account, positions+def _require_equity_only_robinhood_account(account_payload: dict[str, Any]) -> None:+ """Refuse a Robinhood account whose holdings reach beyond equities.++ ``get_equity_positions`` lists equities only, while ``get_portfolio`` reports+ options, crypto, futures, event contracts, mutual funds and fixed income as+ separate values. Showing the equity rows for an account that also holds any+ of those would be a quietly shorter portfolio, so the source fails instead,+ naming what it cannot list. An omitted value is unknown, not zero.++ Args:+ account_payload: The mapped ``get_portfolio`` read.++ Raises:+ PortfolioContractError: If the mapped summary is missing, or any+ non-equity value is non-zero or not reported.+ """+ summary = account_payload.get("account")+ values = summary.get("non_equity_values") if isinstance(summary, dict) else None+ if not isinstance(values, dict):+ raise PortfolioContractError("Robinhood account read carries no mapped portfolio summary")+ unreported = sorted(field for field, value in values.items() if value is None)+ held = sorted(field for field, value in values.items() if value is not None and _decimal(value) != 0)+ if unreported:+ raise PortfolioContractError(+ "Robinhood did not report " + ", ".join(unreported) + ", so an equity-only view cannot be shown as complete"+ )+ if held:+ raise PortfolioContractError(+ "this Robinhood account holds " + ", ".join(held) + ", which equity positions do not cover; "+ "an equity-only view would be incomplete"+ )++def ensure_supported_currencies(rows: list[dict[str, Any]], account_payload: dict[str, Any] | None = None) -> None:"""Fail closed when the current portfolio FX model cannot value a source.diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex a53b1cc59..b46483280 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -33,6 +33,7 @@ from src.portfolio.normalization import (value_position,)from src.portfolio.store import PortfolioStore+from src.trading.connections import requires_account_selectionfrom src.trading.profiles import profile_by_idfrom src.trading.types import TradingProfile@@ -782,6 +783,15 @@ class PortfolioService:# A dashboard refresh must never open a browser. reconnect_source()# is the one explicit interactive path.read_options["interactive_oauth"] = False+ if requires_account_selection(profile):+ # Checked before any call: one OAuth grant serves every+ # account, so a read without one must not fall back to the+ # broker's default account.+ if not connection.account_ref:+ raise RuntimeError(+ f"Select a {broker} account for this connection before refreshing"+ )+ read_options["account"] = connection.account_refelif profile.transport in {"broker_sdk", "local_plugin"} and (profile.transport == "local_plugin" or self._use_connection_scoped_reads):@@ -848,6 +858,10 @@ class PortfolioService:)if not price and longbridge_price_error:normalized["price_error"] = longbridge_price_error+ elif profile.transport == "remote_mcp" and "quotes.read" not in profile.capabilities:+ normalized["market_price"] = None+ normalized["price_currency"] = normalized["currency"]+ normalized["price_error"] = f"{broker} quotes are not mapped for this connection"else:quote_symbol = normalized["quote_symbol"]quote = self._get_quote(diff --git a/agent/src/trading/accounts.py b/agent/src/trading/accounts.pynew file mode 100644index 000000000..43d074f34--- /dev/null+++ b/agent/src/trading/accounts.py@@ -0,0 +1,85 @@+"""Broker account listing and selection for account-scoped connections.++One OAuth grant can reach several broker accounts (Robinhood). Portfolio reads+and live trading both name the account explicitly, and both choose it from the+broker's own account list, never from a default or the first row.+"""++from __future__ import annotations++from typing import Any, Callable++from src.trading.connections import TradingConnection, requires_account_selection+from src.trading.profiles import profile_by_id+++class AccountListUnavailable(RuntimeError):+ """The broker's account list could not be read or mapped."""+++def connection_accounts(+ connection: TradingConnection,+ *,+ get_accounts: Callable[..., dict[str, Any]] | None = None,+) -> list[dict[str, Any]]:+ """Read the accounts a connection's login can reach.++ Args:+ connection: A connection whose profile requires an account.+ get_accounts: Account reader; defaults to+ ``src.trading.service.get_accounts``.++ Returns:+ Picker rows (``account_ref``, ``label``, ``is_default``,+ ``agentic_allowed``, ``deactivated``).++ Raises:+ ValueError: If the connection's profile takes no account.+ AccountListUnavailable: If the read failed, needs authorization, or+ its reply could not be mapped.+ """+ profile = profile_by_id(connection.profile_id)+ if not requires_account_selection(profile):+ raise ValueError(f"connection profile does not take an account: {profile.id}")+ if get_accounts is None:+ from src.trading.service import get_accounts+ envelope = get_accounts(profile.id, interactive_oauth=False)+ if str(envelope.get("status") or "").lower() not in {"ok", "success"}:+ raise AccountListUnavailable(str(envelope.get("error") or f"{profile.connector} account list read failed"))+ if envelope.get("mapping_error"):+ raise AccountListUnavailable(f"account list could not be mapped: {envelope['mapping_error']}")+ accounts = envelope.get("accounts")+ if not isinstance(accounts, list):+ raise AccountListUnavailable(f"{profile.connector} account list read returned no accounts list")+ return accounts+++def choose_account(+ choices: list[dict[str, Any]],+ account_ref: str,+ *,+ require_agentic: bool = False,+) -> dict[str, Any]:+ """Return the chosen account after checking it is usable.++ Args:+ choices: Picker rows from the broker's account list.+ account_ref: The account the user picked.+ require_agentic: Also require the broker to allow agentic trading on+ the account (a live mandate needs this; a read does not).++ Returns:+ The matching picker row.++ Raises:+ ValueError: If the account is not in the list, is deactivated, or does+ not allow agentic trading when that is required.+ """+ match = next((row for row in choices if row.get("account_ref") == account_ref), None)+ if match is None:+ raise ValueError("that account is not one of the accounts this login can reach")+ if match.get("deactivated"):+ raise ValueError("that account is deactivated")+ if require_agentic and not match.get("agentic_allowed"):+ raise ValueError("the broker does not allow agentic trading on that account")+ return matchdiff --git a/agent/src/trading/connections.py b/agent/src/trading/connections.pyindex b400d577a..533b32427 100644--- a/agent/src/trading/connections.py+++ b/agent/src/trading/connections.py@@ -6,7 +6,7 @@ import jsonimport osimport reimport tempfile-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, replacefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any@@ -21,6 +21,7 @@ from src.trading.types import TradingProfileCONFIG_FILENAME = "connections.json"_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$")REQUIRED_READ_CAPABILITIES = frozenset({"account.read", "positions.read"})+_ACCOUNT_REF_MAX_LENGTH = 128def is_portfolio_connection_profile(profile: TradingProfile) -> bool:@@ -40,6 +41,42 @@ def is_portfolio_connection_profile(profile: TradingProfile) -> bool:return bool(profile.readonly) and REQUIRED_READ_CAPABILITIES.issubset(profile.capabilities)+def requires_account_selection(profile: TradingProfile) -> bool:+ """Report whether a profile's account-scoped reads must name one account.++ A remote MCP server such as Robinhood's serves every account behind one+ OAuth grant and takes the account on each read. A connection through such a+ profile reads nothing until an account is selected; it never falls back to+ a default or first account.++ Args:+ profile: Built-in or operator-installed trading profile.++ Returns:+ True when the profile declares ``account_selection: required``.+ """+ return profile.config.get("account_selection") == "required"+++def validate_account_ref(value: object) -> str:+ """Return a stripped opaque account reference, or raise.++ Args:+ value: Untrusted account reference; ``None`` means no account.++ Returns:+ The stripped reference, empty when none was given.++ Raises:+ ValueError: If the reference is longer than 128 characters or carries+ a control character.+ """+ account_ref = str(value or "").strip()+ if len(account_ref) > _ACCOUNT_REF_MAX_LENGTH or any(ord(character) < 32 for character in account_ref):+ raise ValueError("account reference must be at most 128 printable characters")+ return account_ref++def _now() -> str:return datetime.now(timezone.utc).isoformat()@@ -79,6 +116,8 @@ class TradingConnection:label: Human-readable name shown in the UI.credential_ref: Opaque locator for the credentials; never a secret.created_at: ISO-8601 UTC creation timestamp.+ account_ref: Broker account the reads are scoped to, for a profile+ that requires one; empty until the user selects it."""id: str@@ -86,6 +125,7 @@ class TradingConnection:label: strcredential_ref: strcreated_at: str+ account_ref: str = ""def to_dict(self) -> dict[str, str]:"""Return the connection as a JSON-serializable mapping.@@ -226,6 +266,26 @@ class ConnectionStore:raise ValueError(f"local connection {existing.id} already uses profile {existing.profile_id}")return existing+ def select_account(self, connection_id: str, account_ref: str) -> TradingConnection:+ """Scope a connection's reads to one broker account.++ The caller is responsible for checking the account against the broker's+ own account list first; this only validates and stores the reference.++ Args:+ connection_id: Connection to update.+ account_ref: Account reference, or empty to clear the selection.++ Returns:+ The stored connection.++ Raises:+ ValueError: If the connection is unknown, its profile takes no+ account, or the reference fails validation.+ """+ connection = self.get(connection_id)+ return self.save(replace(connection, account_ref=validate_account_ref(account_ref)))+def delete(self, connection_id: str) -> None:"""Delete a connection and any secrets stored for it.@@ -268,6 +328,7 @@ class ConnectionStore:"readonly": profile.readonly,"capabilities": list(profile.capabilities),"supports_reconnect": profile.transport == "remote_mcp",+ "account_selection_required": requires_account_selection(profile),"credential_fields": credential_field_catalog(profile.id),"credential_status": field_status,"credentials_configured": bool(required_fields)@@ -311,12 +372,16 @@ class ConnectionStore:credential_ref = expected_refif credential_ref != expected_ref:raise ValueError("connection credential_ref does not match its local transport")+ 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}")return TradingConnection(id=connection_id,profile_id=profile.id,label=label,credential_ref=credential_ref,created_at=str(raw.get("created_at") or _now()),+ account_ref=account_ref,)def _write(self, connections: list[TradingConnection]) -> None:@@ -414,6 +479,7 @@ def readonly_profile_catalog() -> list[dict[str, Any]]:"local_plugin": profile.id in plugin_ids,"credential_fields": credential_field_catalog(profile.id),"supports_reconnect": profile.transport == "remote_mcp",+ "account_selection_required": requires_account_selection(profile),"onboarding": onboarding_dict(profile),})diff --git a/agent/src/trading/connectors/robinhood/mcp.py b/agent/src/trading/connectors/robinhood/mcp.pyindex fd061233e..d7b421b5d 100644--- a/agent/src/trading/connectors/robinhood/mcp.py+++ b/agent/src/trading/connectors/robinhood/mcp.py@@ -1,10 +1,34 @@-"""Robinhood remote MCP generic-operation mapping."""+"""Robinhood remote MCP generic-operation mapping and reply shapes.++Every consumer that reads a Robinhood reply goes through this module: the+trading service's generic reads, the portfolio source, the live runner, the+pre-trade order gate and the mandate ceiling fetch. They used to read the reply+one level too shallow (``data.positions`` where Robinhood nests+``data.data.positions``), each in its own way (#1442).++What the shapes are built from, and nothing else:++* ``get_accounts``: observed field names and types posted on #1428+ (2026-09-14). Not a schema.+* ``get_portfolio``: observed on #1428 (2026-09-14). Not a schema.+* ``get_equity_positions``: the server's advertised ``outputSchema`` posted on+ #1428 (2026-09-16). ``data`` allows exactly ``positions`` and ``next``. An item+ carries ``symbol``, ``quantity`` and an optional ``average_buy_price``, and no+ price or currency.++Still unobserved: ``get_equity_quotes``, ``get_equity_orders``, the argument that+fetches a further page, and what an item's ``type`` means. So a reply with+more than one page is an error rather than a first page read as the whole+account, and ``type`` is carried through without being interpreted.+"""from __future__ import annotations+from decimal import Decimal, InvalidOperationfrom typing import Any_REMOTE_TOOL_NAMES = {+ "accounts": "get_accounts","account": "get_portfolio","positions": "get_equity_positions","orders": "get_equity_orders",@@ -12,6 +36,7 @@ _REMOTE_TOOL_NAMES = {}_RUNNER_TOOL_NAMES = {+ "accounts": "get_accounts","account": "get_portfolio","positions": "get_equity_positions","orders": "get_equity_orders",@@ -20,6 +45,24 @@ _RUNNER_TOOL_NAMES = {"cancel_order": "cancel_equity_order",}+#: ``get_portfolio`` values held outside equities. ``get_equity_positions``+#: covers none of them, so a holdings view is only complete when all are zero.+NON_EQUITY_VALUE_FIELDS = (+ "options_value",+ "crypto_value",+ "futures_value",+ "event_contracts_value",+ "mutual_funds_value",+ "fixed_income_value",+)++#: Operations whose remote tool takes the selected account as ``account_number``.+ACCOUNT_SCOPED_OPERATIONS = frozenset({"account", "positions", "orders"})+++class RobinhoodShapeError(ValueError):+ """A Robinhood reply that does not match the shape this mapping was built from."""+def remote_tool_name(operation: str) -> str | None:"""Return the Robinhood remote tool name for a generic operation."""@@ -37,7 +80,7 @@ def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Anysymbol = arguments.get("symbol")symbols = arguments.get("symbols")return {"symbols": symbols or ([symbol] if symbol else [])}- if operation in ("account", "positions", "orders"):+ if operation in ACCOUNT_SCOPED_OPERATIONS:# Robinhood's get_portfolio / get_equity_positions / get_equity_orders# MCP tools require account_number. The generic trading service passes# the CLI/agent-supplied account code in under the "account" key; map@@ -47,3 +90,232 @@ def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Anyreturn {"account_number": account_number}return {}return {}+++def broker_data(envelope: Any, tool: str) -> dict[str, Any]:+ """Return the broker's inner ``data`` object from an adapter envelope.++ Args:+ envelope: ``MCPServerAdapter.call_tool`` result.+ tool: Remote tool name, for the error message.++ Returns:+ The ``data`` object of the broker payload.++ Raises:+ RobinhoodShapeError: If the call failed, or the payload is not an+ object whose ``data`` is an object.+ """+ if not isinstance(envelope, dict):+ raise RobinhoodShapeError(f"{tool} returned {type(envelope).__name__}, not an object")+ if str(envelope.get("status") or "").lower() != "ok":+ raise RobinhoodShapeError(str(envelope.get("error") or f"{tool} failed"))+ payload = envelope.get("structured_content")+ if payload is None:+ payload = envelope.get("data")+ if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):+ raise RobinhoodShapeError(f"{tool} reply has no data object")+ return payload["data"]+++def records(envelope: Any, key: str, tool: str) -> list[dict[str, Any]]:+ """Return the complete record list a Robinhood list read carries.++ Args:+ envelope: ``MCPServerAdapter.call_tool`` result.+ key: The list field inside ``data`` (``positions``, ``orders``,+ ``accounts``).+ tool: Remote tool name, for error messages.++ Returns:+ Every record, each an object.++ Raises:+ RobinhoodShapeError: If the list is missing or null, holds a null or+ non-object item, ``data`` carries a key other than ``key`` and+ ``next``, or a non-empty ``next`` says the reply is one page of+ several.+ """+ data = broker_data(envelope, tool)+ unexpected = sorted(set(data) - {key, "next"})+ if unexpected:+ raise RobinhoodShapeError(f"{tool} reply has unmapped data keys: {', '.join(unexpected)}")+ if data.get("next") not in (None, ""):+ raise RobinhoodShapeError(+ f"{tool} returned more than one page; reading further pages is not mapped yet, "+ "and the first page is not the whole account"+ )+ rows = data.get(key)+ if not isinstance(rows, list):+ raise RobinhoodShapeError(f"{tool} reply has no {key} list")+ for index, row in enumerate(rows):+ if not isinstance(row, dict):+ raise RobinhoodShapeError(f"{tool} {key}[{index}] is not an object")+ return rows+++def _decimal_text(value: Any, field: str, tool: str) -> str:+ """Return ``value`` when it is a finite decimal string, else raise."""+ if isinstance(value, bool) or value is None:+ raise RobinhoodShapeError(f"{tool} {field} is missing")+ try:+ parsed = Decimal(str(value))+ except (InvalidOperation, ValueError):+ raise RobinhoodShapeError(f"{tool} {field} is not a number") from None+ if not parsed.is_finite():+ raise RobinhoodShapeError(f"{tool} {field} is not finite")+ return str(value)+++def portfolio_summary(envelope: Any) -> dict[str, Any]:+ """Map a ``get_portfolio`` reply to the account summary every consumer reads.++ Args:+ envelope: ``MCPServerAdapter.call_tool`` result for ``get_portfolio``.++ Returns:+ ``portfolio_value``, ``cash``, ``buying_power`` and ``currency``, plus+ ``non_equity_values`` mapping each field in+ :data:`NON_EQUITY_VALUE_FIELDS` to its value, or ``None`` when the+ reply omitted it. Values stay decimal strings.++ Raises:+ RobinhoodShapeError: If ``total_value`` or ``currency`` is missing, or a+ value that is present is not a finite number.+ """+ tool = "get_portfolio"+ data = broker_data(envelope, tool)+ currency = data.get("currency")+ if not isinstance(currency, str) or not currency.strip():+ raise RobinhoodShapeError(f"{tool} currency is missing")+ buying_power = data.get("buying_power")+ raw_buying_power = buying_power.get("buying_power") if isinstance(buying_power, dict) else None+ return {+ "portfolio_value": _decimal_text(data.get("total_value"), "total_value", tool),+ "cash": _decimal_text(data["cash"], "cash", tool) if data.get("cash") is not None else None,+ "buying_power": (+ _decimal_text(raw_buying_power, "buying_power.buying_power", tool)+ if raw_buying_power is not None+ else None+ ),+ "currency": currency.strip().upper(),+ "non_equity_values": {+ field: _decimal_text(data[field], field, tool) if data.get(field) is not None else None+ for field in NON_EQUITY_VALUE_FIELDS+ },+ }+++def position_rows(envelope: Any) -> list[dict[str, Any]]:+ """Map a ``get_equity_positions`` reply to generic position rows.++ Args:+ envelope: ``MCPServerAdapter.call_tool`` result for+ ``get_equity_positions``.++ Returns:+ One ``{"symbol", "quantity", "average_cost", "broker_type"}`` row per+ position. ``average_cost`` is ``None`` when Robinhood omitted+ ``average_buy_price`` (it does while a position reconciles); it is+ never read as zero.++ Raises:+ RobinhoodShapeError: If the reply is not a complete, single-page+ position list, or a row has no symbol or a non-numeric quantity.+ """+ tool = "get_equity_positions"+ rows = []+ for index, row in enumerate(records(envelope, "positions", tool)):+ symbol = row.get("symbol")+ if not isinstance(symbol, str) or not symbol.strip():+ raise RobinhoodShapeError(f"{tool} positions[{index}] has no symbol")+ average = row.get("average_buy_price")+ rows.append(+ {+ "symbol": symbol.strip().upper(),+ "quantity": _decimal_text(row.get("quantity"), f"positions[{index}].quantity", tool),+ "average_cost": (+ _decimal_text(average, f"positions[{index}].average_buy_price", tool)+ if average is not None+ else None+ ),+ "broker_type": row.get("type"),+ }+ )+ return rows+++def account_choices(envelope: Any) -> list[dict[str, Any]]:+ """Map a ``get_accounts`` reply to the rows an account picker shows.++ Args:+ envelope: ``MCPServerAdapter.call_tool`` result for ``get_accounts``.++ Returns:+ One row per account: ``account_ref`` (the account number, which is+ what the account-scoped tools take), a ``label`` built from the+ nickname or account type plus the last four digits, and the+ ``is_default`` / ``agentic_allowed`` / ``deactivated`` flags. Every+ other field Robinhood returns is dropped.++ Raises:+ RobinhoodShapeError: If the reply is not a complete account list, or an+ account has no account number.+ """+ tool = "get_accounts"+ choices = []+ for index, row in enumerate(records(envelope, "accounts", tool)):+ number = row.get("account_number")+ if not isinstance(number, str) or not number.strip():+ raise RobinhoodShapeError(f"{tool} accounts[{index}] has no account_number")+ number = number.strip()+ name = next(+ (+ str(row[key]).strip()+ for key in ("nickname", "brokerage_account_type", "type")+ if isinstance(row.get(key), str) and row[key].strip()+ ),+ "Robinhood account",+ )+ choices.append(+ {+ "account_ref": number,+ "label": f"{name} ····{number[-4:]}",+ "is_default": row.get("is_default") is True,+ "agentic_allowed": row.get("agentic_allowed") is True,+ "deactivated": row.get("deactivated") is True or row.get("permanently_deactivated") is True,+ }+ )+ return choices+++def normalize_result(operation: str, envelope: dict[str, Any]) -> dict[str, Any]:+ """Add the generic account / positions / accounts view to a Robinhood reply.++ The broker reply is kept as it came. A reply that does not match the mapped+ shape is not turned into an error here, because an agent reading the+ account can still use the raw text. It carries ``mapping_error`` instead,+ and a consumer that needs the mapped view (the portfolio) fails on it.++ Args:+ operation: Generic operation that produced the reply.+ envelope: ``MCPServerAdapter.call_tool`` result.++ Returns:+ A shallow copy with ``account``, ``positions`` or ``accounts`` added, or+ with ``mapping_error`` when the shape did not match.+ """+ mappers = {+ "account": ("account", portfolio_summary),+ "positions": ("positions", position_rows),+ "accounts": ("accounts", account_choices),+ }+ if operation not in mappers or str(envelope.get("status") or "").lower() != "ok":+ return envelope+ key, mapper = mappers[operation]+ normalized = dict(envelope)+ try:+ normalized[key] = mapper(envelope)+ except RobinhoodShapeError as exc:+ normalized["mapping_error"] = str(exc)+ return normalizeddiff --git a/agent/src/trading/connectors/robinhood/profiles.py b/agent/src/trading/connectors/robinhood/profiles.pyindex 997660b66..ae5864417 100644--- a/agent/src/trading/connectors/robinhood/profiles.py+++ b/agent/src/trading/connectors/robinhood/profiles.py@@ -20,7 +20,27 @@ ROBINHOOD_PROFILES: tuple[TradingProfile, ...] = ("runner.manage.requires_mandate",),readonly=False,- config={"server": "robinhood"},+ config={"server": "robinhood", "account_selection": "required"},notes="Reads via Robinhood MCP; execution stays behind OAuth, mandate, guard, audit, and halt.",),+ # The portfolio view of the same MCP server and OAuth grant. It declares no+ # quotes.read: the get_equity_quotes reply shape has not been observed, so+ # positions are listed unpriced rather than priced off a guessed field.+ TradingProfile(+ id="robinhood-live-mcp-readonly",+ connector="robinhood",+ label="Robinhood Live · Agentic MCP Read-Only",+ environment="live",+ transport="remote_mcp",+ capabilities=("account.read", "positions.read"),+ readonly=True,+ config={"server": "robinhood", "account_selection": "required"},+ notes=(+ "Reads get_portfolio and get_equity_positions for one selected account. "+ "Positions are unpriced until the quote reply is mapped; an account holding "+ "options, crypto, futures, event contracts, mutual funds or fixed income is "+ "reported as an error instead of an equity-only view."+ ),+ ),)+diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 1ab2caf26..b641ad48a 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -238,6 +238,31 @@ def get_account(profile_id: str | None = None, **overrides: Any) -> dict[str, An)+def get_accounts(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:+ """List the broker accounts a remote MCP profile can be scoped to.++ Only remote MCP connectors whose account-scoped reads take an account+ (Robinhood) map this operation; every other profile reports it unsupported.++ Args:+ profile_id: Connector profile to read through.+ **overrides: ``interactive_oauth=False`` keeps an expired grant from+ opening a browser.++ Returns:+ The remote envelope; a mapped connector adds an ``accounts`` list.+ """+ profile = profile_by_id(profile_id)+ if profile.transport != "remote_mcp":+ return _unsupported(profile, "accounts.read")+ return _call_remote(+ profile,+ "accounts",+ {},+ interactive_oauth=bool(overrides.get("interactive_oauth", True)),+ )++def get_positions(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:"""Read positions for a connector profile."""profile = profile_by_id(profile_id)@@ -1279,6 +1304,110 @@ def runner_tool_name(connector: str, operation: str) -> str | None:return None+def runner_requires_account(connector: str) -> bool:+ """Return whether a live runner broker's reads and orders must name an account.++ Args:+ connector: Broker key, e.g. ``"robinhood"``.++ Returns:+ True when the broker's live-runner profile declares+ ``account_selection: required``. Such a broker never falls back to a+ default account: a mandate without one cannot trade.+ """+ from src.trading.connections import requires_account_selection++ profile = live_runner_profile_for_broker(connector)+ return profile is not None and requires_account_selection(profile)+++def runner_arguments(connector: str, operation: str, account_ref: str = "", **arguments: Any) -> dict[str, Any]:+ """Return the wire arguments for a live-path read, bound to one account.++ Args:+ connector: Broker key.+ operation: Generic operation (``account``, ``positions``, ``orders``).+ account_ref: The mandate's account; empty for a broker that takes none.+ **arguments: Further generic arguments.++ Returns:+ The connector's wire arguments. A connector without a mapping gets+ ``arguments`` unchanged, which is what the live path sent before.+ """+ if connector == "robinhood":+ from src.trading.connectors.robinhood.mcp import remote_arguments++ return remote_arguments(operation, {**arguments, "account": account_ref})+ return dict(arguments)+++def runner_records(connector: str, operation: str, envelope: Any) -> list[dict[str, Any]] | None:+ """Unwrap a live-path list read into complete broker records.++ Args:+ connector: Broker key.+ operation: ``positions`` or ``orders``.+ envelope: The adapter's call result.++ Returns:+ The records, or ``None`` when the connector has no mapped reply shape+ (the caller keeps its generic unwrap).++ Raises:+ ValueError: If a mapped reply does not match its shape, is one page of+ several, or is an error envelope.+ """+ if connector != "robinhood":+ return None+ from src.trading.connectors.robinhood import mcp++ if operation == "positions":+ return [{**row, "qty": row["quantity"]} for row in mcp.position_rows(envelope)]+ if operation == "orders":+ return mcp.records(envelope, "orders", "get_equity_orders")+ raise ValueError(f"no record mapping for operation {operation!r}")+++def runner_account_summary(connector: str, envelope: Any) -> dict[str, Any] | None:+ """Unwrap a live-path account read into the mapped summary.++ Args:+ connector: Broker key.+ envelope: The adapter's call result.++ Returns:+ The summary, or ``None`` when the connector has no mapped reply shape.++ Raises:+ ValueError: If a mapped reply does not match its shape.+ """+ if connector != "robinhood":+ return None+ from src.trading.connectors.robinhood.mcp import portfolio_summary++ return portfolio_summary(envelope)+++def runner_account_choices(connector: str, envelope: Any) -> list[dict[str, Any]] | None:+ """Map a live-path account listing to picker rows.++ Args:+ connector: Broker key.+ envelope: The adapter's ``accounts`` call result.++ Returns:+ The picker rows, or ``None`` when the connector lists no accounts.++ Raises:+ ValueError: If a mapped reply does not match its shape.+ """+ if connector != "robinhood":+ return None+ from src.trading.connectors.robinhood.mcp import account_choices++ return account_choices(envelope)++def _with_profile(profile: TradingProfile, payload: dict[str, Any]) -> dict[str, Any]:"""Add connector profile metadata to an operation payload."""result = dict(payload)@@ -1478,6 +1607,10 @@ def _normalize_remote_result(connector: str, operation: str, result: dict[str, Aif connector == "ibkr":from src.trading.connectors.ibkr.mcp import normalize_result+ return normalize_result(operation, result)+ if connector == "robinhood":+ from src.trading.connectors.robinhood.mcp import normalize_result+return normalize_result(operation, result)return resultdiff --git a/agent/tests/robinhood_mcp_helpers.py b/agent/tests/robinhood_mcp_helpers.pynew file mode 100644index 000000000..319aeec20--- /dev/null+++ b/agent/tests/robinhood_mcp_helpers.py@@ -0,0 +1,125 @@+"""Robinhood MCP reply builders, taken from the shapes posted on #1428.++Every builder reproduces the adapter envelope ``MCPServerAdapter.call_tool``+returns around a Robinhood reply: the broker payload ``{"data": ..., "guide":+...}`` sits under both ``structured_content`` and ``data``. So the records a+test cares about are at ``structured_content.data.<key>``, one level deeper than+the ``data.positions`` the live path used to read (#1442).++Field names and types come from balu1866's posts: observed ``get_accounts`` and+``get_portfolio`` replies (2026-09-14) and the advertised+``get_equity_positions`` ``outputSchema`` (2026-09-16). Values are invented.+"""++from __future__ import annotations++from typing import Any++#: Required ``get_equity_positions`` item fields other than symbol / quantity / type.+_POSITION_SHARE_FIELDS = (+ "intraday_quantity",+ "shares_available_for_sells",+ "shares_held_for_sells",+ "shares_held_for_stock_grants",+ "shares_held_for_options_events",+ "shares_held_for_asset_transfer",+ "shares_pending_from_options_events",+)+++def envelope(tool: str, data: Any, *, guide: str = "Values are strings.") -> dict[str, Any]:+ """Wrap a broker ``data`` object the way the MCP adapter returns it."""+ structured = {"data": data, "guide": guide}+ return {+ "status": "ok",+ "data": structured,+ "structured_content": structured,+ "server": "robinhood",+ "remote_tool": tool,+ "tool": tool,+ }+++def position(symbol: str, quantity: str, *, average_buy_price: str | None = "100.00") -> dict[str, Any]:+ """Return one ``get_equity_positions`` item with every required field."""+ # The meaning and values of `type` are unobserved, so tests never depend on it.+ row: dict[str, Any] = {"symbol": symbol, "quantity": quantity, "type": "unobserved"}+ row.update({field: "0" for field in _POSITION_SHARE_FIELDS})+ row["shares_available_for_sells"] = quantity+ if average_buy_price is not None:+ row["average_buy_price"] = average_buy_price+ return row+++def positions(rows: list[dict[str, Any]] | None, *, next_page: str | None = None) -> dict[str, Any]:+ """Return a ``get_equity_positions`` envelope."""+ data: dict[str, Any] = {"positions": rows}+ if next_page is not None:+ data["next"] = next_page+ return envelope("get_equity_positions", data)+++def portfolio(+ *,+ total_value: str = "5000.00",+ cash: str = "5000.00",+ buying_power: str = "5000.00",+ currency: str = "USD",+ **values: str,+) -> dict[str, Any]:+ """Return a ``get_portfolio`` envelope; non-equity values default to zero."""+ data: dict[str, Any] = {+ "total_value": total_value,+ "equity_value": "0.00",+ "options_value": "0.00",+ "futures_value": "0.00",+ "event_contracts_value": "0.00",+ "crypto_value": "0.00",+ "cash": cash,+ "pending_deposits": "0.00",+ "mutual_funds_value": "0.00",+ "fixed_income_value": "0.00",+ "currency": currency,+ "buying_power": {+ "buying_power": buying_power,+ "unleveraged_buying_power": buying_power,+ "display_currency": currency,+ },+ "crypto_buying_power": {"buying_power": "0.00"},+ }+ data.update(values)+ return envelope("get_portfolio", data)+++def account(+ number: str,+ *,+ nickname: str | None = None,+ is_default: bool = False,+ agentic_allowed: bool = True,+ deactivated: bool = False,+) -> dict[str, Any]:+ """Return one ``get_accounts`` item."""+ row: dict[str, Any] = {+ "account_number": number,+ "affiliate": "rhf",+ "agentic_allowed": agentic_allowed,+ "brokerage_account_type": "individual",+ "deactivated": deactivated,+ "is_default": is_default,+ "management_type": "self_directed",+ "option_level": "option_level_2",+ "permanently_deactivated": False,+ "rhs_account_number": f"rhs-{number}",+ "state": "active",+ "type": "cash",+ "unsettled_funds": "0.00",+ }+ if nickname is not None:+ row["nickname"] = nickname+ return row+++def accounts(rows: list[dict[str, Any]]) -> dict[str, Any]:+ """Return a ``get_accounts`` envelope."""+ return envelope("get_accounts", {"accounts": rows})diff --git a/agent/tests/test_advisory.py b/agent/tests/test_advisory.pyindex 0a6433674..483b2bd10 100644--- a/agent/tests/test_advisory.py+++ b/agent/tests/test_advisory.py@@ -37,6 +37,7 @@ from src.live.mandate.model import ()from src.live.order_guard import LiveOrderGuardToolfrom src.tools.mcp import MCPRemoteToolSpec+from tests import robinhood_mcp_helpers as rh@pytest.fixture@@ -56,9 +57,9 @@ class _MockAdapter:self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:if remote_name == "get_equity_positions":- return {"positions": self._positions, "status": "ok"}+ return rh.positions(self._positions)if remote_name == "get_portfolio":- return {"equity": self._balance, "status": "ok"}+ return rh.portfolio(total_value=str(self._balance))self.order_calls.append({"remote": remote_name, "arguments": arguments})return {"status": "ok", "order_id": "rh_test_1", "state": "accepted"}diff --git a/agent/tests/test_api_live_runtime.py b/agent/tests/test_api_live_runtime.pyindex 9a9c2b683..11798d2fd 100644--- a/agent/tests/test_api_live_runtime.py+++ b/agent/tests/test_api_live_runtime.py@@ -22,6 +22,7 @@ from fastapi.testclient import TestClientimport pytestimport api_server+from tests import robinhood_mcp_helpers as rhdef _client(tmp_path: Path, monkeypatch) -> TestClient:@@ -353,6 +354,7 @@ def test_build_live_runner_wires_a_real_runner(tmp_path, monkeypatch) -> None:monkeypatch.setattr(api_server, "_live_broker_adapter", lambda broker: _StubAdapter())monkeypatch.setattr(api_server, "_get_session_service", lambda: _StubSvc())+ monkeypatch.setattr(api_server, "_mandate_account_ref", lambda broker: "5QR00001")runner = api_server._build_live_runner("robinhood")# Constructs without TypeError and exposes the R2 contract.@@ -427,13 +429,18 @@ def test_live_action_relay_ignores_non_live_results(tmp_path: Path, monkeypatch)def test_fetch_broker_ceilings_derives_from_account(tmp_path, monkeypatch) -> None:+ calls: list[tuple[str, dict]] = []+class _StubAdapter:def call_tool(self, name, args):- assert name == "get_portfolio"- return {"status": "ok", "result": {"buying_power": 4200.0}}+ calls.append((name, args))+ return rh.portfolio(total_value="9000.00", cash="1000.00", buying_power="4200.00")monkeypatch.setattr(api_server, "_live_broker_adapter", lambda broker: _StubAdapter())- ceilings = api_server._fetch_broker_ceilings("robinhood")+ ceilings = api_server._fetch_broker_ceilings("robinhood", "5QR00001")+ # The read is scoped to the account being bound, and the value comes from+ # Robinhood's nested buying_power.buying_power, not a top-level key.+ assert calls == [("get_portfolio", {"account_number": "5QR00001"})]assert ceilings == {"account_funding_usd": 4200.0,"max_order_notional_usd": 4200.0,@@ -464,11 +471,11 @@ def test_build_live_runner_reads_normalize_adapter_payloads(tmp_path, monkeypatcdef call_tool(self, name, args):self.calls.append((name, args))if name.endswith("positions"):- return {"status": "ok", "data": {"positions": [{"symbol": "NVDA", "qty": 3}]}}+ return rh.positions([rh.position("NVDA", "3")])if name.endswith("orders"):- return {"status": "ok", "data": {"orders": [{"order_id": "o1"}]}}+ return rh.envelope("get_equity_orders", {"orders": [{"order_id": "o1"}]})if name.endswith("portfolio"):- return {"status": "ok", "data": {"buying_power": 4200.0}}+ return rh.portfolio(buying_power="4200.00")raise AssertionError(f"unexpected tool {name}")class _StubSvc:@@ -484,11 +491,15 @@ def test_build_live_runner_reads_normalize_adapter_payloads(tmp_path, monkeypatcadapter = _StubAdapter()monkeypatch.setattr(api_server, "_live_broker_adapter", lambda broker: adapter)monkeypatch.setattr(api_server, "_get_session_service", lambda: _StubSvc())+ monkeypatch.setattr(api_server, "_mandate_account_ref", lambda broker: "5QR00001")runner = api_server._build_live_runner("robinhood")- assert runner._read_positions() == [{"symbol": "NVDA", "qty": 3}]+ assert runner._read_positions() == [+ {"symbol": "NVDA", "quantity": "3", "average_cost": "100.00", "broker_type": "unobserved", "qty": "3"}+ ]assert runner._read_open_orders() == [{"order_id": "o1"}]- assert runner._read_balance() == {"buying_power": 4200.0}+ assert runner._read_balance()["buying_power"] == "4200.00"+ assert {args.get("account_number") for _, args in adapter.calls} == {"5QR00001"}def test_build_live_runner_read_error_envelope_raises(tmp_path, monkeypatch) -> None:@@ -521,6 +532,7 @@ def test_build_live_runner_read_error_envelope_raises(tmp_path, monkeypatch) ->monkeypatch.setattr(api_server, "_live_broker_adapter", lambda broker: _StubAdapter())monkeypatch.setattr(api_server, "_get_session_service", lambda: _StubSvc())+ monkeypatch.setattr(api_server, "_mandate_account_ref", lambda broker: "5QR00001")runner = api_server._build_live_runner("robinhood")with pytest.raises(RuntimeError, match="connection reset while reading positions"):diff --git a/agent/tests/test_cli_live.py b/agent/tests/test_cli_live.pyindex a04e6f0ab..a7f1f5cb3 100644--- a/agent/tests/test_cli_live.py+++ b/agent/tests/test_cli_live.py@@ -14,6 +14,7 @@ Covers SPEC.md §9 Decision 1 (CLI surface table) and Consent §2/§4:from __future__ import annotations+from types import SimpleNamespaceimport jsonfrom pathlib import Pathfrom typing import Any, Dict@@ -467,6 +468,19 @@ class TestNumericPick:# ---------------------------------------------------------------------------+class _AccountListing:+ """Stands in for ``httpx.get`` on ``/live/accounts``."""++ def __init__(self, payload: Dict[str, Any]) -> None:+ self.payload = payload+ self.calls: list[Dict[str, Any]] = []++ def __call__(self, url: str, params: Dict[str, Any], headers: Dict[str, str], timeout: float):+ assert url.endswith("/live/accounts")+ self.calls.append(dict(params))+ return SimpleNamespace(raise_for_status=lambda: None, json=lambda: self.payload)++def _proposal() -> Dict[str, Any]:return {"proposal_id": "mp_" + "3" * 32,@@ -556,10 +570,12 @@ class TestProposalPickIntercept:return _Resp()monkeypatch.setenv("API_AUTH_KEY", "cli-secret")- with patch("httpx.post", _fake_post):+ listing = _AccountListing({"account_selection_required": False, "accounts": []})+ with patch("httpx.post", _fake_post), patch("httpx.get", listing):result = _commit_mandate(_proposal(), 2)assert result["mandate_id"] == "m1"+ assert listing.calls == [{"broker": "robinhood"}]assert captured["url"].endswith("/mandate/commit")assert captured["body"]["selected_ordinal"] == 2assert captured["body"]["proposal_id"] == "mp_" + "3" * 32@@ -573,12 +589,60 @@ class TestProposalPickIntercept:proposal = _proposal()proposal["account"] = {"type": "cash"}- with patch("httpx.post") as post:+ with patch("httpx.post") as post, patch("httpx.get") as get:result = _commit_mandate(proposal, 1)assert result["status"] == "error"assert "broker" in result["error"]post.assert_not_called()+ get.assert_not_called()++ def test_an_account_bound_broker_commits_the_account_the_user_picks(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """The account comes from the user's pick, never from the proposal."""+ rows = [+ {"account_ref": "5QR12345", "label": "Main ····2345", "is_default": True, "agentic_allowed": True, "deactivated": False},+ ]+ seen: Dict[str, Any] = {}+ posted: Dict[str, Any] = {}+ listing = _AccountListing({"account_selection_required": True, "accounts": rows})++ def _choose(accounts: list) -> str:+ seen["accounts"] = accounts+ return "5QR12345"++ def _fake_post(url, json, headers, timeout): # noqa: A002, ANN001+ posted.update(json)+ return SimpleNamespace(raise_for_status=lambda: None, json=lambda: {"status": "ok", "mandate_id": "m2"})++ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ with patch("httpx.post", _fake_post), patch("httpx.get", listing):+ result = _commit_mandate(_proposal(), 1, choose_account=_choose)++ assert result["mandate_id"] == "m2"+ assert seen["accounts"] == rows+ assert posted["account_ref"] == "5QR12345" # not the proposal's "acct-demo"++ def test_no_chosen_account_commits_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:+ listing = _AccountListing({"account_selection_required": True, "accounts": []})+ with patch("httpx.post") as post, patch("httpx.get", listing):+ result = _commit_mandate(_proposal(), 1, choose_account=lambda accounts: "")++ assert result == {"status": "error", "error": "no account was chosen for this mandate"}+ post.assert_not_called()++ def test_the_default_chooser_offers_only_usable_accounts_and_preselects_nothing(self, monkeypatch) -> None:+ rows = [+ {"account_ref": "A1", "label": "Main", "is_default": True, "agentic_allowed": True, "deactivated": False},+ {"account_ref": "A2", "label": "IRA", "is_default": False, "agentic_allowed": False, "deactivated": False},+ {"account_ref": "A3", "label": "Old", "is_default": False, "agentic_allowed": True, "deactivated": True},+ {"account_ref": "A4", "label": "Joint", "is_default": False, "agentic_allowed": True, "deactivated": False},+ ]+ replies = iter(["", "2", "9"])+ monkeypatch.setattr("builtins.input", lambda prompt="": next(replies))++ assert main._choose_mandate_account(rows) == "" # an empty reply is not the default+ assert main._choose_mandate_account(rows) == "A4" # [1] Main, [2] Joint+ assert main._choose_mandate_account(rows) == "" # out of range# ---------------------------------------------------------------------------diff --git a/agent/tests/test_enforcement_l6.py b/agent/tests/test_enforcement_l6.pyindex f2070105b..729cf398a 100644--- a/agent/tests/test_enforcement_l6.py+++ b/agent/tests/test_enforcement_l6.py@@ -31,6 +31,7 @@ from src.live.mandate.model import ()from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSfrom src.tools.mcp import MCPRemoteToolSpec+from tests import robinhood_mcp_helpers as rh# --------------------------------------------------------------------------- #@@ -215,9 +216,9 @@ class _BrokerQuoteAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:if remote_name == "get_equity_positions":- return {"positions": [], "status": "ok"}+ return rh.positions([])if remote_name == "get_portfolio":- return {"equity": 100000.0, "status": "ok"}+ return rh.portfolio(total_value="100000.00", cash="100000.00", buying_power="100000.00")if remote_name == "get_equity_quotes":self.quote_calls += 1return {"status": "ok", "results": [{"symbol": arguments.get("symbol"), "last_price": self._price}]}@@ -234,9 +235,9 @@ class _NoBrokerQuoteAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:if remote_name == "get_equity_positions":- return {"positions": [], "status": "ok"}+ return rh.positions([])if remote_name == "get_portfolio":- return {"equity": 100000.0, "status": "ok"}+ return rh.portfolio(total_value="100000.00", cash="100000.00", buying_power="100000.00")if remote_name == "get_equity_quotes":return {"status": "error", "error": "quotes unavailable"}self.order_calls.append({"remote": remote_name, "arguments": arguments})diff --git a/agent/tests/test_killswitch_blocks_orders.py b/agent/tests/test_killswitch_blocks_orders.pyindex ff1a7e351..2f34da09a 100644--- a/agent/tests/test_killswitch_blocks_orders.py+++ b/agent/tests/test_killswitch_blocks_orders.py@@ -27,6 +27,7 @@ from src.live.mandate.model import ()from src.live.order_guard import LiveOrderGuardToolfrom src.tools.mcp import MCPRemoteTool, MCPRemoteToolSpec+from tests import robinhood_mcp_helpers as rh@pytest.fixture@@ -43,9 +44,9 @@ class _MockAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:self.calls.append(remote_name)if remote_name == "get_equity_positions":- return {"positions": [], "status": "ok"}+ return rh.positions([])if remote_name == "get_portfolio":- return {"equity": 5000.0, "status": "ok"}+ return rh.portfolio()return {"status": "ok", "order_id": "rh_x", "state": "accepted"}diff --git a/agent/tests/test_limit_price_notional.py b/agent/tests/test_limit_price_notional.pyindex 9a0651a0a..7ff4b2c3b 100644--- a/agent/tests/test_limit_price_notional.py+++ b/agent/tests/test_limit_price_notional.py@@ -21,6 +21,7 @@ import src.live.sdk_order_gate as sdk_order_gatefrom src.live.enforcement import OrderIntentfrom src.live.mandate.model import AssetClass, InstrumentType, MANDATE_SCHEMA_VERSIONfrom src.tools.mcp import MCPRemoteToolSpec+from tests import robinhood_mcp_helpers as rhdef _connector(last: float):@@ -93,9 +94,9 @@ class _McpQuoteAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name=None) -> dict:if remote_name == "get_equity_positions":- return {"positions": [], "status": "ok"}+ return rh.positions([])if remote_name == "get_portfolio":- return {"equity": 5000.0, "status": "ok"}+ return rh.portfolio()if remote_name == "get_equity_quotes":return {"status": "ok", "results": [{"symbol": arguments.get("symbol"), "last_price": self._price}]}self.order_calls.append({"remote": remote_name, "arguments": arguments})diff --git a/agent/tests/test_mandate_enforcement.py b/agent/tests/test_mandate_enforcement.pyindex 5253b4b05..3b0cfd7c1 100644--- a/agent/tests/test_mandate_enforcement.py+++ b/agent/tests/test_mandate_enforcement.py@@ -36,6 +36,7 @@ from src.live.mandate.model import (UniverseConstraint,)from src.tools.mcp import MCPRemoteToolSpec+from tests import robinhood_mcp_helpers as rh# --------------------------------------------------------------------------- #@@ -63,9 +64,9 @@ class _MockAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:self.call_records.append({"remote": remote_name, "arguments": arguments})if remote_name == "get_equity_positions":- return {"positions": self._positions, "status": "ok"}+ return rh.positions(self._positions)if remote_name == "get_portfolio":- return {"equity": self._balance, "status": "ok"}+ return rh.portfolio(total_value=str(self._balance))# The order placement itself (super().execute forwards here).self.order_calls.append({"remote": remote_name, "arguments": arguments})return {"status": "ok", "order_id": "rh_test_1", "state": "accepted"}@@ -475,9 +476,9 @@ class _FailingForwardAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:if remote_name == "get_equity_positions":- return {"positions": [], "status": "ok"}+ return rh.positions([])if remote_name == "get_portfolio":- return {"equity": 5000.0, "status": "ok"}+ return rh.portfolio()# The order placement fails at the broker.self.order_calls.append({"remote": remote_name, "arguments": arguments})return {"status": "error", "error": "broker rejected", "error_type": "BrokerError"}@@ -556,9 +557,9 @@ class _QuoteAdapter:def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:if remote_name == "get_equity_positions":- return {"positions": self._positions, "status": "ok"}+ return rh.positions(self._positions)if remote_name == "get_portfolio":- return {"equity": self._balance, "status": "ok"}+ return rh.portfolio(total_value=str(self._balance))if remote_name == "get_equity_quotes":self.quote_calls.append({"arguments": arguments})return {"status": "ok", "symbol": arguments.get("symbol"), "price": self._price}diff --git a/agent/tests/test_portfolio_compatibility.py b/agent/tests/test_portfolio_compatibility.pyindex d0d253ba1..fbf74fed9 100644--- a/agent/tests/test_portfolio_compatibility.py+++ b/agent/tests/test_portfolio_compatibility.py@@ -31,6 +31,7 @@ def test_every_builtin_portfolio_connector_has_an_explicit_compatibility_tier():"zerodha": "experimental","upbit": "experimental","toss": "experimental",+ "robinhood": "experimental",}observed = {profile.connector: profile_compatibility(profile)["level"] for profile in eligible_profiles()}diff --git a/agent/tests/test_robinhood_live_account_binding.py b/agent/tests/test_robinhood_live_account_binding.pynew file mode 100644index 000000000..b2863d329--- /dev/null+++ b/agent/tests/test_robinhood_live_account_binding.py@@ -0,0 +1,369 @@+"""Robinhood live trading is bound to one account (#1442).++One Robinhood login reaches several accounts. The mandate names the one the+user picked at commit, and the runner reads, the runner's own orders, the+pre-trade gate reads, the gate's forwarded order and the ceiling fetch all use+that account. Nothing falls back to a default account. Replies are the #1428+shapes from ``tests/robinhood_mcp_helpers.py``.+"""++from __future__ import annotations++import json+from dataclasses import replace+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from fastapi.testclient import TestClient++import api_server+import src.live.paths as paths+from src.live import order_guard+from src.live.mandate.store import load_mandate+from src.tools.propose_mandate_tool import ProposeMandateProfilesTool+from tests import robinhood_mcp_helpers as rh+from tests.test_mandate_enforcement import _mandate, _spec, _write_mandate++pytestmark = pytest.mark.unit++ACCOUNT = "5QR12345"+++# --------------------------------------------------------------------------- #+# Pre-trade gate #+# --------------------------------------------------------------------------- #+++def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)+ return tmp_path+++class _GateBroker:+ """Answers the gate's reads and records the forwarded order."""++ def __init__(self, *, positions: list[dict] | None = None, portfolio: dict | None = None) -> None:+ self.server_name = "robinhood"+ self.positions = rh.positions(positions or [])+ self.portfolio = portfolio or rh.portfolio()+ self.reads: list[tuple[str, dict]] = []+ self.order_calls: list[dict[str, Any]] = []++ def call_tool(self, remote_name: str, arguments: dict, *, local_name: str | None = None) -> dict:+ if remote_name == "get_equity_positions":+ self.reads.append((remote_name, dict(arguments)))+ return self.positions+ if remote_name == "get_portfolio":+ self.reads.append((remote_name, dict(arguments)))+ return self.portfolio+ if remote_name == "get_equity_quotes":+ return {"status": "error", "error": "quote shape unmapped"}+ self.order_calls.append(dict(arguments))+ return {"status": "ok", "order_id": "rh_1", "state": "accepted"}+++def _bound_mandate(account_ref: str = ACCOUNT, **caps: Any):+ mandate = _mandate(**caps)+ return replace(mandate, consent=replace(mandate.consent, account_ref=account_ref))+++def _guard(adapter: _GateBroker) -> order_guard.LiveOrderGuardTool:+ return order_guard.LiveOrderGuardTool(adapter, _spec(), broker="robinhood", session_id="s1")+++def _order(guard: order_guard.LiveOrderGuardTool, **extra: Any) -> dict:+ return json.loads(guard.execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0, **extra))+++def test_gate_stamps_the_mandate_account_on_reads_and_the_order(live_runtime: Path) -> None:+ _write_mandate(live_runtime, _bound_mandate())+ broker = _GateBroker()++ out = _order(_guard(broker))++ assert out["status"] == "ok"+ assert broker.reads == [+ ("get_equity_positions", {"account_number": ACCOUNT}),+ ("get_portfolio", {"account_number": ACCOUNT}),+ ]+ assert broker.order_calls[0]["account_number"] == ACCOUNT+++def test_gate_refuses_every_order_when_the_mandate_names_no_account(live_runtime: Path) -> None:+ _write_mandate(live_runtime, _bound_mandate(account_ref=""))+ broker = _GateBroker()++ out = _order(_guard(broker))++ assert out["status"] == "blocked"+ assert "not bound to an account" in out["reason"]+ assert broker.reads == [] and broker.order_calls == []++[email protected]("key", ["account_number", "account"])+def test_gate_refuses_an_order_naming_another_account(live_runtime: Path, key: str) -> None:+ _write_mandate(live_runtime, _bound_mandate())+ broker = _GateBroker()++ out = _order(_guard(broker), **{key: "5QR99999"})++ assert out["status"] == "blocked"+ assert "different account" in out["reason"]+ assert broker.order_calls == []+++def test_gate_accepts_an_order_naming_the_bound_account_without_duplicating_it(live_runtime: Path) -> None:+ _write_mandate(live_runtime, _bound_mandate())+ broker = _GateBroker()++ out = _order(_guard(broker), account=ACCOUNT)++ assert out["status"] == "ok"+ assert broker.order_calls[0]["account_number"] == ACCOUNT+ assert "account" not in broker.order_calls[0]+++def test_gate_prices_held_positions_so_exposure_is_enforced(+ live_runtime: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # 20 AAPL at $200 = $4,000 already held; a $750 buy would take gross+ # exposure to $4,750 — inside a $5,000 cap, outside a $4,500 one.+ monkeypatch.setattr(order_guard, "last_price_usd", lambda symbol, asset_class: 200.0)+ held = [rh.position("AAPL", "20")]++ _write_mandate(live_runtime, _bound_mandate(max_total_exposure_usd=5000.0))+ broker = _GateBroker(positions=held)+ out = json.loads(+ _guard(broker).execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=750.0)+ )+ assert out["status"] == "ok", out++ _write_mandate(live_runtime, _bound_mandate(max_total_exposure_usd=4500.0))+ broker = _GateBroker(positions=held)+ out = json.loads(+ _guard(broker).execute(symbol="AAPL", side="buy", instrument_type="equity", notional_usd=750.0)+ )+ assert out["status"] == "blocked"+ assert out["breach"]["limit"] == "max_total_exposure_usd"+ assert out["breach"]["attempted_value"] == 4750.0+++def test_gate_fails_closed_when_a_held_position_cannot_be_priced(+ live_runtime: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(order_guard, "last_price_usd", lambda symbol, asset_class: None)+ _write_mandate(live_runtime, _bound_mandate())+ broker = _GateBroker(positions=[rh.position("MSFT", "3")])++ out = _order(_guard(broker))++ assert out["status"] == "blocked"+ assert "current positions could not be read" in out["breach"]["detail"]+ assert broker.order_calls == []+++def test_gate_fails_closed_on_a_first_page_of_positions(live_runtime: Path) -> None:+ _write_mandate(live_runtime, _bound_mandate())+ broker = _GateBroker()+ broker.positions = rh.positions([rh.position("AAPL", "1")], next_page="cursor-2")++ out = _order(_guard(broker))++ assert out["status"] == "blocked"+ assert broker.order_calls == []+++# --------------------------------------------------------------------------- #+# Runner #+# --------------------------------------------------------------------------- #+++class _SessionService:+ session_id = "live-sess"+ event_bus = SimpleNamespace(emit=lambda *a, **k: None)++ def create_session(self, title=""):+ return self++ async def send_message(self, sid, content, **kw):+ return {"message_id": "m1", "attempt_id": "a1"}+++class _RunnerBroker:+ def __init__(self) -> None:+ self.calls: list[tuple[str, dict]] = []++ def call_tool(self, name: str, args: dict) -> dict:+ self.calls.append((name, dict(args)))+ if name == "get_equity_positions":+ return rh.positions([rh.position("NVDA", "3")])+ if name == "get_equity_orders":+ return rh.envelope("get_equity_orders", {"orders": []})+ if name == "get_portfolio":+ return rh.portfolio()+ return {"status": "ok"}+++def _runner(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, broker: _RunnerBroker, account: dict):+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)+ monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)+ monkeypatch.setattr(api_server, "_live_broker_adapter", lambda name: broker)+ monkeypatch.setattr(api_server, "_get_session_service", lambda: _SessionService())+ monkeypatch.setattr(api_server, "_mandate_account_ref", lambda name: account["ref"])+ return api_server._build_live_runner("robinhood")+++def test_runner_refuses_to_build_for_a_mandate_without_an_account(tmp_path, monkeypatch) -> None:+ with pytest.raises(api_server.LiveRunnerUnavailable, match="not bound to an account"):+ _runner(tmp_path, monkeypatch, _RunnerBroker(), {"ref": ""})+++def test_runner_reads_and_submits_for_the_current_mandate_account(tmp_path, monkeypatch) -> None:+ broker = _RunnerBroker()+ account = {"ref": ACCOUNT}+ runner = _runner(tmp_path, monkeypatch, broker, account)++ runner._read_positions()+ runner._submit_fn({"action": "close", "symbol": "NVDA", "side": "sell", "qty": 3.0, "account_number": "OTHER"})+ account["ref"] = "5QR77777" # re-committed to another account while running+ runner._read_balance()++ assert broker.calls == [+ ("get_equity_positions", {"account_number": ACCOUNT}),+ (+ "place_equity_order",+ {"action": "close", "symbol": "NVDA", "side": "sell", "qty": 3.0, "account_number": ACCOUNT},+ ),+ ("get_portfolio", {"account_number": "5QR77777"}),+ ]+++def test_runner_stops_calling_the_broker_once_the_account_is_gone(tmp_path, monkeypatch) -> None:+ broker = _RunnerBroker()+ account = {"ref": ACCOUNT}+ runner = _runner(tmp_path, monkeypatch, broker, account)+ account["ref"] = ""++ with pytest.raises(RuntimeError, match="not bound to an account"):+ runner._read_open_orders()+ assert broker.calls == []+++def test_runner_positions_carry_qty_for_the_halt_sweep(tmp_path, monkeypatch) -> None:+ runner = _runner(tmp_path, monkeypatch, _RunnerBroker(), {"ref": ACCOUNT})++ assert runner._read_positions()[0]["qty"] == "3"+++# --------------------------------------------------------------------------- #+# Commit + account listing #+# --------------------------------------------------------------------------- #+++class _CommitBroker:+ def __init__(self, accounts: list[dict]) -> None:+ self.accounts = accounts+ self.calls: list[tuple[str, dict]] = []++ def call_tool(self, name: str, args: dict) -> dict:+ self.calls.append((name, dict(args)))+ if name == "get_accounts":+ return rh.accounts(self.accounts)+ if name == "get_portfolio":+ return rh.portfolio(buying_power="5000.00")+ raise AssertionError(f"unexpected tool {name}")+++def _commit_client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, broker: _CommitBroker) -> TestClient:+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)+ monkeypatch.setattr(api_server, "_live_broker_adapter", lambda name: broker)+ return TestClient(api_server.app, client=("127.0.0.1", 50000))+++def _proposal_id() -> str:+ raw = ProposeMandateProfilesTool().execute(+ broker="robinhood",+ ceilings={+ "account_funding_usd": 5000.0,+ "max_order_usd": 1500.0,+ "max_total_exposure_usd": 5000.0,+ "daily_trade_cap": 10,+ "leverage": "none",+ "instruments": ["equity"],+ },+ )+ return json.loads(raw)["proposal_id"]+++def _commit(client: TestClient, account_ref: str) -> Any:+ return client.post(+ "/mandate/commit",+ json={+ "broker": "robinhood",+ "proposal_id": _proposal_id(),+ "selected_ordinal": 1,+ "consent_ack": True,+ "account_ref": account_ref,+ },+ )+++def test_commit_binds_the_mandate_to_a_listed_agentic_account(tmp_path, monkeypatch) -> None:+ broker = _CommitBroker([rh.account(ACCOUNT, nickname="Main")])+ client = _commit_client(tmp_path, monkeypatch, broker)++ response = _commit(client, ACCOUNT)++ assert response.status_code == 200, response.text+ assert load_mandate("robinhood").consent.account_ref == ACCOUNT+ assert broker.calls == [("get_accounts", {}), ("get_portfolio", {"account_number": ACCOUNT})]+++ ("accounts", "account_ref", "detail"),+ [+ ([rh.account(ACCOUNT)], "", "choose the robinhood account"),+ ([rh.account("5QR00009")], ACCOUNT, "not one of the accounts"),+ ([rh.account(ACCOUNT, deactivated=True)], ACCOUNT, "deactivated"),+ ([rh.account(ACCOUNT, agentic_allowed=False)], ACCOUNT, "does not allow agentic trading"),+ ],+)+def test_commit_refuses_an_account_the_mandate_cannot_trade(+ tmp_path, monkeypatch, accounts: list, account_ref: str, detail: str+) -> None:+ client = _commit_client(tmp_path, monkeypatch, _CommitBroker(accounts))++ response = _commit(client, account_ref)++ assert response.status_code == 400+ assert detail in response.json()["detail"]+ assert load_mandate("robinhood") is None+++def test_commit_reports_an_unreadable_account_list_as_503(tmp_path, monkeypatch) -> None:+ broker = _CommitBroker([])+ broker.call_tool = lambda name, args: {"status": "error", "error": "token expired"} # type: ignore[method-assign]+ client = _commit_client(tmp_path, monkeypatch, broker)++ response = _commit(client, ACCOUNT)++ assert response.status_code == 503+ assert "token expired" in response.json()["detail"]+ assert load_mandate("robinhood") is None+++def test_live_accounts_route_says_which_brokers_bind_an_account(tmp_path, monkeypatch) -> None:+ broker = _CommitBroker([rh.account(ACCOUNT, is_default=True)])+ client = _commit_client(tmp_path, monkeypatch, broker)++ listed = client.get("/live/accounts", params={"broker": "robinhood"})+ unbound = client.get("/live/accounts", params={"broker": "ibkr"})++ assert listed.status_code == 200+ assert listed.json()["account_selection_required"] is True+ assert listed.json()["accounts"][0]["account_ref"] == ACCOUNT+ assert unbound.json() == {"status": "ok", "broker": "ibkr", "account_selection_required": False, "accounts": []}+ assert broker.calls == [("get_accounts", {})]diff --git a/agent/tests/test_robinhood_mcp_mapping.py b/agent/tests/test_robinhood_mcp_mapping.pynew file mode 100644index 000000000..46c5497d2--- /dev/null+++ b/agent/tests/test_robinhood_mcp_mapping.py@@ -0,0 +1,212 @@+"""Robinhood reply mapping (#1428 / #1442): the one place that reads the nested shape.++Fixtures come from ``tests/robinhood_mcp_helpers.py``, which reproduces the+shapes posted on #1428. Each rejection case is a way a reply could be read as+something it is not: a first page as the whole account, a null list as an empty+account, an omitted cost as zero.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from src.trading import service+from src.trading.connectors.robinhood import mcp+from tests import robinhood_mcp_helpers as rh++pytestmark = pytest.mark.unit+++def test_portfolio_summary_reads_the_nested_data_object() -> None:+ summary = mcp.portfolio_summary(rh.portfolio(total_value="1234.50", cash="200.00", buying_power="180.25"))++ assert summary == {+ "portfolio_value": "1234.50",+ "cash": "200.00",+ "buying_power": "180.25",+ "currency": "USD",+ "non_equity_values": {field: "0.00" for field in mcp.NON_EQUITY_VALUE_FIELDS},+ }+++ ("override", "message"),+ [+ ({"total_value": None}, "total_value is missing"),+ ({"total_value": "n/a"}, "total_value is not a number"),+ ({"total_value": "NaN"}, "total_value is not finite"),+ ({"currency": ""}, "currency is missing"),+ ],+)+def test_portfolio_summary_refuses_a_missing_or_unreadable_total(override: dict, message: str) -> None:+ envelope = rh.portfolio()+ envelope["structured_content"]["data"].update(override)++ with pytest.raises(mcp.RobinhoodShapeError, match=message):+ mcp.portfolio_summary(envelope)+++def test_an_omitted_non_equity_value_is_unknown_not_zero() -> None:+ envelope = rh.portfolio()+ del envelope["structured_content"]["data"]["crypto_value"]++ assert mcp.portfolio_summary(envelope)["non_equity_values"]["crypto_value"] is None+++def test_position_rows_map_symbol_quantity_and_cost() -> None:+ rows = mcp.position_rows(+ rh.positions(+ [+ rh.position("aapl", "10.5", average_buy_price="150.25"),+ rh.position("MSFT", "2", average_buy_price=None),+ ]+ )+ )++ assert rows == [+ {"symbol": "AAPL", "quantity": "10.5", "average_cost": "150.25", "broker_type": "unobserved"},+ {"symbol": "MSFT", "quantity": "2", "average_cost": None, "broker_type": "unobserved"},+ ]+++def test_an_empty_position_list_is_a_complete_empty_account() -> None:+ assert mcp.position_rows(rh.positions([])) == []+ assert mcp.position_rows(rh.positions([], next_page="")) == []+++ ("envelope", "message"),+ [+ (rh.positions(None), "no positions list"),+ (rh.positions([None]), r"positions\[0\] is not an object"),+ (rh.positions([rh.position("AAPL", "1")], next_page="cursor-2"), "more than one page"),+ (rh.envelope("get_equity_positions", {"positions": [], "total": "3"}), "unmapped data keys: total"),+ (rh.positions([{**rh.position("AAPL", "1"), "symbol": ""}]), "has no symbol"),+ (rh.positions([{**rh.position("AAPL", "1"), "quantity": "lots"}]), "quantity is not a number"),+ ({"status": "ok", "structured_content": {"guide": "no data"}}, "no data object"),+ ({"status": "error", "error": "token expired"}, "token expired"),+ ],+)+def test_position_rows_refuse_what_is_not_a_whole_account(envelope: dict, message: str) -> None:+ with pytest.raises(mcp.RobinhoodShapeError, match=message):+ mcp.position_rows(envelope)+++def test_account_choices_keep_only_what_a_picker_shows() -> None:+ choices = mcp.account_choices(+ rh.accounts(+ [+ rh.account("5QR12345", nickname="Main", is_default=True),+ rh.account("5QR99887", agentic_allowed=False),+ {**rh.account("5QR55555"), "permanently_deactivated": True},+ ]+ )+ )++ assert choices == [+ {+ "account_ref": "5QR12345",+ "label": "Main ····2345",+ "is_default": True,+ "agentic_allowed": True,+ "deactivated": False,+ },+ {+ "account_ref": "5QR99887",+ "label": "individual ····9887",+ "is_default": False,+ "agentic_allowed": False,+ "deactivated": False,+ },+ {+ "account_ref": "5QR55555",+ "label": "individual ····5555",+ "is_default": False,+ "agentic_allowed": True,+ "deactivated": True,+ },+ ]+++def test_account_choices_refuse_an_account_without_a_number() -> None:+ with pytest.raises(mcp.RobinhoodShapeError, match="has no account_number"):+ mcp.account_choices(rh.accounts([{**rh.account("5QR1"), "account_number": None}]))+++def test_normalize_result_adds_the_view_and_keeps_the_raw_reply() -> None:+ envelope = rh.positions([rh.position("AAPL", "1")])++ normalized = mcp.normalize_result("positions", envelope)++ assert normalized["positions"][0]["symbol"] == "AAPL"+ assert normalized["structured_content"] is envelope["structured_content"]+ assert "mapping_error" not in normalized+ assert "positions" not in envelope # the caller's reply is not mutated+++def test_normalize_result_marks_an_unmappable_reply_instead_of_failing_the_read() -> None:+ normalized = mcp.normalize_result("positions", rh.positions([rh.position("AAPL", "1")], next_page="p2"))++ assert normalized["status"] == "ok"+ assert "positions" not in normalized+ assert "more than one page" in normalized["mapping_error"]+++def test_normalize_result_leaves_error_envelopes_and_other_operations_alone() -> None:+ error = {"status": "error", "error": "boom"}+ quote = {"status": "ok", "data": {"anything": 1}}++ assert mcp.normalize_result("positions", error) is error+ assert mcp.normalize_result("quote", quote) is quote+++def test_account_scoped_operations_send_account_number_and_accounts_sends_nothing() -> None:+ assert mcp.remote_arguments("positions", {"account": "5QR1"}) == {"account_number": "5QR1"}+ assert mcp.remote_arguments("account", {"account_number": "5QR1"}) == {"account_number": "5QR1"}+ assert mcp.remote_arguments("orders", {}) == {}+ assert mcp.remote_arguments("accounts", {"account": "5QR1"}) == {}+++def test_trading_service_lists_accounts_through_get_accounts(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[tuple[str, dict]] = []+ server = SimpleNamespace(+ url="https://agent.robinhood.com/mcp/trading",+ enabled_tools=["get_accounts"],+ auth=SimpleNamespace(cache_dir="/tmp/vibe-token"),+ )++ class _Adapter:+ def __init__(self, server_name, server_config, **kwargs): # noqa: ANN001+ assert kwargs == {"interactive_oauth": False}++ def call_tool(self, remote_name, arguments): # noqa: ANN001+ calls.append((remote_name, dict(arguments)))+ return rh.accounts([rh.account("5QR12345", nickname="Main")])++ monkeypatch.setattr(+ "src.config.loader.load_agent_config", lambda: SimpleNamespace(mcp_servers={"robinhood": server})+ )+ monkeypatch.setattr("src.live.registry.has_cached_oauth_token", lambda *_: True)+ monkeypatch.setattr("src.tools.mcp.MCPServerAdapter", _Adapter)++ result = service.get_accounts("robinhood-live-mcp-readonly", interactive_oauth=False)++ assert calls == [("get_accounts", {})]+ assert result["accounts"][0]["account_ref"] == "5QR12345"+ assert result["profile_id"] == "robinhood-live-mcp-readonly"+++def test_accounts_are_unsupported_off_remote_mcp() -> None:+ result = service.get_accounts("ibkr-paper-local")++ assert result["status"] == "error"+ assert "accounts.read" in result["error"]+++def test_the_trading_profile_stays_first_for_the_broker_on_ramp() -> None:+ assert service.connector_profile_id_for_broker("robinhood") == "robinhood-live-mcp"+ assert service.live_runner_profile_for_broker("robinhood").id == "robinhood-live-mcp"+ assert service.runner_requires_account("robinhood") is True+ assert service.runner_requires_account("ibkr") is Falsediff --git a/agent/tests/test_robinhood_portfolio_source.py b/agent/tests/test_robinhood_portfolio_source.pynew file mode 100644index 000000000..f5ffc6e48--- /dev/null+++ b/agent/tests/test_robinhood_portfolio_source.py@@ -0,0 +1,283 @@+"""Read-only Robinhood portfolio source (#1428), end to end through the real read path.++``PortfolioService`` uses its default readers here, so a refresh goes through+``trading.service`` → the Robinhood mapping → the portfolio contract. Only the+MCP adapter is stubbed, and it answers with the shapes posted on #1428.+"""++from __future__ import annotations++from decimal import Decimal+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from src.api import connection_routes+from src.portfolio.config import PortfolioSettingsStore+from src.portfolio.service import PortfolioService+from src.portfolio.store import PortfolioStore+from src.trading.connections import ConnectionStore, is_portfolio_connection_profile+from src.trading.profiles import profile_by_id+from tests import robinhood_mcp_helpers as rh++pytestmark = pytest.mark.unit++ACCOUNT = "5QR12345"+++class _Broker:+ """Records every MCP call and answers with the configured replies."""++ def __init__(self) -> None:+ self.calls: list[tuple[str, dict]] = []+ self.replies: dict[str, dict] = {+ "get_accounts": rh.accounts([rh.account(ACCOUNT, nickname="Main"), rh.account("5QR00009")]),+ "get_portfolio": rh.portfolio(total_value="1500.00", cash="500.00"),+ "get_equity_positions": rh.positions([]),+ }++ def adapter_class(self):+ broker = self++ class _Adapter:+ def __init__(self, server_name, server_config, **kwargs): # noqa: ANN001+ assert server_name == "robinhood"+ assert kwargs.get("interactive_oauth") is False++ def call_tool(self, remote_name, arguments): # noqa: ANN001+ broker.calls.append((remote_name, dict(arguments)))+ return broker.replies[remote_name]++ return _Adapter+++def broker(monkeypatch: pytest.MonkeyPatch) -> _Broker:+ fake = _Broker()+ server = SimpleNamespace(+ url="https://agent.robinhood.com/mcp/trading",+ enabled_tools=["get_accounts", "get_portfolio", "get_equity_positions", "get_equity_quotes"],+ auth=SimpleNamespace(cache_dir="/tmp/vibe-token"),+ )+ monkeypatch.setattr(+ "src.config.loader.load_agent_config", lambda: SimpleNamespace(mcp_servers={"robinhood": server})+ )+ monkeypatch.setattr("src.live.registry.has_cached_oauth_token", lambda *_: True)+ monkeypatch.setattr("src.tools.mcp.MCPServerAdapter", fake.adapter_class())+ return fake+++def _service(tmp_path, *, account_ref: str = ACCOUNT) -> PortfolioService:+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")+ settings.connection_store.ensure("robinhood-live", "robinhood-live-mcp-readonly", "Robinhood")+ if account_ref:+ settings.connection_store.select_account("robinhood-live", account_ref)+ settings.save({"display_currency": "USD", "sources": [{"connection_id": "robinhood-live", "label": "Robinhood"}]})+ return PortfolioService(+ PortfolioStore(tmp_path / "portfolio.sqlite3"),+ settings_store=settings,+ fx_fetcher=lambda: (Decimal("7.2"), Decimal("7.8"), "2026-09-17T00:00:00+00:00"),+ )+++def test_only_the_readonly_profile_can_back_a_portfolio_connection() -> None:+ assert is_portfolio_connection_profile(profile_by_id("robinhood-live-mcp-readonly")) is True+ assert is_portfolio_connection_profile(profile_by_id("robinhood-live-mcp")) is False+++def test_a_source_without_a_selected_account_errors_before_any_call(tmp_path, broker: _Broker) -> None:+ snapshot = _service(tmp_path, account_ref="").refresh()++ account = snapshot["accounts"][0]+ assert account["status"] == "error"+ assert "Select a robinhood account" in account["error"]+ assert snapshot["complete"] is False+ assert broker.calls == []+++def test_an_empty_account_is_a_complete_snapshot_read_for_the_selected_account(tmp_path, broker: _Broker) -> None:+ snapshot = _service(tmp_path).refresh()++ account = snapshot["accounts"][0]+ assert snapshot["complete"] is True+ assert account["status"] == "ok"+ assert account["total_usd"] == 1500.0+ assert account["cash_usd"] == 500.0+ assert broker.calls == [+ ("get_portfolio", {"account_number": ACCOUNT}),+ ("get_equity_positions", {"account_number": ACCOUNT}),+ ]+++def test_positions_are_listed_unpriced_and_quotes_are_never_called(tmp_path, broker: _Broker) -> None:+ broker.replies["get_portfolio"] = rh.portfolio(total_value="2500.00", cash="500.00")+ broker.replies["get_equity_positions"] = rh.positions(+ [+ rh.position("AAPL", "4", average_buy_price="150.00"),+ rh.position("MSFT", "2", average_buy_price=None),+ ]+ )++ snapshot = _service(tmp_path).refresh()++ rows = {row["symbol"]: row for row in snapshot["positions"]}+ assert rows["AAPL"]["quantity"] == 4.0+ assert rows["AAPL"]["cost_price"] == 150.0+ assert rows["MSFT"]["cost_price"] is None # omitted while reconciling, never zero+ assert all(row["market_price"] is None for row in rows.values())+ assert all("quotes are not mapped" in row["price_error"] for row in rows.values())+ assert snapshot["accounts"][0]["total_usd"] == 2500.0+ assert snapshot["accounts"][0]["unpriced_or_other_usd"] == 2000.0+ assert any("No price available" in warning for warning in snapshot["warnings"])+ assert "get_equity_quotes" not in [name for name, _ in broker.calls]++[email protected]("field", ["options_value", "crypto_value", "futures_value", "fixed_income_value"])+def test_holdings_outside_equities_fail_the_source_instead_of_shortening_it(+ tmp_path, broker: _Broker, field: str+) -> None:+ broker.replies["get_portfolio"] = rh.portfolio(total_value="3000.00", **{field: "125.00"})+ broker.replies["get_equity_positions"] = rh.positions([rh.position("AAPL", "1")])++ snapshot = _service(tmp_path).refresh()++ account = snapshot["accounts"][0]+ assert account["status"] == "error"+ assert field in account["error"]+ assert account["total_usd"] is None+ assert snapshot["positions"] == []+ assert snapshot["complete"] is False+++def test_an_unreported_non_equity_value_is_not_read_as_zero(tmp_path, broker: _Broker) -> None:+ envelope = rh.portfolio()+ del envelope["structured_content"]["data"]["event_contracts_value"]+ broker.replies["get_portfolio"] = envelope++ account = _service(tmp_path).refresh()["accounts"][0]++ assert account["status"] == "error"+ assert "did not report event_contracts_value" in account["error"]+++ ("reply", "message"),+ [+ (rh.positions([rh.position("AAPL", "1")], next_page="cursor-2"), "more than one page"),+ (rh.positions(None), "no positions list"),+ (rh.positions([None]), "is not an object"),+ ],+)+def test_a_partial_or_null_position_read_is_an_error_not_an_empty_account(+ tmp_path, broker: _Broker, reply: dict, message: str+) -> None:+ broker.replies["get_equity_positions"] = reply++ account = _service(tmp_path).refresh()["accounts"][0]++ assert account["status"] == "error"+ assert message in account["error"]+++def test_a_missing_total_value_is_an_error_not_a_zero_account(tmp_path, broker: _Broker) -> None:+ envelope = rh.portfolio()+ del envelope["structured_content"]["data"]["total_value"]+ broker.replies["get_portfolio"] = envelope++ account = _service(tmp_path).refresh()["accounts"][0]++ assert account["status"] == "error"+ assert "total_value is missing" in account["error"]+++def test_the_connection_store_refuses_an_account_on_a_profile_that_takes_none(tmp_path) -> None:+ store = ConnectionStore(tmp_path / "connections.json")+ store.ensure("ibkr", "ibkr-live-local-readonly", "IBKR")++ with pytest.raises(ValueError, match="does not take an account"):+ store.select_account("ibkr", "U1234")+++def test_the_connection_store_refuses_a_control_character_in_an_account(tmp_path) -> None:+ store = ConnectionStore(tmp_path / "connections.json")+ store.ensure("robinhood-live", "robinhood-live-mcp-readonly", "Robinhood")++ with pytest.raises(ValueError, match="printable"):+ store.select_account("robinhood-live", "5QR\n1")+++def _client(tmp_path, monkeypatch: pytest.MonkeyPatch) -> tuple[TestClient, ConnectionStore]:+ store = ConnectionStore(tmp_path / "connections.json")+ store.ensure("robinhood-live", "robinhood-live-mcp-readonly", "Robinhood")+ monkeypatch.setattr(connection_routes, "ConnectionStore", lambda: store)+ monkeypatch.setattr(connection_routes, "require_auth", lambda: None)+ monkeypatch.setattr(connection_routes, "require_settings_write_auth", lambda: None)+ app = FastAPI()+ connection_routes.register_connection_routes(app)+ return TestClient(app), store+++def test_accounts_route_lists_the_login_accounts(tmp_path, monkeypatch, broker: _Broker) -> None:+ client, _ = _client(tmp_path, monkeypatch)++ response = client.get("/api/connections/robinhood-live/accounts")++ assert response.status_code == 200+ body = response.json()+ assert [row["account_ref"] for row in body["accounts"]] == [ACCOUNT, "5QR00009"]+ assert body["account_ref"] == ""+ assert broker.calls == [("get_accounts", {})]+++ ("accounts", "status", "detail"),+ [+ ([rh.account("5QR00009")], 400, "not one of the accounts"),+ ([rh.account(ACCOUNT, deactivated=True)], 400, "deactivated"),+ ],+)+def test_selecting_an_account_the_login_cannot_use_is_refused(+ tmp_path, monkeypatch, broker: _Broker, accounts: list, status: int, detail: str+) -> None:+ broker.replies["get_accounts"] = rh.accounts(accounts)+ client, store = _client(tmp_path, monkeypatch)++ response = client.put("/api/connections/robinhood-live/account", json={"account_ref": ACCOUNT})++ assert response.status_code == status+ assert detail in response.json()["detail"]+ assert store.get("robinhood-live").account_ref == ""+++def test_selecting_clearing_and_renaming_keep_the_account_where_it_belongs(+ tmp_path, monkeypatch, broker: _Broker+) -> None:+ client, store = _client(tmp_path, monkeypatch)++ assert client.put("/api/connections/robinhood-live/account", json={"account_ref": ACCOUNT}).status_code == 200+ assert store.get("robinhood-live").account_ref == ACCOUNT++ renamed = client.put(+ "/api/connections/robinhood-live",+ json={"id": "robinhood-live", "profile_id": "robinhood-live-mcp-readonly", "label": "RH main"},+ )+ assert renamed.status_code == 200+ assert store.get("robinhood-live").label == "RH main"+ assert store.get("robinhood-live").account_ref == ACCOUNT++ calls_before_clear = len(broker.calls)+ assert client.put("/api/connections/robinhood-live/account", json={"account_ref": ""}).status_code == 200+ assert store.get("robinhood-live").account_ref == ""+ assert len(broker.calls) == calls_before_clear # clearing needs no broker read+++def test_accounts_route_reports_an_unavailable_broker_as_503(tmp_path, monkeypatch, broker: _Broker) -> None:+ broker.replies["get_accounts"] = {"status": "error", "error": "token expired"}+ client, _ = _client(tmp_path, monkeypatch)++ response = client.get("/api/connections/robinhood-live/accounts")++ assert response.status_code == 503+ assert "token expired" in response.json()["detail"]diff --git a/frontend/src/components/chat/MandateProposalCard.tsx b/frontend/src/components/chat/MandateProposalCard.tsxindex 716d3d93c..334cc02f9 100644--- a/frontend/src/components/chat/MandateProposalCard.tsx+++ b/frontend/src/components/chat/MandateProposalCard.tsx@@ -1,8 +1,8 @@import i18n from '@/i18n';-import { memo, useCallback, useState } from "react";+import { memo, useCallback, useEffect, useState } from "react";import { ShieldCheck, ShieldAlert, Wallet, OctagonX, SlidersHorizontal, Check, X, Loader2 } from "lucide-react";import { toast } from "sonner";-import { api, type MandateProfile, type MandateProposal } from "@/lib/api";+import { api, type BrokerAccountChoice, type MandateProfile, type MandateProposal } from "@/lib/api";import { AgentAvatar } from "./AgentAvatar";import { ConfirmDialog } from "@/components/common/ConfirmDialog";@@ -195,15 +195,43 @@ function ProfileTile({* never `api.sendMessage`. "Adjust" sends a natural-language message back to the agent* to re-render a fresh proposal. Once committed, the card collapses to a compact badge.*/+type AccountOptions =+ | { status: "idle" | "loading" }+ | { status: "ready"; required: boolean; accounts: BrokerAccountChoice[] }+ | { status: "error"; error: string };+export const MandateProposalCard = memo(function MandateProposalCard({ proposal, committed, onAdjust }: Props) {const [busyOrdinal, setBusyOrdinal] = useState<number | null>(null);const [adjustingOrdinal, setAdjustingOrdinal] = useState<number | null>(null);const [pendingOrdinal, setPendingOrdinal] = useState<number | null>(null);+ const [accountOptions, setAccountOptions] = useState<AccountOptions>({ status: "idle" });+ const [accountRef, setAccountRef] = useState("");+ const broker = proposal.account?.broker?.trim().toLowerCase() ?? "";++ // The account is chosen by the user in the confirm step, from the broker's own+ // list. The proposal (written by the agent) never carries one, and nothing is+ // preselected: a mandate must not silently bind to the broker's default account.+ useEffect(() => {+ if (pendingOrdinal == null || !broker || accountOptions.status !== "idle") return;+ setAccountOptions({ status: "loading" });+ api.getLiveAccounts(broker)+ .then((result) => setAccountOptions({+ status: "ready",+ required: result.account_selection_required,+ accounts: result.accounts,+ }))+ .catch((error) => setAccountOptions({+ status: "error",+ error: error instanceof Error ? error.message : String(error),+ }));+ }, [pendingOrdinal, broker, accountOptions.status]);++ const accountRequired = accountOptions.status === "ready" && accountOptions.required;+ const accountReady = accountOptions.status === "ready" && (!accountOptions.required || Boolean(accountRef));const handleCommit = useCallback(- async (ordinal: number) => {+ async (ordinal: number, selectedAccount: string) => {if (busyOrdinal != null) return;- const broker = proposal.account?.broker?.trim().toLowerCase();if (!broker) {toast.error(i18n.t("mandate.noBroker"));return;@@ -217,6 +245,7 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,adjustments: null,consent_ack: true,session_id: proposal.session_id,+ ...(selectedAccount ? { account_ref: selectedAccount } : {}),});// Card collapses to the active-mandate badge when the mandate.committed// SSE event arrives; no optimistic state-write here.@@ -225,7 +254,7 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,toast.error(error instanceof Error ? error.message : i18n.t("mandate.failedToCommit"));}},- [busyOrdinal, proposal.account?.broker, proposal.proposal_id, proposal.session_id],+ [busyOrdinal, broker, proposal.proposal_id, proposal.session_id],);const pendingProfile = proposal.profiles.find((p) => p.ordinal === pendingOrdinal) ?? null;@@ -350,13 +379,57 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,confirmLabel={i18n.t("mandate.confirmButton")}cancelLabel={i18n.t("mandate.cancel")}tone="destructive"- onCancel={() => setPendingOrdinal(null)}+ confirmDisabled={!accountReady}+ onCancel={() => {+ setPendingOrdinal(null);+ // A failed account read is retried the next time the dialog opens.+ if (accountOptions.status === "error") setAccountOptions({ status: "idle" });+ }}onConfirm={() => {const ordinal = pendingOrdinal;+ if (ordinal == null || !accountReady) return;setPendingOrdinal(null);- if (ordinal != null) handleCommit(ordinal);+ handleCommit(ordinal, accountRequired ? accountRef : "");}}>+ {accountOptions.status === "loading" && (+ <p className="mb-2 flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin" />+ {i18n.t("mandate.accountLoading")}+ </p>+ )}+ {accountOptions.status === "error" && (+ <p role="alert" className="mb-2 break-words text-[11px] text-destructive">+ {i18n.t("mandate.accountLoadFailed", { error: accountOptions.error })}+ </p>+ )}+ {accountOptions.status === "ready" && accountOptions.required && (+ <label className="mb-2 block text-[11px] text-muted-foreground">+ {i18n.t("mandate.accountLabel")}+ <select+ value={accountRef}+ onChange={(event) => setAccountRef(event.target.value)}+ className="mt-1 w-full rounded-lg border bg-background px-2 py-1.5 text-xs text-foreground"+ >+ <option value="">{i18n.t("mandate.accountChoose")}</option>+ {accountOptions.accounts.map((account) => {+ const unusable = account.deactivated || !account.agentic_allowed;+ return (+ <option key={account.account_ref} value={account.account_ref} disabled={unusable}>+ {account.label}+ {account.is_default ? i18n.t("mandate.accountDefault") : ""}+ {account.deactivated+ ? i18n.t("mandate.accountDeactivated")+ : !account.agentic_allowed+ ? i18n.t("mandate.accountNotAgentic")+ : ""}+ </option>+ );+ })}+ </select>+ <span className="mt-1 block">{i18n.t("mandate.accountHint")}</span>+ </label>+ )}{pendingProfile && (<dl className="grid grid-cols-2 gap-x-3 gap-y-1.5 rounded-lg border bg-muted/20 p-2.5 text-[11px]"><div className="col-span-2">diff --git a/frontend/src/components/chat/__tests__/MandateProposalCard.test.tsx b/frontend/src/components/chat/__tests__/MandateProposalCard.test.tsxnew file mode 100644index 000000000..d31d3f8a9--- /dev/null+++ b/frontend/src/components/chat/__tests__/MandateProposalCard.test.tsx@@ -0,0 +1,109 @@+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { MandateProposalCard } from "@/components/chat/MandateProposalCard";+import { api, type MandateProposal } from "@/lib/api";+import i18n from "@/i18n";++vi.mock("@/lib/api", async () => {+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");+ return {+ ...actual,+ api: {+ ...actual.api,+ getLiveAccounts: vi.fn(),+ commitMandate: vi.fn(),+ },+ };+});++const mocked = api as unknown as {+ getLiveAccounts: ReturnType<typeof vi.fn>;+ commitMandate: ReturnType<typeof vi.fn>;+};++function proposal(broker: string): MandateProposal {+ return {+ type: "mandate.proposal",+ proposal_id: `mp_${"a".repeat(32)}`,+ session_id: "sess-1",+ intent_normalized: "tech, ~$5000",+ account: { broker, type: "cash", funded_by: "user" },+ ceilings_ref: "caps_1",+ profiles: [+ { ordinal: 1, label: "Steady", universe: ["AAPL"], max_order_usd: 250, daily_trade_cap: 2, leverage: "none", instruments: ["equity"] },+ ],+ } as MandateProposal;+}++function openConfirm() {+ fireEvent.click(screen.getByRole("button", { name: i18n.t("mandate.commit", { label: "Steady" }) }));+ return screen.getByRole("alertdialog");+}++describe("MandateProposalCard account binding", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocked.commitMandate.mockResolvedValue({ mandate_id: "m1", consent_record_id: "cr1" });+ });++ it("requires the user to pick the account and commits it", async () => {+ mocked.getLiveAccounts.mockResolvedValue({+ status: "ok",+ broker: "robinhood",+ account_selection_required: true,+ accounts: [+ { account_ref: "5QR12345", label: "Main ····2345", is_default: true, agentic_allowed: true, deactivated: false },+ { account_ref: "5QR99887", label: "IRA ····9887", is_default: false, agentic_allowed: false, deactivated: false },+ ],+ });+ render(<MandateProposalCard proposal={proposal("robinhood")} onAdjust={() => undefined} />);++ const dialog = openConfirm();+ const select = await within(dialog).findByLabelText(new RegExp(i18n.t("mandate.accountLabel")));+ const confirm = within(dialog).getByRole("button", { name: i18n.t("mandate.confirmButton") });++ expect(mocked.getLiveAccounts).toHaveBeenCalledWith("robinhood");+ expect(select).toHaveValue("");+ expect(confirm).toBeDisabled();+ expect(within(select).getByRole("option", { name: /IRA ····9887/ })).toBeDisabled();++ fireEvent.change(select, { target: { value: "5QR12345" } });+ expect(confirm).toBeEnabled();+ fireEvent.click(confirm);++ await waitFor(() => expect(mocked.commitMandate).toHaveBeenCalledWith(+ expect.objectContaining({ broker: "robinhood", selected_ordinal: 1, account_ref: "5QR12345", consent_ack: true }),+ ));+ });++ it("commits without an account for a broker that binds none", async () => {+ mocked.getLiveAccounts.mockResolvedValue({+ status: "ok",+ broker: "ibkr",+ account_selection_required: false,+ accounts: [],+ });+ render(<MandateProposalCard proposal={proposal("ibkr")} onAdjust={() => undefined} />);++ const dialog = openConfirm();+ const confirm = within(dialog).getByRole("button", { name: i18n.t("mandate.confirmButton") });+ await waitFor(() => expect(confirm).toBeEnabled());+ expect(within(dialog).queryByRole("combobox")).toBeNull();+ fireEvent.click(confirm);++ await waitFor(() => expect(mocked.commitMandate).toHaveBeenCalled());+ expect(mocked.commitMandate.mock.calls[0][0]).not.toHaveProperty("account_ref");+ });++ it("keeps commit disabled when the account list cannot be read", async () => {+ mocked.getLiveAccounts.mockRejectedValue(new Error("token expired"));+ render(<MandateProposalCard proposal={proposal("robinhood")} onAdjust={() => undefined} />);++ const dialog = openConfirm();++ expect(await within(dialog).findByRole("alert")).toHaveTextContent("token expired");+ expect(within(dialog).getByRole("button", { name: i18n.t("mandate.confirmButton") })).toBeDisabled();+ fireEvent.click(within(dialog).getByRole("button", { name: i18n.t("mandate.confirmButton") }));+ expect(mocked.commitMandate).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/components/common/ConfirmDialog.tsx b/frontend/src/components/common/ConfirmDialog.tsxindex 32ea5c00c..2e6ea1494 100644--- a/frontend/src/components/common/ConfirmDialog.tsx+++ b/frontend/src/components/common/ConfirmDialog.tsx@@ -11,6 +11,8 @@ interface ConfirmDialogProps {tone?: "primary" | "destructive";onConfirm: () => void;onCancel: () => void;+ /** Keeps the confirm button disabled until the dialog's content is complete. */+ confirmDisabled?: boolean;/** Extra summary content rendered between the description and the action buttons. */children?: ReactNode;}@@ -29,6 +31,7 @@ export function ConfirmDialog({tone = "primary",onConfirm,onCancel,+ confirmDisabled = false,children,}: ConfirmDialogProps) {const confirmRef = useRef<HTMLButtonElement>(null);@@ -110,8 +113,9 @@ export function ConfirmDialog({ref={confirmRef}type="button"onClick={onConfirm}+ disabled={confirmDisabled}className={[- "rounded-lg px-3 py-1.5 text-xs font-medium transition-opacity hover:opacity-90",+ "rounded-lg px-3 py-1.5 text-xs font-medium transition-opacity hover:opacity-90 disabled:opacity-40",tone === "destructive"? "bg-destructive text-destructive-foreground": "bg-primary text-primary-foreground",diff --git a/frontend/src/components/portfolio/ConnectionCenter.tsx b/frontend/src/components/portfolio/ConnectionCenter.tsxindex 2d912def6..8d8acad76 100644--- a/frontend/src/components/portfolio/ConnectionCenter.tsx+++ b/frontend/src/components/portfolio/ConnectionCenter.tsx@@ -1,8 +1,8 @@import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";-import { CheckCircle2, FolderCode, Loader2, PlugZap, Plus, ShieldCheck, Trash2, X } from "lucide-react";+import { CheckCircle2, FolderCode, Loader2, PlugZap, Plus, ShieldCheck, Trash2, Wallet, X } from "lucide-react";import { PortfolioCompatibilityBadge } from "@/components/portfolio/PortfolioCompatibilityBadge";-import { api, type ConnectionsResponse, type LocalConnection } from "@/lib/api";+import { api, type BrokerAccountChoice, type ConnectionsResponse, type LocalConnection } from "@/lib/api";interface Props {open: boolean;@@ -186,6 +186,7 @@ function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSavereturn <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}+ {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}@@ -193,6 +194,73 @@ function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSave</article>;}+/**+ * Picks the one broker account an account-scoped connection (Robinhood) reads.+ * The list comes from the broker; nothing is preselected, so a connection never+ * silently reads the broker's default account.+ */+function AccountSelector({ connection, busy, setBusy, setMessage, onSaved }: { connection: LocalConnection; busy: string | null; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void; onSaved: () => Promise<void> }) {+ const { t } = useTranslation();+ const [accounts, setAccounts] = useState<BrokerAccountChoice[] | null>(null);+ const [choice, setChoice] = useState("");+ const [error, setError] = useState<string | null>(null);+ const loading = busy === `accounts:${connection.id}`;+ const saving = busy === `account:${connection.id}`;++ async function loadAccounts() {+ setBusy(`accounts:${connection.id}`);+ setError(null);+ try {+ const result = await api.getConnectionAccounts(connection.id);+ setAccounts(result.accounts);+ setChoice("");+ } catch (reason) {+ setError(reason instanceof Error ? reason.message : String(reason));+ } finally {+ setBusy(null);+ }+ }++ async function save() {+ if (!choice) return;+ setBusy(`account:${connection.id}`);+ setError(null);+ setMessage(null);+ try {+ await api.selectConnectionAccount(connection.id, choice);+ setAccounts(null);+ setChoice("");+ await onSaved();+ setMessage(t("portfolio.connections.accountSaved"));+ } catch (reason) {+ setError(reason instanceof Error ? reason.message : String(reason));+ } finally {+ setBusy(null);+ }+ }++ return <div className="mt-4 rounded-md border bg-muted/20 p-3 text-xs">+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="font-medium text-foreground">{t("portfolio.connections.accountTitle")}</div>+ <p className={`mt-1 ${connection.account_ref ? "text-muted-foreground" : "text-warning"}`}>{connection.account_ref ? t("portfolio.connections.accountCurrent", { last4: connection.account_ref.slice(-4) }) : t("portfolio.connections.accountNone")}</p>+ </div>+ <button type="button" onClick={() => void loadAccounts()} disabled={loading} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40">{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Wallet className="h-3.5 w-3.5" />}{connection.account_ref ? t("portfolio.connections.accountChange") : t("portfolio.connections.accountLoad")}</button>+ </div>+ {accounts && !accounts.length ? <p className="mt-3 text-muted-foreground">{t("portfolio.connections.accountEmpty")}</p> : null}+ {accounts && accounts.length ? <div className="mt-3 flex flex-wrap items-end gap-2">+ <label className="min-w-0 flex-1 text-muted-foreground">{t("portfolio.connections.accountPicker")}+ <select value={choice} onChange={(event) => setChoice(event.target.value)} className={`mt-1 ${fieldClass}`}>+ <option value="">{t("portfolio.connections.accountChoose")}</option>+ {accounts.map((account) => <option key={account.account_ref} value={account.account_ref} disabled={account.deactivated}>{account.label}{account.is_default ? t("portfolio.connections.accountDefault") : ""}{account.deactivated ? t("portfolio.connections.accountDeactivated") : ""}</option>)}+ </select>+ </label>+ <button type="button" onClick={() => void save()} disabled={!choice || saving} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground disabled:opacity-40">{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="h-3.5 w-3.5" />}{t("portfolio.connections.accountSave")}</button>+ </div> : null}+ {error ? <div role="alert" className="mt-2 break-words text-danger">{error}</div> : null}+ </div>;+}+function SetupContract({ onboarding }: { onboarding: NonNullable<LocalConnection["onboarding"]> }) {const { t } = useTranslation();return <div className="mt-3 rounded-md border bg-muted/20 p-3 text-xs text-muted-foreground">diff --git a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsxnew file mode 100644index 000000000..a38c07418--- /dev/null+++ b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx@@ -0,0 +1,116 @@+import { 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";+import i18n from "@/i18n";++vi.mock("@/lib/api", async () => {+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");+ return {+ ...actual,+ api: {+ ...actual.api,+ getConnections: vi.fn(),+ getConnectionAccounts: vi.fn(),+ selectConnectionAccount: vi.fn(),+ },+ };+});++const mocked = api as unknown as {+ getConnections: ReturnType<typeof vi.fn>;+ getConnectionAccounts: ReturnType<typeof vi.fn>;+ selectConnectionAccount: ReturnType<typeof vi.fn>;+};++function robinhood(accountRef: string): LocalConnection {+ return {+ id: "robinhood-live",+ profile_id: "robinhood-live-mcp-readonly",+ label: "Robinhood",+ account_ref: accountRef,+ account_selection_required: true,+ connector: "robinhood",+ environment: "live",+ transport: "remote_mcp",+ readonly: true,+ capabilities: ["account.read", "positions.read"],+ supports_reconnect: true,+ credential_fields: [],+ credential_status: {},+ credentials_configured: false,+ portfolio_compatibility: { level: "experimental", contract_version: 1, asset_scope: "stocks_etfs", note: "" },+ };+}++function renderCenter(connection: LocalConnection, onChanged = vi.fn().mockResolvedValue(undefined)) {+ mocked.getConnections.mockResolvedValue({+ status: "ok",+ connections: [connection],+ profiles: [],+ plugin_directory: "/tmp/connectors",+ });+ render(<ConnectionCenter open onClose={() => undefined} onChanged={onChanged} />);+ return onChanged;+}++describe("ConnectionCenter account selection", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocked.getConnectionAccounts.mockResolvedValue({+ status: "ok",+ connection_id: "robinhood-live",+ account_ref: "",+ accounts: [+ { account_ref: "5QR12345", label: "Main ····2345", is_default: true, agentic_allowed: true, deactivated: false },+ { account_ref: "5QR55555", label: "Old ····5555", is_default: false, agentic_allowed: true, deactivated: true },+ ],+ });+ mocked.selectConnectionAccount.mockResolvedValue({ status: "ok", connection: robinhood("5QR12345") });+ });++ it("warns that an unscoped connection reads nothing", async () => {+ renderCenter(robinhood(""));++ expect(await screen.findByText(i18n.t("portfolio.connections.accountNone"))).toBeInTheDocument();+ });++ it("picks from the broker's list with nothing preselected and saves the choice", async () => {+ const onChanged = renderCenter(robinhood(""));++ fireEvent.click(await screen.findByRole("button", { name: i18n.t("portfolio.connections.accountLoad") }));+ const select = await screen.findByLabelText(i18n.t("portfolio.connections.accountPicker"));+ const save = screen.getByRole("button", { name: i18n.t("portfolio.connections.accountSave") });++ expect(select).toHaveValue("");+ expect(save).toBeDisabled();+ const deactivated = within(select).getByRole("option", { name: /Old ····5555/ });+ expect(deactivated).toBeDisabled();++ fireEvent.change(select, { target: { value: "5QR12345" } });+ expect(save).toBeEnabled();+ fireEvent.click(save);++ await waitFor(() => expect(mocked.selectConnectionAccount).toHaveBeenCalledWith("robinhood-live", "5QR12345"));+ await waitFor(() => expect(onChanged).toHaveBeenCalled());+ });++ it("shows the selected account by its last four digits", async () => {+ renderCenter(robinhood("5QR12345"));++ expect(+ await screen.findByText(i18n.t("portfolio.connections.accountCurrent", { last4: "2345" })),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: i18n.t("portfolio.connections.accountChange") })).toBeInTheDocument();+ });++ it("reports an account list the broker could not return", async () => {+ mocked.getConnectionAccounts.mockRejectedValue(new Error("token expired"));+ renderCenter(robinhood(""));++ fireEvent.click(await screen.findByRole("button", { name: i18n.t("portfolio.connections.accountLoad") }));++ expect(await screen.findByRole("alert")).toHaveTextContent("token expired");+ expect(mocked.selectConnectionAccount).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex bef6029d6..5b9dce532 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -1208,7 +1208,15 @@"maxPerOrder": "بحد أقصى {{amount}} لكل أمر","expiresOn": "ينتهي في {{date}}","accountSummary": "{{broker}} · حساب {{type}} · ممول من {{fundedBy}}",- "adjustRequestMessage": "لطلب تعديل اقتراح التفويض «{{label}}» (الخيار {{ordinal}}): {{text}}"+ "adjustRequestMessage": "لطلب تعديل اقتراح التفويض «{{label}}» (الخيار {{ordinal}}): {{text}}",+ "accountLoading": "جارٍ تحميل حسابات الوسيط…",+ "accountLoadFailed": "تعذّر تحميل حسابات الوسيط: {{error}}",+ "accountLabel": "الحساب الذي يمكن لهذا التفويض التداول فيه",+ "accountChoose": "اختر حسابًا",+ "accountDefault": " · الافتراضي لدى الوسيط",+ "accountDeactivated": " · معطّل",+ "accountNotAgentic": " · لا يُسمح بتداول الوكيل",+ "accountHint": "يتداول الوكيل في هذا الحساب فقط، ولن يُختار أي حساب نيابةً عنك."},"messageBubble": {"elapsedTime": "إجمالي وقت الاستجابة",@@ -1623,7 +1631,19 @@"testFailed": "فشل اختبار {{label}}: {{error}}","unknownTestError": "أرجع الموصل خطأ غير معروف.","delete": "حذف",- "configured": "بيانات الاعتماد المطلوبة مضبوطة"+ "configured": "بيانات الاعتماد المطلوبة مضبوطة",+ "accountTitle": "الحساب",+ "accountCurrent": "يقرأ الحساب المنتهي بـ ····{{last4}}",+ "accountNone": "لم يتم اختيار حساب. لن يقرأ هذا الاتصال أي بيانات حتى تختار حسابًا.",+ "accountLoad": "اختيار الحساب",+ "accountChange": "تغيير الحساب",+ "accountEmpty": "لا يصل تسجيل الدخول هذا إلى أي حساب.",+ "accountPicker": "الحسابات التي يصل إليها تسجيل الدخول هذا",+ "accountChoose": "اختر حسابًا",+ "accountDefault": " · الافتراضي لدى الوسيط",+ "accountDeactivated": " · معطّل",+ "accountSave": "استخدام هذا الحساب",+ "accountSaved": "تم حفظ الحساب."}}}diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex c5b6d120b..ba52492df 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -1213,7 +1213,15 @@"maxPerOrder": "≤{{amount}}/Order","expiresOn": "läuft ab {{date}}","accountSummary": "{{broker}} · {{type}}-Konto · finanziert von {{fundedBy}}",- "adjustRequestMessage": "Für Mandatsvorschlag \"{{label}}\" (Option {{ordinal}}): {{text}}"+ "adjustRequestMessage": "Für Mandatsvorschlag \"{{label}}\" (Option {{ordinal}}): {{text}}",+ "accountLoading": "Konten des Brokers werden geladen…",+ "accountLoadFailed": "Die Konten des Brokers konnten nicht geladen werden: {{error}}",+ "accountLabel": "Konto, auf dem dieses Mandat handeln darf",+ "accountChoose": "Konto auswählen",+ "accountDefault": " · Broker-Standard",+ "accountDeactivated": " · deaktiviert",+ "accountNotAgentic": " · Agenten-Trading nicht erlaubt",+ "accountHint": "Der Agent handelt nur auf diesem Konto. Es wird nichts für Sie vorausgewählt."},"messageBubble": {"elapsedTime": "Gesamte Antwortzeit",@@ -1623,7 +1631,19 @@"testFailed": "Test für {{label}} fehlgeschlagen: {{error}}","unknownTestError": "Der Connector hat einen unbekannten Fehler zurückgegeben.","delete": "Löschen",- "configured": "Erforderliche Zugangsdaten konfiguriert"+ "configured": "Erforderliche Zugangsdaten konfiguriert",+ "accountTitle": "Konto",+ "accountCurrent": "Liest das Konto mit der Endung ····{{last4}}",+ "accountNone": "Kein Konto ausgewählt. Diese Verbindung liest nichts, bis Sie eines auswählen.",+ "accountLoad": "Konto auswählen",+ "accountChange": "Konto wechseln",+ "accountEmpty": "Mit dieser Anmeldung ist kein Konto erreichbar.",+ "accountPicker": "Konten, die diese Anmeldung erreicht",+ "accountChoose": "Konto auswählen",+ "accountDefault": " · Broker-Standard",+ "accountDeactivated": " · deaktiviert",+ "accountSave": "Dieses Konto verwenden",+ "accountSaved": "Konto gespeichert."}}}diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 0bbef91c7..0d66694e1 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -1213,7 +1213,15 @@"maxPerOrder": "≤{{amount}}/order","expiresOn": "expires {{date}}","accountSummary": "{{broker}} · {{type}} account · funded by {{fundedBy}}",- "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}"+ "adjustRequestMessage": "For mandate proposal \"{{label}}\" (option {{ordinal}}): {{text}}",+ "accountLoading": "Loading the broker's accounts…",+ "accountLoadFailed": "Could not load the broker's accounts: {{error}}",+ "accountLabel": "Account this mandate may trade",+ "accountChoose": "Choose an account",+ "accountDefault": " · broker default",+ "accountDeactivated": " · deactivated",+ "accountNotAgentic": " · agentic trading not allowed",+ "accountHint": "The agent trades only this account. Nothing is chosen for you."},"messageBubble": {"elapsedTime": "Total response time",@@ -1623,7 +1631,19 @@"testFailed": "{{label}} check failed: {{error}}","unknownTestError": "The connector returned an unknown error.","delete": "Delete",- "configured": "Required credentials configured"+ "configured": "Required credentials configured",+ "accountTitle": "Account",+ "accountCurrent": "Reads the account ending ····{{last4}}",+ "accountNone": "No account selected. This connection reads nothing until you choose one.",+ "accountLoad": "Choose account",+ "accountChange": "Change account",+ "accountEmpty": "This login reaches no accounts.",+ "accountPicker": "Accounts this login can reach",+ "accountChoose": "Choose an account",+ "accountDefault": " · broker default",+ "accountDeactivated": " · deactivated",+ "accountSave": "Use this account",+ "accountSaved": "Account saved."}}}diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex 989ae85dd..b556ec6b8 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -1213,7 +1213,15 @@"maxPerOrder": "≤{{amount}}/orden","expiresOn": "vence {{date}}","accountSummary": "{{broker}} · cuenta {{type}} · financiada por {{fundedBy}}",- "adjustRequestMessage": "Para la propuesta de mandato \"{{label}}\" (opción {{ordinal}}): {{text}}"+ "adjustRequestMessage": "Para la propuesta de mandato \"{{label}}\" (opción {{ordinal}}): {{text}}",+ "accountLoading": "Cargando las cuentas del bróker…",+ "accountLoadFailed": "No se pudieron cargar las cuentas del bróker: {{error}}",+ "accountLabel": "Cuenta en la que este mandato puede operar",+ "accountChoose": "Elige una cuenta",+ "accountDefault": " · predeterminada del bróker",+ "accountDeactivated": " · desactivada",+ "accountNotAgentic": " · no permite trading con agentes",+ "accountHint": "El agente solo opera en esta cuenta. No se elige ninguna por ti."},"messageBubble": {"elapsedTime": "Tiempo total de respuesta",@@ -1623,7 +1631,19 @@"testFailed": "Falló la prueba de {{label}}: {{error}}","unknownTestError": "El conector devolvió un error desconocido.","delete": "Eliminar",- "configured": "Credenciales necesarias configuradas"+ "configured": "Credenciales necesarias configuradas",+ "accountTitle": "Cuenta",+ "accountCurrent": "Lee la cuenta terminada en ····{{last4}}",+ "accountNone": "No hay ninguna cuenta seleccionada. Esta conexión no lee nada hasta que elijas una.",+ "accountLoad": "Elegir cuenta",+ "accountChange": "Cambiar cuenta",+ "accountEmpty": "Este inicio de sesión no tiene acceso a ninguna cuenta.",+ "accountPicker": "Cuentas a las que accede este inicio de sesión",+ "accountChoose": "Elige una cuenta",+ "accountDefault": " · predeterminada del bróker",+ "accountDeactivated": " · desactivada",+ "accountSave": "Usar esta cuenta",+ "accountSaved": "Cuenta guardada."}}}diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex b8d72d68a..d2b809194 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -1208,7 +1208,15 @@"maxPerOrder": "1注文あたり {{amount}} 以下","expiresOn": "有効期限: {{date}}","accountSummary": "{{broker}}・{{type}}口座・資金提供元: {{fundedBy}}",- "adjustRequestMessage": "マンデート案「{{label}}」(選択肢 {{ordinal}})への調整依頼: {{text}}"+ "adjustRequestMessage": "マンデート案「{{label}}」(選択肢 {{ordinal}})への調整依頼: {{text}}",+ "accountLoading": "ブローカーの口座を読み込んでいます…",+ "accountLoadFailed": "ブローカーの口座を読み込めませんでした: {{error}}",+ "accountLabel": "このマンデートで取引できる口座",+ "accountChoose": "口座を選択",+ "accountDefault": "・ブローカーの既定",+ "accountDeactivated": "・無効化済み",+ "accountNotAgentic": "・エージェント取引は許可されていません",+ "accountHint": "エージェントはこの口座だけで取引します。自動では選択されません。"},"messageBubble": {"elapsedTime": "合計応答時間",@@ -1623,7 +1631,19 @@"testFailed": "{{label}} のテストに失敗しました: {{error}}","unknownTestError": "コネクターが不明なエラーを返しました。","delete": "削除",- "configured": "必要な認証情報は設定済みです"+ "configured": "必要な認証情報は設定済みです",+ "accountTitle": "口座",+ "accountCurrent": "末尾 ····{{last4}} の口座を読み取ります",+ "accountNone": "口座が選択されていません。選択するまで、この接続は何も読み取りません。",+ "accountLoad": "口座を選択",+ "accountChange": "口座を変更",+ "accountEmpty": "このログインで利用できる口座はありません。",+ "accountPicker": "このログインで利用できる口座",+ "accountChoose": "口座を選択",+ "accountDefault": "・ブローカーの既定",+ "accountDeactivated": "・無効化済み",+ "accountSave": "この口座を使う",+ "accountSaved": "口座を保存しました。"}}}diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 542b80ab9..a114113d6 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -1208,7 +1208,15 @@"maxPerOrder": "주문당 {{amount}} 이하","expiresOn": "{{date}} 만료","accountSummary": "{{broker}} · {{type}} 계정 · 자금 제공: {{fundedBy}}",- "adjustRequestMessage": "운용 권한 제안 \"{{label}}\"(옵션 {{ordinal}})에 대한 조정 요청: {{text}}"+ "adjustRequestMessage": "운용 권한 제안 \"{{label}}\"(옵션 {{ordinal}})에 대한 조정 요청: {{text}}",+ "accountLoading": "브로커 계좌를 불러오는 중…",+ "accountLoadFailed": "브로커 계좌를 불러오지 못했습니다: {{error}}",+ "accountLabel": "이 mandate로 거래할 계좌",+ "accountChoose": "계좌 선택",+ "accountDefault": " · 브로커 기본값",+ "accountDeactivated": " · 비활성화됨",+ "accountNotAgentic": " · 에이전트 거래 허용 안 됨",+ "accountHint": "에이전트는 이 계좌에서만 거래합니다. 자동으로 선택되지 않습니다."},"messageBubble": {"elapsedTime": "총 응답 시간",@@ -1623,7 +1631,19 @@"testFailed": "{{label}} 테스트 실패: {{error}}","unknownTestError": "커넥터가 알 수 없는 오류를 반환했습니다.","delete": "삭제",- "configured": "필요한 자격 증명이 설정되었습니다"+ "configured": "필요한 자격 증명이 설정되었습니다",+ "accountTitle": "계좌",+ "accountCurrent": "끝자리 ····{{last4}} 계좌를 읽습니다",+ "accountNone": "선택된 계좌가 없습니다. 계좌를 선택하기 전까지 이 연결은 아무것도 읽지 않습니다.",+ "accountLoad": "계좌 선택",+ "accountChange": "계좌 변경",+ "accountEmpty": "이 로그인으로 접근할 수 있는 계좌가 없습니다.",+ "accountPicker": "이 로그인으로 접근할 수 있는 계좌",+ "accountChoose": "계좌 선택",+ "accountDefault": " · 브로커 기본값",+ "accountDeactivated": " · 비활성화됨",+ "accountSave": "이 계좌 사용",+ "accountSaved": "계좌를 저장했습니다."}}}diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex cebfcf558..dfedc3282 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -1213,7 +1213,15 @@"maxPerOrder": "≤{{amount}}/ordem","expiresOn": "expira {{date}}","accountSummary": "{{broker}} · Conta {{type}} · financiado por {{fundedBy}}",- "adjustRequestMessage": "Para proposta de mandato \"{{label}}\" (opção {{ordinal}}): {{text}}"+ "adjustRequestMessage": "Para proposta de mandato \"{{label}}\" (opção {{ordinal}}): {{text}}",+ "accountLoading": "Carregando as contas da corretora…",+ "accountLoadFailed": "Não foi possível carregar as contas da corretora: {{error}}",+ "accountLabel": "Conta em que este mandato pode negociar",+ "accountChoose": "Escolha uma conta",+ "accountDefault": " · padrão da corretora",+ "accountDeactivated": " · desativada",+ "accountNotAgentic": " · negociação por agente não permitida",+ "accountHint": "O agente negocia apenas nesta conta. Nenhuma conta é escolhida por você."},"messageBubble": {"elapsedTime": "Tempo total de resposta",@@ -1623,7 +1631,19 @@"testFailed": "Falha na verificação {{label}}: {{error}}","unknownTestError": "O conector retornou um erro desconhecido.","delete": "Excluir",- "configured": "Credenciais necessárias configuradas"+ "configured": "Credenciais necessárias configuradas",+ "accountTitle": "Conta",+ "accountCurrent": "Lê a conta com final ····{{last4}}",+ "accountNone": "Nenhuma conta selecionada. Esta conexão não lê nada até você escolher uma.",+ "accountLoad": "Escolher conta",+ "accountChange": "Trocar conta",+ "accountEmpty": "Este login não acessa nenhuma conta.",+ "accountPicker": "Contas que este login acessa",+ "accountChoose": "Escolha uma conta",+ "accountDefault": " · padrão da corretora",+ "accountDeactivated": " · desativada",+ "accountSave": "Usar esta conta",+ "accountSaved": "Conta salva."}}}diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 69aed134b..73732b4b8 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -1208,7 +1208,15 @@"maxPerOrder": "每笔 ≤{{amount}}","expiresOn": "到期日:{{date}}","accountSummary": "{{broker}} · {{type}} 账户 · 资金来源:{{fundedBy}}",- "adjustRequestMessage": "针对授权提案「{{label}}」(选项 {{ordinal}})的调整:{{text}}"+ "adjustRequestMessage": "针对授权提案「{{label}}」(选项 {{ordinal}})的调整:{{text}}",+ "accountLoading": "正在读取券商账户…",+ "accountLoadFailed": "无法读取券商账户:{{error}}",+ "accountLabel": "该授权可交易的账户",+ "accountChoose": "选择账户",+ "accountDefault": " · 券商默认",+ "accountDeactivated": " · 已停用",+ "accountNotAgentic": " · 不允许智能体交易",+ "accountHint": "智能体只会交易这个账户,系统不会替你预选。"},"messageBubble": {"elapsedTime": "本次回复总耗时",@@ -1623,7 +1631,19 @@"testFailed": "{{label}} 测试失败:{{error}}","unknownTestError": "连接器返回了未知错误。","delete": "删除",- "configured": "所需凭证已配置"+ "configured": "所需凭证已配置",+ "accountTitle": "账户",+ "accountCurrent": "读取尾号 ····{{last4}} 的账户",+ "accountNone": "尚未选择账户。选择之前,这个连接不会读取任何数据。",+ "accountLoad": "选择账户",+ "accountChange": "更换账户",+ "accountEmpty": "这个登录下没有可用账户。",+ "accountPicker": "这个登录可访问的账户",+ "accountChoose": "选择账户",+ "accountDefault": " · 券商默认",+ "accountDeactivated": " · 已停用",+ "accountSave": "使用这个账户",+ "accountSaved": "账户已保存。"}}}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1de6c76f6..a49e10938 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -233,6 +233,10 @@ export interface LocalConnection {id: string;profile_id: string;label: string;+ /** Broker account the reads are scoped to; empty until the user selects one. */+ account_ref: string;+ /** True when this connection reads nothing until an account is selected. */+ account_selection_required: boolean;connector: string;environment: "paper" | "live";transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin";@@ -259,12 +263,22 @@ export interface ReadonlyConnectionProfile {credential_fields: CredentialField[];onboarding?: ConnectorOnboarding;supports_reconnect: boolean;+ account_selection_required: boolean;portfolio_compatibility: PortfolioConnectorCompatibility;invalid_plugin?: boolean;directory?: string;error?: string;}+/** One account a broker login can reach, as the backend maps it for a picker. */+export interface BrokerAccountChoice {+ account_ref: string;+ label: string;+ is_default: boolean;+ agentic_allowed: boolean;+ deactivated: boolean;+}+export interface ConnectionsResponse {status: string;connections: LocalConnection[];@@ -382,6 +396,15 @@ export const api = {`/api/connections/${encodeURIComponent(connectionId)}/check`,{ method: "POST" },),+ getConnectionAccounts: (connectionId: string) =>+ request<{ status: string; connection_id: string; account_ref: string; accounts: BrokerAccountChoice[] }>(+ `/api/connections/${encodeURIComponent(connectionId)}/accounts`,+ ),+ selectConnectionAccount: (connectionId: string, accountRef: string) =>+ request<{ status: string; connection: LocalConnection }>(+ `/api/connections/${encodeURIComponent(connectionId)}/account`,+ { method: "PUT", body: JSON.stringify({ account_ref: accountRef }) },+ ),deleteConnection: (connectionId: string) =>request<{ status: string; deleted: string }>(`/api/connections/${encodeURIComponent(connectionId)}`,@@ -544,6 +567,10 @@ export const api = {// Connector runtime channel — privileged surface actions (NOT agent tools).// commit is the ONLY action that writes a mandate; halt trips the kill switch.+ getLiveAccounts: (broker: string) =>+ request<{ status: string; broker: string; account_selection_required: boolean; accounts: BrokerAccountChoice[] }>(+ `/live/accounts?broker=${encodeURIComponent(broker)}`,+ ),commitMandate: (body: CommitMandateRequest) =>request<CommitMandateResponse>("/mandate/commit", {method: "POST",