"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(connections): preserve vault protection and show deletion errors
Haozhe Wuf95215f66015
diff --git a/agent/src/api/connection_routes.py b/agent/src/api/connection_routes.pyindex 6311225c4..cbfe71fc8 100644--- a/agent/src/api/connection_routes.py+++ b/agent/src/api/connection_routes.py@@ -240,8 +240,13 @@ def register_connection_routes(app: FastAPI) -> None:try:selected = {source.connection_id for source in PortfolioSettingsStore().load().sources}if connection_id.strip().lower() in selected:- raise ValueError("remove this connection from the portfolio before deleting it")+ raise HTTPException(status_code=400, detail={+ "code": "connection_in_use",+ "message": "remove this connection from the portfolio before deleting it",+ })store().delete(connection_id)return {"status": "ok", "deleted": connection_id}except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ except RuntimeError as exc:+ raise HTTPException(status_code=503, detail=str(exc)) from excdiff --git a/agent/src/trading/credentials.py b/agent/src/trading/credentials.pyindex 98963caf8..388414f71 100644--- a/agent/src/trading/credentials.py+++ b/agent/src/trading/credentials.py@@ -152,19 +152,21 @@ class CredentialStore:return resultdef delete(self, connection_id: str, fields: Iterable[str]) -> None:- """Remove the stored secrets for a connection.+ """Remove stored secrets; a missing vault cannot confirm their deletion.Args:connection_id: Identifier of the local connection instance.fields: Credential field names declared by the connector manifest.Raises:- RuntimeError: If the ``keyring`` extra is not installed.- Exception: Whatever the backend raises for a failure other than a- missing entry, which is treated as already deleted.+ RuntimeError: If the vault is unavailable or cannot delete the secrets.+ A missing entry is treated as already deleted."""+ field_names = tuple(fields)+ if not field_names:+ returnbackend = self.backend- for field in fields:+ for field in field_names:try:backend.delete_password(SERVICE_NAME,@@ -172,4 +174,4 @@ class CredentialStore:)except Exception as exc: # keyring backends differ on missing entriesif "not found" not in str(exc).lower():- raise+ raise RuntimeError(str(exc)) from excdiff --git a/agent/tests/test_connection_routes.py b/agent/tests/test_connection_routes.pyindex 1c72c56c5..120c16660 100644--- a/agent/tests/test_connection_routes.py+++ b/agent/tests/test_connection_routes.py@@ -25,6 +25,56 @@ class _MemoryCredentials:self.values.pop((service_name, username), None)+def deletion_client(tmp_path, monkeypatch):+ from src.portfolio.config import PortfolioSettingsStore++ credentials = _MemoryCredentials()+ store = ConnectionStore(tmp_path / "connections.json", credential_store=CredentialStore(credentials))+ store.create("main-alpaca", "alpaca-live-sdk-readonly", "Main Alpaca")+ store.credentials.save("main-alpaca", {"api_key": "test-key", "secret_key": "test-secret"})+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json", connection_store=store)+ monkeypatch.setattr(connection_routes, "ConnectionStore", lambda: store)+ monkeypatch.setattr(connection_routes, "PortfolioSettingsStore", lambda: settings)+ app = FastAPI()+ connection_routes.register_connection_routes(app)+ return TestClient(app, raise_server_exceptions=False), store, settings, credentials++[email protected]("enabled", [True, False])+def test_delete_rejects_portfolio_references_until_settings_are_saved(deletion_client, enabled):+ client, store, settings, credentials = deletion_client+ settings.save({"sources": [{"connection_id": "main-alpaca", "enabled": enabled}]})+ original_settings = settings.path.read_bytes()+ response = client.delete("/api/connections/main-alpaca")+ assert response.status_code == 400+ assert response.json()["detail"]["code"] == "connection_in_use"+ assert "remove this connection from the portfolio" in response.json()["detail"]["message"]+ assert store.get("main-alpaca").id == "main-alpaca"+ assert settings.path.read_bytes() == original_settings+ assert credentials.values++ settings.save({"sources": []})+ assert client.delete("/api/connections/main-alpaca").status_code == 200+ assert store.list() == []+ assert credentials.values == {}++[email protected]("error_type", [RuntimeError, PermissionError])+def test_delete_returns_vault_failure_without_deleting_connection(deletion_client, monkeypatch, error_type):+ client, store, _, credentials = deletion_client++ def locked(*args):+ raise error_type("credential vault is locked")++ monkeypatch.setattr(credentials, "delete_password", locked)+ response = client.delete("/api/connections/main-alpaca")+ assert response.status_code == 503+ assert response.json()["detail"] == "credential vault is locked"+ assert store.get("main-alpaca").id == "main-alpaca"+ assert credentials.values++def test_connection_routes_create_list_and_check_without_returning_secrets(tmp_path,monkeypatch,diff --git a/agent/tests/test_local_connections_hardening.py b/agent/tests/test_local_connections_hardening.pyindex d29d308ad..a4c41b049 100644--- a/agent/tests/test_local_connections_hardening.py+++ b/agent/tests/test_local_connections_hardening.py@@ -8,6 +8,7 @@ import osimport subprocessimport sysimport tomllib+import typesfrom pathlib import Pathimport pytest@@ -97,6 +98,76 @@ def test_credential_store_names_the_extra_when_keyring_is_missing(CredentialStore().save("main-account", {"api_key": "value"})[email protected]("profile_id", ["alpaca-live-sdk-readonly", "ibkr-paper-local"])+def test_delete_connection_without_keyring_installed(tmp_path, monkeypatch, profile_id):+ real_import = builtins.__import__++ def blocking_import(name, *args, **kwargs):+ if name == "keyring" or name.startswith("keyring."):+ raise ModuleNotFoundError("No module named 'keyring'", name="keyring")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", blocking_import)+ store = ConnectionStore(tmp_path / "connections.json")+ store.create("unused", profile_id, "Unused")+ if profile_id == "alpaca-live-sdk-readonly":+ with pytest.raises(RuntimeError, match="credential vault"):+ store.delete("unused")+ assert store.get("unused").id == "unused"+ else:+ store.delete("unused")+ assert store.list() == []+++def test_delete_connection_without_a_keyring_backend(tmp_path, monkeypatch):+ class NoKeyringError(RuntimeError):+ pass++ def unavailable(*args):+ raise NoKeyringError("No recommended backend was available")++ keyring = types.ModuleType("keyring")+ errors = types.ModuleType("keyring.errors")+ errors.NoKeyringError = NoKeyringError+ keyring.delete_password = unavailable+ keyring.get_password = unavailable+ monkeypatch.setitem(sys.modules, "keyring", keyring)+ monkeypatch.setitem(sys.modules, "keyring.errors", errors)+ store = ConnectionStore(tmp_path / "connections.json")+ store.create("unused", "alpaca-live-sdk-readonly", "Unused")+ # Listing may cache the imported keyring module before deletion.+ store.public_list()+ with pytest.raises(RuntimeError, match="backend"):+ store.delete("unused")+ assert store.get("unused").id == "unused"++[email protected]("error_type", [RuntimeError, PermissionError])+def test_delete_connection_keeps_registry_when_vault_is_locked(tmp_path, error_type):+ class LockedCredentials(_MemoryCredentials):+ def delete_password(self, service_name, username):+ raise error_type("credential vault is locked")++ store = ConnectionStore(tmp_path / "connections.json", credential_store=CredentialStore(LockedCredentials()))+ store.create("protected", "alpaca-live-sdk-readonly", "Protected")+ with pytest.raises(RuntimeError, match="vault is locked"):+ store.delete("protected")+ assert store.get("protected").label == "Protected"+++def test_delete_connection_removes_only_its_own_credentials(tmp_path):+ backend = _MemoryCredentials()+ credentials = CredentialStore(backend)+ store = ConnectionStore(tmp_path / "connections.json", credential_store=credentials)+ for connection_id in ["deleted", "retained"]:+ store.create(connection_id, "alpaca-live-sdk-readonly", connection_id)+ credentials.save(connection_id, {"api_key": "key", "secret_key": "secret"})+ store.delete("deleted")+ assert credentials.load("deleted", ["api_key", "secret_key"]) == {}+ assert credentials.load("retained", ["api_key", "secret_key"]) == {"api_key": "key", "secret_key": "secret"}+ assert [row.id for row in store.list()] == ["retained"]++def test_connection_modules_import_without_keyring_installed() -> None:"""Connection metadata must stay importable on a base install.diff --git a/frontend/src/components/portfolio/ConnectionCenter.tsx b/frontend/src/components/portfolio/ConnectionCenter.tsxindex 623f20828..bdb9eb931 100644--- a/frontend/src/components/portfolio/ConnectionCenter.tsx+++ b/frontend/src/components/portfolio/ConnectionCenter.tsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { CheckCircle2, FolderCode, Loader2, PlugZap, Plus, ShieldCheck, Trash2, Wallet, X } from "lucide-react";import { PortfolioCompatibilityBadge } from "@/components/portfolio/PortfolioCompatibilityBadge";-import { api, type BrokerAccountChoice, type ConnectionsResponse, type LocalConnection } from "@/lib/api";+import { api, ApiError, type BrokerAccountChoice, type ConnectionsResponse, type LocalConnection } from "@/lib/api";interface Props {open: boolean;@@ -26,6 +26,7 @@ export function ConnectionCenter({ open, onClose, onChanged }: Props) {const [label, setLabel] = useState("");const [busy, setBusy] = useState<string | null>(null);const [message, setMessage] = useState<string | null>(null);+ const [deleteErrors, setDeleteErrors] = useState<Record<string, Error>>({});const [testResults, setTestResults] = useState<Record<string, TestResult>>({});async function load() {@@ -35,6 +36,7 @@ export function ConnectionCenter({ open, onClose, onChanged }: Props) {useEffect(() => {if (!open) return;setMessage(null);+ setDeleteErrors({});void load().catch((error) => setMessage(error instanceof Error ? error.message : String(error)));}, [open]);@@ -116,8 +118,20 @@ export function ConnectionCenter({ open, onClose, onChanged }: Props) {async function remove(connection: LocalConnection) {setBusy(`delete:${connection.id}`);setMessage(null);+ setDeleteErrors((current) => {+ const next = { ...current };+ delete next[connection.id];+ return next;+ });try {await api.deleteConnection(connection.id);+ } catch (error) {+ const reason = error instanceof Error ? error : new Error(String(error));+ setDeleteErrors((current) => ({ ...current, [connection.id]: reason }));+ setBusy(null);+ return;+ }+ try {await load();await onChanged();} catch (error) {@@ -153,7 +167,7 @@ export function ConnectionCenter({ open, onClose, onChanged }: Props) {<section><div className="flex items-end justify-between"><div><h3 className="font-medium">{t("portfolio.connections.listTitle")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.connections.listCount", { count: data?.connections.length ?? 0 })}</p></div><ShieldCheck className="h-5 w-5 text-positive" /></div>- <div className="mt-3 space-y-3">{data?.connections.map((connection) => <ConnectionCard key={connection.id} connection={connection} busy={busy} testResult={testResults[connection.id]} onTest={test} onDelete={remove} onSaved={async () => { await load(); await onChanged(); }} setBusy={setBusy} setMessage={setMessage} />)}{data && !data.connections.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{t("portfolio.connections.empty")}</div> : null}</div>+ <div className="mt-3 space-y-3">{data?.connections.map((connection) => <ConnectionCard key={connection.id} connection={connection} busy={busy} deleteError={deleteErrors[connection.id]} testResult={testResults[connection.id]} onTest={test} onDelete={remove} onSaved={async () => { await load(); await onChanged(); }} setBusy={setBusy} setMessage={setMessage} />)}{data && !data.connections.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{t("portfolio.connections.empty")}</div> : null}</div></section><section className="rounded-xl border border-dashed p-4">@@ -166,7 +180,7 @@ export function ConnectionCenter({ open, onClose, onChanged }: Props) {</div>;}-function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSaved, setBusy, setMessage }: { connection: LocalConnection; busy: string | null; testResult?: TestResult; onTest: (connection: LocalConnection) => Promise<void>; onDelete: (connection: LocalConnection) => Promise<void>; onSaved: () => Promise<void>; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void }) {+function ConnectionCard({ connection, busy, deleteError, testResult, onTest, onDelete, onSaved, setBusy, setMessage }: { connection: LocalConnection; busy: string | null; deleteError?: Error; testResult?: TestResult; onTest: (connection: LocalConnection) => Promise<void>; onDelete: (connection: LocalConnection) => Promise<void>; onSaved: () => Promise<void>; setBusy: (value: string | null) => void; setMessage: (value: string | null) => void }) {const { t } = useTranslation();const [values, setValues] = useState<Record<string, string>>({});const socketConnection = (connection.connector === "ibkr" && connection.transport === "local_tws")@@ -233,6 +247,7 @@ function ConnectionCard({ connection, busy, testResult, onTest, onDelete, onSave{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 testConnection()} disabled={socketConnection ? busy !== null || !endpointValid : busy === `test:${connection.id}`} className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs">{busy === `test:${connection.id}` ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}{t("portfolio.connections.test")}</button><button type="button" onClick={() => void onDelete(connection)} disabled={busy === `delete:${connection.id}`} className="ml-auto inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs text-danger hover:bg-danger/10"><Trash2 className="h-3.5 w-3.5" />{t("portfolio.connections.delete")}</button></div>+ {deleteError ? <div role="alert" className="mt-3 rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-xs text-danger break-words">{deleteError instanceof ApiError && deleteError.code === "connection_in_use" ? t("portfolio.connections.deleteInUse") : deleteError.message}</div> : null}{testResult && !endpointDirty ? <div role="status" className={`mt-3 rounded-md border px-3 py-2 text-xs ${testResult.ok ? "border-positive/30 bg-positive/5 text-positive" : "border-danger/30 bg-danger/5 text-danger"}`}>{testResult.message}</div> : null}{connection.credentials_configured ? <div className="mt-3 flex items-center gap-1.5 text-xs text-positive"><CheckCircle2 className="h-3.5 w-3.5" />{t("portfolio.connections.configured")}</div> : null}</article>;diff --git a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsxindex 599c3eaf9..355c7f55c 100644--- a/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx+++ b/frontend/src/components/portfolio/__tests__/ConnectionCenter.test.tsx@@ -1,7 +1,7 @@import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { ConnectionCenter } from "@/components/portfolio/ConnectionCenter";-import { api, type LocalConnection } from "@/lib/api";+import { api, ApiError, type LocalConnection } from "@/lib/api";import i18n from "@/i18n";vi.mock("@/lib/api", async () => {@@ -15,6 +15,7 @@ vi.mock("@/lib/api", async () => {selectConnectionAccount: vi.fn(),saveConnectionEndpoint: vi.fn(),checkConnection: vi.fn(),+ deleteConnection: vi.fn(),},};});@@ -25,6 +26,7 @@ const mocked = api as unknown as {selectConnectionAccount: ReturnType<typeof vi.fn>;saveConnectionEndpoint: ReturnType<typeof vi.fn>;checkConnection: ReturnType<typeof vi.fn>;+ deleteConnection: ReturnType<typeof vi.fn>;};function robinhood(accountRef: string): LocalConnection {@@ -58,6 +60,72 @@ function renderCenter(connection: LocalConnection, onChanged = vi.fn().mockResolreturn onChanged;}+describe("ConnectionCenter deletion", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocked.deleteConnection.mockReset().mockResolvedValue({ status: "ok" });+ });++ it.each([+ ["en", "Remove this connection from Account holdings and save your changes before deleting it."],+ ["zh-CN", "请先从账户持仓中移除此连接并保存,再删除连接。"],+ ])("localizes an in-use connection error in %s", async (language, message) => {+ try {+ await i18n.changeLanguage(language);+ renderCenter(robinhood(""));+ mocked.deleteConnection.mockRejectedValueOnce(new ApiError("Server fallback message", 400, "connection_in_use"));+ fireEvent.click(await screen.findByRole("button", { name: language === "zh-CN" ? "删除" : "Delete" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(message);+ expect(screen.queryByText("Server fallback message")).not.toBeInTheDocument();+ } finally {+ await act(async () => { await i18n.changeLanguage("en"); });+ }+ });++ it("updates an existing deletion error when the language changes", async () => {+ renderCenter(robinhood(""));+ mocked.deleteConnection.mockRejectedValueOnce(new ApiError("Server fallback message", 400, "connection_in_use"));+ fireEvent.click(await screen.findByRole("button", { name: i18n.t("portfolio.connections.delete") }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Remove this connection from Account holdings");+ try {+ await act(async () => { await i18n.changeLanguage("zh-CN"); });+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("请先从账户持仓中移除此连接并保存,再删除连接。"));+ expect(mocked.deleteConnection).toHaveBeenCalledTimes(1);+ } finally {+ await act(async () => { await i18n.changeLanguage("en"); });+ }+ });++ it("deletes the connection and refreshes the list", async () => {+ const onChanged = renderCenter(robinhood(""));+ const button = await screen.findByRole("button", { name: i18n.t("portfolio.connections.delete") });+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [], profiles: [] });+ fireEvent.click(button);+ await waitFor(() => expect(mocked.deleteConnection).toHaveBeenCalledWith("robinhood-live"));+ expect(await screen.findByText(i18n.t("portfolio.connections.empty"))).toBeInTheDocument();+ await waitFor(() => expect(onChanged).toHaveBeenCalledTimes(1));+ });++ it("shows deletion errors on the affected card and clears them on retry", async () => {+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [robinhood(""), ibkr()], profiles: [] });+ render(<ConnectionCenter open onClose={() => undefined} onChanged={vi.fn().mockResolvedValue(undefined)} />);+ const label = await screen.findByText("Robinhood");+ const button = within(label.closest("article")!).getByRole("button", { name: i18n.t("portfolio.connections.delete") });+ mocked.deleteConnection.mockRejectedValueOnce(new Error("remove this connection from the portfolio before deleting it"));+ fireEvent.click(button);+ const alert = await screen.findByRole("alert");+ const card = alert.closest("article")!;+ expect(within(card).getByText("Robinhood")).toBeInTheDocument();+ expect(alert).toHaveTextContent("remove this connection from the portfolio before deleting it");+ expect(within(screen.getByText("IBKR Paper").closest("article")!).queryByRole("alert")).not.toBeInTheDocument();+ expect(mocked.getConnections).toHaveBeenCalledTimes(1);+ mocked.getConnections.mockResolvedValue({ status: "ok", connections: [ibkr()], profiles: [] });+ fireEvent.click(within(card).getByRole("button", { name: i18n.t("portfolio.connections.delete") }));+ await waitFor(() => expect(mocked.deleteConnection).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());+ });+});+describe("ConnectionCenter account selection", () => {beforeEach(() => {vi.clearAllMocks();diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex b7f9d278d..816642149 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -2350,6 +2350,7 @@"testFailed": "فشل اختبار {{label}}: {{error}}","unknownTestError": "أرجع الموصل خطأ غير معروف.","delete": "حذف",+ "deleteInUse": "أزل هذا الاتصال من «مراكز الحسابات» واحفظ التغييرات قبل حذفه.","configured": "بيانات الاعتماد المطلوبة مضبوطة","accountTitle": "الحساب","accountCurrent": "يقرأ الحساب المنتهي بـ ····{{last4}}",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex 43f54237b..f8ee376bf 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -2350,6 +2350,7 @@"testFailed": "Test für {{label}} fehlgeschlagen: {{error}}","unknownTestError": "Der Connector hat einen unbekannten Fehler zurückgegeben.","delete": "Löschen",+ "deleteInUse": "Entferne diese Verbindung aus „Kontopositionen“ und speichere die Änderungen, bevor du sie löschst.","configured": "Erforderliche Zugangsdaten konfiguriert","accountTitle": "Konto","accountCurrent": "Liest das Konto mit der Endung ····{{last4}}",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 34c68913c..317f618ea 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -2350,6 +2350,7 @@"testFailed": "{{label}} check failed: {{error}}","unknownTestError": "The connector returned an unknown error.","delete": "Delete",+ "deleteInUse": "Remove this connection from Account holdings and save your changes before deleting it.","configured": "Required credentials configured","accountTitle": "Account","accountCurrent": "Reads the account ending ····{{last4}}",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex d22779786..095d19c84 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -2350,6 +2350,7 @@"testFailed": "Falló la prueba de {{label}}: {{error}}","unknownTestError": "El conector devolvió un error desconocido.","delete": "Eliminar",+ "deleteInUse": "Quita esta conexión de «Posiciones de cuentas» y guarda los cambios antes de eliminarla.","configured": "Credenciales necesarias configuradas","accountTitle": "Cuenta","accountCurrent": "Lee la cuenta terminada en ····{{last4}}",diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.jsonindex 83c0922c2..eab408b27 100644--- a/frontend/src/i18n/locales/fa.json+++ b/frontend/src/i18n/locales/fa.json@@ -2350,6 +2350,7 @@"testFailed": "بررسی {{label}} ناموفق بود: {{error}}","unknownTestError": "کانکتور خطای ناشناختهای برگرداند.","delete": "حذف",+ "deleteInUse": "پیش از حذف این اتصال، آن را از «پورتفولیو» بردارید و تغییرات را ذخیره کنید.","configured": "اعتبارنامههای لازم پیکربندی شدهاند","accountTitle": "حساب","accountCurrent": "حساب با پایان ····{{last4}} خوانده میشود",diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex 35eeabece..cedb25cb4 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -2350,6 +2350,7 @@"testFailed": "Pemeriksaan {{label}} gagal: {{error}}","unknownTestError": "Connector mengembalikan error yang tidak diketahui.","delete": "Hapus",+ "deleteInUse": "Keluarkan koneksi ini dari Posisi akun dan simpan perubahan sebelum menghapus koneksi tersebut.","configured": "Kredensial wajib sudah dikonfigurasi","accountTitle": "Akun","accountCurrent": "Membaca akun yang berakhiran ····{{last4}}",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex b853448e2..62e733969 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -2350,6 +2350,7 @@"testFailed": "{{label}} のテストに失敗しました: {{error}}","unknownTestError": "コネクターが不明なエラーを返しました。","delete": "削除",+ "deleteInUse": "この接続を「口座の保有資産」から外して変更を保存してから、接続を削除してください。","configured": "必要な認証情報は設定済みです","accountTitle": "口座","accountCurrent": "末尾 ····{{last4}} の口座を読み取ります",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex a60098564..58c9670cb 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -2350,6 +2350,7 @@"testFailed": "{{label}} 테스트 실패: {{error}}","unknownTestError": "커넥터가 알 수 없는 오류를 반환했습니다.","delete": "삭제",+ "deleteInUse": "이 연결을 삭제하려면 먼저 ‘계좌 보유 자산’에서 제거하고 변경 사항을 저장하세요.","configured": "필요한 자격 증명이 설정되었습니다","accountTitle": "계좌","accountCurrent": "끝자리 ····{{last4}} 계좌를 읽습니다",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex 533a6cff1..a120edf21 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -2350,6 +2350,7 @@"testFailed": "Falha na verificação {{label}}: {{error}}","unknownTestError": "O conector retornou um erro desconhecido.","delete": "Excluir",+ "deleteInUse": "Remova esta conexão de “Posições das contas” e salve as alterações antes de excluí-la.","configured": "Credenciais necessárias configuradas","accountTitle": "Conta","accountCurrent": "Lê a conta com final ····{{last4}}",diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.jsonindex 02bfae210..cd4f5a6b2 100644--- a/frontend/src/i18n/locales/tr.json+++ b/frontend/src/i18n/locales/tr.json@@ -2312,6 +2312,7 @@"testFailed": "{{label}} kontrolü başarısız: {{error}}","unknownTestError": "Bağlantı bilinmeyen bir hata döndürdü.","delete": "Sil",+ "deleteInUse": "Bu bağlantıyı silmeden önce Portföy'den kaldırın ve değişiklikleri kaydedin.","configured": "Gerekli kimlik bilgileri yapılandırıldı","accountTitle": "Hesap","accountCurrent": "Sonu ····{{last4}} olan hesabı okur",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 0fb8245cf..fa100237d 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -2350,6 +2350,7 @@"testFailed": "{{label}} 测试失败:{{error}}","unknownTestError": "连接器返回了未知错误。","delete": "删除",+ "deleteInUse": "请先从账户持仓中移除此连接并保存,再删除连接。","configured": "所需凭证已配置","accountTitle": "账户","accountCurrent": "读取尾号 ····{{last4}} 的账户",diff --git a/frontend/src/lib/__tests__/api.test.ts b/frontend/src/lib/__tests__/api.test.tsindex 4dee67727..57f679b2a 100644--- a/frontend/src/lib/__tests__/api.test.ts+++ b/frontend/src/lib/__tests__/api.test.ts@@ -25,6 +25,16 @@ describe("generated report download", () => {});describe("api request helper", () => {+ it("preserves the structured error code when a connection is still in use", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({+ detail: { code: "connection_in_use", message: "remove this connection from the portfolio before deleting it" },+ }), { status: 400, headers: { "content-type": "application/json" } })));+ const { api } = await loadApiModule();+ await expect(api.deleteConnection("main-alpaca")).rejects.toMatchObject({+ status: 400, code: "connection_in_use", message: "remove this connection from the portfolio before deleting it",+ });+ });+it("translates the server's message-size error into a recovery instruction", async () => {vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({detail: { code: "message_too_long", max_length: 100_000, message: "Shorten input" },