Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

ci: eliminate backend and frontend warnings (#873)

Albert Dolkunc444a3195688
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 41bddc7e..d86b944f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -84,7 +84,7 @@ jobs:
- name: Run tests with coverage
if: steps.backend-changes.outputs.run_backend == 'true'
run: |
- pytest -n auto --dist loadfile --cov=app --cov-report=xml --cov-report=term-missing --cov-fail-under=60
+ pytest -n auto --dist loadfile --cov=app --cov-report=xml --cov-report=term-missing --cov-fail-under=60 -ra -W error
- name: Upload coverage report
if: ${{ always() && steps.backend-changes.outputs.run_backend == 'true' }}
@@ -147,7 +147,7 @@ jobs:
run: npm ci
- name: Lint
- run: npm run lint
+ run: npm run lint -- --max-warnings=0
- name: Type check & Build
run: npm run build
diff --git a/backend/app/api/assets.py b/backend/app/api/assets.py
index d520c76f..90b4e0d3 100644
--- a/backend/app/api/assets.py
+++ b/backend/app/api/assets.py
@@ -132,7 +132,7 @@ async def refresh_asset_price(
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")
if asset.valuation_method != "market_price":
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="Only externally priced assets can be refreshed via this endpoint",
)
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 2ec97033..0530506c 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -132,7 +132,7 @@ async def list_transactions(
min_amount: Optional[float] = Query(None, ge=0, description="Filter to transactions with absolute amount >= this value (primary currency)."),
max_amount: Optional[float] = Query(None, ge=0, description="Filter to transactions with absolute amount <= this value (primary currency)."),
sort_by: Optional[str] = Query(None, description="Column to sort by (date|amount|description|payee|category|account|type|status). Default: date desc."),
- sort_dir: str = Query("desc", regex="^(asc|desc)$"),
+ sort_dir: str = Query("desc", pattern="^(asc|desc)$"),
ctx: WorkspaceContext = Depends(current_workspace),
session: AsyncSession = Depends(get_async_session),
):
@@ -548,7 +548,7 @@ async def unlink_recurring_transaction(
@router.delete("/{transaction_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_transaction(
transaction_id: uuid.UUID,
- apply_to: str = Query("this", regex="^(this|future|all)$", description="Installment-series scope: this row only (default), this + later installments, or the whole series. Ignored for non-installment transactions."),
+ apply_to: str = Query("this", pattern="^(this|future|all)$", description="Installment-series scope: this row only (default), this + later installments, or the whole series. Ignored for non-installment transactions."),
ctx: WorkspaceContext = Depends(current_writable_workspace),
session: AsyncSession = Depends(get_async_session),
):
diff --git a/backend/app/schemas/workspace.py b/backend/app/schemas/workspace.py
index d17e62ea..94dba025 100644
--- a/backend/app/schemas/workspace.py
+++ b/backend/app/schemas/workspace.py
@@ -2,7 +2,7 @@ import uuid
from datetime import datetime
from typing import Optional
-from pydantic import BaseModel, EmailStr, Field
+from pydantic import BaseModel, ConfigDict, EmailStr, Field
from app.models.workspace import WorkspaceKind
@@ -34,8 +34,7 @@ class WorkspaceRead(BaseModel):
# sees a module the server thinks is off.
enabled_modules: list[str] = []
- class Config:
- from_attributes = True
+ model_config = ConfigDict(from_attributes=True)
class WorkspaceCreate(BaseModel):
@@ -76,8 +75,7 @@ class MemberRead(BaseModel):
role: str
joined_at: datetime
- class Config:
- from_attributes = True
+ model_config = ConfigDict(from_attributes=True)
class MemberInvite(BaseModel):
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.py
index fa8d7930..7a1f6459 100644
--- a/backend/app/services/asset_service.py
+++ b/backend/app/services/asset_service.py
@@ -432,12 +432,12 @@ async def create_asset(
if data.valuation_method == "market_price":
if not data.ticker:
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="ticker is required for market_price assets",
)
if data.units is None or data.units <= 0:
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="units (quantity) must be > 0 for market_price assets",
)
provider = market_provider or get_market_price_provider()
diff --git a/backend/app/services/asset_transaction_service.py b/backend/app/services/asset_transaction_service.py
index afa30f93..ae2239f0 100644
--- a/backend/app/services/asset_transaction_service.py
+++ b/backend/app/services/asset_transaction_service.py
@@ -121,7 +121,7 @@ def _raise_if_oversell(transactions: list[AssetTransaction]) -> None:
attempted, available = over
fmt = lambda q: f"{q:.6f}".rstrip("0").rstrip(".") # noqa: E731
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail=(
f"Cannot sell {fmt(attempted)} units — only {fmt(available)} held at that date. "
"Short positions aren't supported."
@@ -233,17 +233,17 @@ async def list_workspace_transactions(
def _validate(kind: str, quantity: Decimal, price: Decimal) -> None:
if kind not in _VALID_KINDS:
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="kind must be 'buy' or 'sell'",
)
if quantity is None or quantity <= 0:
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="quantity must be > 0",
)
if price is None or price < 0:
raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="price must be >= 0",
)
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index a9f84b85..94eff8f2 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -3,10 +3,12 @@ import hashlib
import io
import re
import uuid
+import warnings
import xml.etree.ElementTree as ET
from datetime import datetime
from decimal import Decimal
+from bs4 import XMLParsedAsHTMLWarning
from ofxparse import OfxParser
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -139,7 +141,25 @@ def _is_balance_summary_row(description: str | None) -> bool:
def parse_ofx(content: bytes) -> list[TransactionImport]:
"""Parse OFX file content and return transactions."""
content = _preprocess_ofx(content)
- ofx = OfxParser.parse(io.BytesIO(content))
+ # ofxparse 0.21 intentionally parses normalized SGML/XML with html.parser
+ # and still calls BeautifulSoup's findAll alias. Keep this compatibility
+ # boundary local; remove it when ofxparse adopts the supported soup API.
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ message=(
+ r"^Call to deprecated method findAll\. \(Replaced by find_all\) "
+ r"-- Deprecated since version 4\.0\.0\.$"
+ ),
+ category=DeprecationWarning,
+ module=r"^ofxparse\.ofxparse$",
+ )
+ warnings.filterwarnings(
+ "ignore",
+ category=XMLParsedAsHTMLWarning,
+ module=r"^ofxparse\.ofxparse$",
+ )
+ ofx = OfxParser.parse(io.BytesIO(content))
transactions = []
for account in ofx.accounts:
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 77f64a9b..82be07bb 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -3,7 +3,7 @@ import uuid
from datetime import date, datetime, timezone
from decimal import Decimal
from typing import AsyncGenerator
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
# --- Agents test setup (must run BEFORE app.main is imported) ---------------
# Force the optional agents feature on for the test process so the routes
@@ -12,6 +12,10 @@ from unittest.mock import AsyncMock, patch
os.environ.setdefault("AGENTS_ENABLED", "true")
os.environ.setdefault("AGENTS_MCP_JWT_SECRET", "test-secret-not-for-production")
os.environ.setdefault("AGENTS_BUILTIN_MCP_URL", "http://test-mcp:8765/mcp")
+# Tests use synthetic credentials, never local deployment secrets. Explicit
+# Settings(_secrets_dir=...) tests still exercise secret-file loading.
+os.environ["SECRET_KEY"] = "synthetic-test-signing-key-not-for-production"
+os.environ["CREDENTIALS_DIRECTORY"] = ""
# pgvector's Vector type only compiles on PostgreSQL. Tests use SQLite, so
# we shim it with JSON before any model module imports it. Production runs
@@ -559,12 +563,14 @@ async def test_user_with_2fa(session: AsyncSession, clean_db) -> User:
def _mock_redis():
"""Provide a no-op Redis mock so rate limiting never blocks tests."""
mock = AsyncMock()
- # Pipeline mock that always reports 0 prior requests (never rate-limits)
- pipe_mock = AsyncMock()
- pipe_mock.zremrangebyscore = AsyncMock()
- pipe_mock.zcard = AsyncMock()
- pipe_mock.zadd = AsyncMock()
- pipe_mock.expire = AsyncMock()
+ # Pipeline commands are synchronous/chained on redis-py's pipeline; only
+ # execute() is awaited. Match that contract so requests create no unawaited
+ # mock coroutines, while still reporting zero prior requests.
+ pipe_mock = MagicMock()
+ pipe_mock.zremrangebyscore = MagicMock(return_value=pipe_mock)
+ pipe_mock.zcard = MagicMock(return_value=pipe_mock)
+ pipe_mock.zadd = MagicMock(return_value=pipe_mock)
+ pipe_mock.expire = MagicMock(return_value=pipe_mock)
pipe_mock.execute = AsyncMock(return_value=[0, 0, True, True])
mock.pipeline = lambda: pipe_mock
# Key-value ops for 2FA temp tokens
diff --git a/backend/tests/test_agents_connections.py b/backend/tests/test_agents_connections.py
index 658d7994..25539de7 100644
--- a/backend/tests/test_agents_connections.py
+++ b/backend/tests/test_agents_connections.py
@@ -13,9 +13,6 @@ from app.agents.services.crypto import decrypt, encrypt
from app.models.user import User
-pytestmark = pytest.mark.asyncio
-
-
# --- Encryption ------------------------------------------------------------
def test_encrypt_decrypt_roundtrip():
diff --git a/backend/tests/test_agents_mcp_tools.py b/backend/tests/test_agents_mcp_tools.py
index 0409393c..60b12858 100644
--- a/backend/tests/test_agents_mcp_tools.py
+++ b/backend/tests/test_agents_mcp_tools.py
@@ -17,9 +17,6 @@ from mcp_server.auth import CallContext
from mcp_server.registry import REGISTRY
-pytestmark = pytest.mark.asyncio
-
-
@pytest_asyncio.fixture
async def ctx(test_user) -> CallContext:
return CallContext(user_id=test_user.id, conversation_id=uuid.uuid4())
diff --git a/backend/tests/test_agents_providers.py b/backend/tests/test_agents_providers.py
index 72442d20..551cffe8 100644
--- a/backend/tests/test_agents_providers.py
+++ b/backend/tests/test_agents_providers.py
@@ -32,9 +32,6 @@ from app.agents.providers.openai import (
)
-pytestmark = pytest.mark.asyncio
-
-
def test_registry_lists_all_four_providers():
assert set(list_providers()) == {"ollama", "openai", "anthropic", "openai_compatible"}
diff --git a/backend/tests/test_api_extended.py b/backend/tests/test_api_extended.py
index 9d9b9e3a..2f32502b 100644
--- a/backend/tests/test_api_extended.py
+++ b/backend/tests/test_api_extended.py
@@ -194,8 +194,7 @@ async def test_install_rule_pack(client: AsyncClient, auth_headers, test_categor
# First list packs to get a valid code
packs_resp = await client.get("/api/rules/packs", headers=auth_headers)
packs = packs_resp.json()
- if not packs:
- pytest.skip("No rule packs available")
+ assert packs, "the bundled rule packs must be available"
pack_code = packs[0]["code"]
response = await client.post(
diff --git a/backend/tests/test_attachment_service.py b/backend/tests/test_attachment_service.py
index 9742773e..81338424 100644
--- a/backend/tests/test_attachment_service.py
+++ b/backend/tests/test_attachment_service.py
@@ -23,9 +23,6 @@ from app.services.attachment_service import (
)
-pytestmark = pytest.mark.asyncio
-
-
# ---------------------------------------------------------------------------
# sanitize_filename — pure function
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py
index 3f635987..2dc8fa79 100644
--- a/backend/tests/test_config.py
+++ b/backend/tests/test_config.py
@@ -25,10 +25,11 @@ def test_env_file_is_anchored_to_backend_dir():
assert backend_env in tuple(Path(p) for p in env_files)
-def test_env_file_with_unknown_keys_still_loads(tmp_path: Path, secrets: Path):
+def test_env_file_with_unknown_keys_still_loads(tmp_path: Path, secrets: Path, monkeypatch):
"""The .env is shared with Docker Compose and the optional modules, so it
holds keys Settings doesn't declare (COMPOSE_PROFILES, FRONTEND_PORT,
AGENTS_*). Unknown keys must be ignored, not abort startup."""
+ monkeypatch.delenv("SECRET_KEY")
env_file = tmp_path / ".env"
env_file.write_text(
"SECRET_KEY=from-env-file\n"
diff --git a/backend/tests/test_dashboard_service_coverage.py b/backend/tests/test_dashboard_service_coverage.py
index e1f2efee..ef0fe6b9 100644
--- a/backend/tests/test_dashboard_service_coverage.py
+++ b/backend/tests/test_dashboard_service_coverage.py
@@ -37,6 +37,18 @@ from app.services.dashboard_service import (
# ---------------------------------------------------------------------------
+def projection_today(monkeypatch):
+ """Keep current-month projection cases away from the last day of a month."""
+ class ProjectionDate(date):
+ @classmethod
+ def today(cls):
+ return cls(2026, 1, 15)
+
+ monkeypatch.setattr("app.services.dashboard_service.date", ProjectionDate)
+ return ProjectionDate.today()
+
+
async def _seed_fx(session, today=None):
"""USD->BRL=5.0, USD->EUR=0.9, USD->USD=1.0."""
today = today or date.today()
@@ -384,18 +396,17 @@ async def test_daily_deltas_multi_currency(session, test_user, test_workspace):
@pytest.mark.asyncio
-async def test_balance_history_with_future_projections(session, test_user, test_workspace):
- today = date.today()
+async def test_balance_history_with_future_projections(
+ session, test_user, test_workspace, projection_today
+):
+ today = projection_today
month_start = today.replace(day=1)
acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")
await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1000, "credit", month_start, source="opening_balance")
# Daily recurring whose next occurrence is in the future -> future days
- # get projection deltas (lines 979-985). Skip on the last day of the month
- # when no future days remain.
+ # get projection deltas even when the suite runs at a month boundary.
next_day = today + timedelta(days=1)
- if next_day.month != today.month:
- pytest.skip("no future days left in current month")
rec = RecurringTransaction(
id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
description="Daily", amount=Decimal("5"), type="credit",
@@ -470,14 +481,11 @@ async def test_monthly_trend(session, test_user, test_workspace):
@pytest.mark.asyncio
async def test_summary_current_month_projection_only_adjusts_projected_balance(
- session, test_user, test_workspace
+ session, test_user, test_workspace, projection_today
):
"""Future recurring rows affect projected, never current, balance."""
- today = date.today()
+ today = projection_today
month_start = today.replace(day=1)
- # Only run when there's at least one future day in the month.
- if (month_start + timedelta(days=40)).replace(day=1) - timedelta(days=1) <= today:
- pytest.skip("no future days left in current month")
acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")
await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1000, "credit", month_start, source="opening_balance")
diff --git a/backend/tests/test_goal_service_coverage.py b/backend/tests/test_goal_service_coverage.py
index bcccf767..d1c0d1c6 100644
--- a/backend/tests/test_goal_service_coverage.py
+++ b/backend/tests/test_goal_service_coverage.py
@@ -7,6 +7,7 @@ each tracking_type, enrich currency conversion, get/update/delete/summary).
import uuid
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
+from unittest.mock import patch
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
@@ -156,19 +157,10 @@ def test_monthly_contribution_normal():
def test_monthly_contribution_months_clamped_to_one():
# Target date in the same calendar month but a later day -> months == 0,
# clamped to 1 (line 111). today < target_date so we don't hit the past branch.
- today = date.today()
- if today.day < 28:
- target = today.replace(day=28)
- val = _compute_monthly_contribution(Decimal("0"), Decimal("500"), target)
- assert val == 500.0 # remaining / 1 month
- else:
- # Last days of month: just assert it returns a value (same-month edge)
- target = today + timedelta(days=1)
- if target.month == today.month:
- val = _compute_monthly_contribution(Decimal("0"), Decimal("500"), target)
- assert val == 500.0
- else:
- pytest.skip("month boundary makes same-month clamp untestable today")
+ with patch("app.services.goal_service.date", wraps=date) as clock:
+ clock.today.return_value = date(2026, 1, 15)
+ val = _compute_monthly_contribution(Decimal("0"), Decimal("500"), date(2026, 1, 28))
+ assert val == 500.0 # remaining / 1 month
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_import_warnings.py b/backend/tests/test_import_warnings.py
new file mode 100644
index 00000000..f5889b71
--- /dev/null
+++ b/backend/tests/test_import_warnings.py
@@ -0,0 +1,63 @@
+"""The OFX compatibility boundary hides only known dependency warnings."""
+
+import warnings
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+from bs4 import XMLParsedAsHTMLWarning
+
+from app.services.import_service import parse_ofx
+
+
+FIND_ALL_WARNING = (
+ "Call to deprecated method findAll. (Replaced by find_all) "
+ "-- Deprecated since version 4.0.0."
+)
+
+
+def test_known_ofx_warnings_are_scoped_to_the_parser():
+ def parse(stream):
+ warnings.warn_explicit(
+ FIND_ALL_WARNING, DeprecationWarning, "ofxparse.py", 1, module="ofxparse.ofxparse"
+ )
+ warnings.warn_explicit(
+ "XML parsed as HTML", XMLParsedAsHTMLWarning,
+ "ofxparse.py", 2, module="ofxparse.ofxparse",
+ )
+ return SimpleNamespace(accounts=[])
+
+ with patch("app.services.import_service.OfxParser.parse", side_effect=parse), \
+ warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert parse_ofx(b"") == []
+ # The same warning outside the parser must not inherit its filter.
+ with pytest.raises(DeprecationWarning, match="findAll"):
+ warnings.warn_explicit(
+ FIND_ALL_WARNING, DeprecationWarning,
+ "ofxparse.py", 1, module="ofxparse.ofxparse",
+ )
+
+
[email protected]("message,module", [
+ ("a new parser deprecation", "ofxparse.ofxparse"),
+ (FIND_ALL_WARNING, "unrelated_dependency"),
+])
+def test_unrelated_ofx_warnings_are_visible(message, module):
+ def parse(stream):
+ warnings.warn_explicit(message, DeprecationWarning, "parser.py", 1, module=module)
+ return SimpleNamespace(accounts=[])
+
+ with patch("app.services.import_service.OfxParser.parse", side_effect=parse), \
+ pytest.warns(DeprecationWarning) as captured:
+ assert parse_ofx(b"") == []
+ assert len(captured) == 1
+ assert str(captured[0].message) == message
+
+
+def test_parser_errors_are_not_suppressed():
+ error = ValueError("synthetic invalid OFX")
+ with patch("app.services.import_service.OfxParser.parse", side_effect=error), \
+ pytest.raises(ValueError) as raised:
+ parse_ofx(b"")
+ assert raised.value is error
diff --git a/backend/tests/test_invoice_document.py b/backend/tests/test_invoice_document.py
index 7f423fab..619dd15f 100644
--- a/backend/tests/test_invoice_document.py
+++ b/backend/tests/test_invoice_document.py
@@ -236,7 +236,6 @@ class TestDocument:
# ---------------------------------------------------------------------------
# PDF
# ---------------------------------------------------------------------------
class TestPdf:
async def test_downloads_a_real_pdf(self, client: AsyncClient, biz_headers, client_payee):
invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))
@@ -1024,7 +1023,8 @@ def test_an_oversized_raster_is_refused_before_it_is_decoded():
_Image.new("RGB", (10000, 10000), (255, 0, 0)).save(buf, format="PNG")
assert len(buf.getvalue()) < 1_000_000, "the point is that it is small"
- with pytest.raises(ValueError, match="megapixels"):
+ with pytest.warns(_Image.DecompressionBombWarning, match="Image size"), \
+ pytest.raises(ValueError, match="megapixels"):
invoice_logo_service.normalise(buf.getvalue(), "image/png")
diff --git a/backend/tests/test_invoices_api.py b/backend/tests/test_invoices_api.py
index a0be0d5e..7d828174 100644
--- a/backend/tests/test_invoices_api.py
+++ b/backend/tests/test_invoices_api.py
@@ -10,8 +10,9 @@ Two things these tests exist to pin down, beyond the usual CRUD:
UI does, computed from allocations and the due date.
"""
import uuid
-from datetime import date, timedelta
+from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
+from unittest.mock import patch
import pytest
import pytest_asyncio
@@ -23,6 +24,14 @@ from app.models.payee import Payee
from app.models.transaction import Transaction
+def invoice_today():
+ """Pin the service clock so UTC/local midnight cannot change expectations."""
+ with patch("app.services.invoice_service.datetime", wraps=datetime) as clock:
+ clock.now.return_value = datetime(2026, 1, 15, tzinfo=timezone.utc)
+ yield clock.now.return_value.date()
+
+
@pytest_asyncio.fixture
async def personal_ws(session: AsyncSession, test_user):
"""The user's personal workspace, resolved by kind.
@@ -338,13 +347,13 @@ async def test_unlinking_restores_both_sides(client: AsyncClient, biz_headers, i
@pytest.mark.asyncio
-async def test_overdue_needs_no_job(client: AsyncClient, biz_headers):
+async def test_overdue_needs_no_job(client: AsyncClient, biz_headers, invoice_today):
"""The point of deriving: nothing ran, and it still reads overdue."""
invoice = await _create(
client,
biz_headers,
- issue_date=str(date.today() - timedelta(days=40)),
- due_date=str(date.today() - timedelta(days=10)),
+ issue_date=str(invoice_today - timedelta(days=40)),
+ due_date=str(invoice_today - timedelta(days=10)),
)
resp = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
assert resp.json()["state"] == "overdue"
@@ -565,13 +574,15 @@ async def test_competence_date_defaults_to_issue_but_can_diverge(
@pytest.mark.asyncio
-async def test_due_date_defaults_to_payment_terms(client: AsyncClient, biz_headers):
+async def test_due_date_defaults_to_payment_terms(
+ client: AsyncClient, biz_headers, invoice_today
+):
await client.patch(
"/api/invoices/settings", headers=biz_headers, json={"default_payment_terms_days": 7}
)
resp = await client.post("/api/invoices", headers=biz_headers, json={"total": "10.00"})
assert resp.status_code == 201, resp.text
- assert resp.json()["due_date"] == str(date.today() + timedelta(days=7))
+ assert resp.json()["due_date"] == str(invoice_today + timedelta(days=7))
@pytest.mark.asyncio
diff --git a/backend/tests/test_passkeys.py b/backend/tests/test_passkeys.py
index b6cd2b6b..b6bd060e 100644
--- a/backend/tests/test_passkeys.py
+++ b/backend/tests/test_passkeys.py
@@ -1,6 +1,6 @@
from datetime import datetime
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from httpx import AsyncClient
@@ -18,11 +18,11 @@ class _RedisStore:
self.getdel = AsyncMock(side_effect=self._getdel)
self.set = AsyncMock(side_effect=self._set)
self.delete = AsyncMock(side_effect=self._delete)
- pipe = AsyncMock()
- pipe.zremrangebyscore = AsyncMock()
- pipe.zcard = AsyncMock()
- pipe.zadd = AsyncMock()
- pipe.expire = AsyncMock()
+ pipe = MagicMock()
+ pipe.zremrangebyscore = MagicMock(return_value=pipe)
+ pipe.zcard = MagicMock(return_value=pipe)
+ pipe.zadd = MagicMock(return_value=pipe)
+ pipe.expire = MagicMock(return_value=pipe)
pipe.execute = AsyncMock(return_value=[0, 0, True, True])
self.pipeline = lambda: pipe
diff --git a/backend/tests/test_write_permission_coverage.py b/backend/tests/test_write_permission_coverage.py
index 51305892..c387bac5 100644
--- a/backend/tests/test_write_permission_coverage.py
+++ b/backend/tests/test_write_permission_coverage.py
@@ -21,6 +21,7 @@ change it should survive.
import pytest
from fastapi.routing import APIRoute
+from app.core.auth import current_superuser
from app.main import app
MUTATING = {"POST", "PATCH", "PUT", "DELETE"}
@@ -96,6 +97,22 @@ ALLOWLIST: dict[tuple[str, str], str] = {
("POST", "/api/fx-rates/refresh"): "refreshes instance-wide FX rates, no workspace data",
}
+# These routes establish authentication (or end it), so requiring an existing
+# user would prevent the operation. All other exemptions still require a user.
+PUBLIC_ROUTES = {
+ ("POST", path) for path in (
+ "/login", "/logout", "/register", "/forgot-password", "/reset-password",
+ "/2fa/verify", "/passkeys/authenticate/options", "/passkeys/authenticate/verify",
+ "/passkeys/2fa/options", "/passkeys/2fa/verify", "/api/setup/create-admin",
+ )
+}
+WORKSPACE_READ_ROUTES = {
+ ("POST", path) for path in (
+ "/api/transactions/import/preview", "/api/assets/import/preview",
+ "/api/rules/preview", "/api/export/backup",
+ )
+}
+
def _api_routes(routes):
"""Descend through FastAPI's lazily-included routers.
@@ -123,6 +140,10 @@ def _dependency_names(route: APIRoute) -> set[str]:
seen.add(id(dependant))
if dependant.call is not None:
names.add(getattr(dependant.call, "__name__", str(dependant.call)))
+ # fastapi-users gives active-user and superuser closures the same
+ # name; compare identity before recording the stricter decision.
+ if dependant.call is current_superuser:
+ names.add("current_superuser")
stack.extend(dependant.dependencies)
return names
@@ -147,11 +168,20 @@ def test_the_walk_actually_finds_the_routes():
"method,path", ALL_MUTATING, ids=[f"{m} {p}" for m, p in ALL_MUTATING]
)
def test_a_mutating_route_declares_a_permission_decision(method, path):
- if (method, path) in ALLOWLIST:
- pytest.skip(f"allowlisted: {ALLOWLIST[(method, path)]}")
-
route = next(r for m, p, r in _mutating_routes() if (m, p) == (method, path))
names = _dependency_names(route)
+ if (method, path) in ALLOWLIST:
+ assert ALLOWLIST[(method, path)].strip(), "an exemption needs a reason"
+ assert not names & WRITE_GATES, "remove the redundant write-gate exemption"
+ if (method, path) in PUBLIC_ROUTES:
+ assert "current_user_dependency" not in names, "login cannot require an existing user"
+ else:
+ assert "current_user_dependency" in names, "the exemption still requires authentication"
+ if (method, path) in WORKSPACE_READ_ROUTES:
+ assert "current_workspace" in names, "read-only does not mean cross-workspace"
+ if path.startswith("/api/admin/"):
+ assert "current_superuser" in names, "instance administration requires a superuser"
+ return
assert names & WRITE_GATES, (
f"{method} {path} mutates but reaches no write gate.\n"
f"Add `ctx: WorkspaceContext = Depends(current_writable_workspace)`, "
@@ -165,6 +195,7 @@ def test_the_allowlist_has_no_stale_entries():
reusing the path."""
stale = sorted(set(ALLOWLIST) - set(ALL_MUTATING))
assert stale == [], f"allowlist entries matching no route: {stale}"
+ assert PUBLIC_ROUTES | WORKSPACE_READ_ROUTES <= set(ALLOWLIST)
def test_nothing_allowlisted_is_already_gated():
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 8efea0d9..66c69065 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4,9 +4,9 @@ import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { Toaster } from '@/components/ui/sonner'
import { TooltipProvider } from '@/components/ui/tooltip'
import { ThemeProvider } from '@/components/theme-provider'
-import { AuthProvider } from '@/contexts/auth-context'
-import { WorkspaceProvider } from '@/contexts/workspace-context'
-import { CollectionFilterProvider } from '@/contexts/collection-filter-context'
+import { AuthProvider } from '@/contexts/auth-provider'
+import { WorkspaceProvider } from '@/contexts/workspace-provider'
+import { CollectionFilterProvider } from '@/contexts/collection-filter-provider'
import { ProtectedRoute } from '@/components/protected-route'
import { AdminRoute } from '@/components/admin-route'
import { AgentsRoute } from '@/components/agents-route'
diff --git a/frontend/src/components/account-icon.tsx b/frontend/src/components/account-icon.tsx
index 34a8d8bf..1d2e32ef 100644
--- a/frontend/src/components/account-icon.tsx
+++ b/frontend/src/components/account-icon.tsx
@@ -1,24 +1,8 @@
-import { useState, type ElementType } from 'react'
-import { Building2, PiggyBank, CreditCard, TrendingUp, Wallet } from 'lucide-react'
+import { useState } from 'react'
+import { Building2 } from 'lucide-react'
+import { getAccountTypeConfig } from '@/lib/account-type-config'
import { cn } from '@/lib/utils'
-// Account-type → icon/color, the fallback shown when an account has no bank
-// logo (manual accounts, and connected accounts whose provider exposes none).
-export const ACCOUNT_TYPE_CONFIG: Record<
- string,
- { icon: ElementType; color: string; bg: string; label: string }
-> = {
- checking: { icon: Building2, color: 'text-indigo-600', bg: 'bg-indigo-100', label: 'accounts.typeChecking' },
- savings: { icon: PiggyBank, color: 'text-emerald-600', bg: 'bg-emerald-100', label: 'accounts.typeSavings' },
- credit_card: { icon: CreditCard, color: 'text-violet-600', bg: 'bg-violet-100', label: 'accounts.typeCreditCard' },
- investment: { icon: TrendingUp, color: 'text-amber-600', bg: 'bg-amber-100', label: 'accounts.typeInvestment' },
- wallet: { icon: Wallet, color: 'text-rose-600', bg: 'bg-rose-100', label: 'accounts.typeWallet' },
-}
-
-export function getAccountTypeConfig(type: string) {
- return ACCOUNT_TYPE_CONFIG[type] ?? ACCOUNT_TYPE_CONFIG['checking']
-}
-
const SIZES = {
xs: { tile: 'w-5 h-5', icon: 11 },
sm: { tile: 'w-6 h-6', icon: 12 },
diff --git a/frontend/src/components/agents/chat-panel.tsx b/frontend/src/components/agents/chat-panel.tsx
index 02ff667a..10ec3897 100644
--- a/frontend/src/components/agents/chat-panel.tsx
+++ b/frontend/src/components/agents/chat-panel.tsx
@@ -1,3 +1,4 @@
+import { isProposalData, isProposalToolName } from '@/lib/agent-proposals'
import { useEffect, useMemo, useRef, useState } from 'react'
import { ShellLogo } from '@/components/shell-logo'
import { useQuery, useQueryClient } from '@tanstack/react-query'
@@ -9,7 +10,7 @@ import type { Agent, AgentMessage } from '@/lib/api'
import { streamChat, type AgentStreamEvent } from '@/lib/agents-stream'
import { Markdown } from '@/components/agents/markdown'
import { ToolDebugChip } from '@/components/agents/tool-debug-chip'
-import { ProposalCard, isProposalData, isProposalToolName } from '@/components/agents/proposal-card'
+import { ProposalCard } from '@/components/agents/proposal-card'
interface Props {
agent: Agent
diff --git a/frontend/src/components/agents/connection-form-dialog.tsx b/frontend/src/components/agents/connection-form-dialog.tsx
index 1c3e04f0..cbdee7b8 100644
--- a/frontend/src/components/agents/connection-form-dialog.tsx
+++ b/frontend/src/components/agents/connection-form-dialog.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
@@ -61,7 +61,9 @@ export function ConnectionFormDialog({ open, onOpenChange, connection }: Props)
setDefaultModel(KIND_LABELS[newKind].defaultModel ?? '')
}
- useEffect(() => {
+ const [formSource, setFormSource] = useState<{ connection: typeof connection; open: typeof open } | null>(null)
+ if (!formSource || formSource.connection !== connection || formSource.open !== open) {
+ setFormSource({ connection, open })
if (connection) {
setName(connection.name)
setKind(connection.kind)
@@ -86,7 +88,7 @@ export function ConnectionFormDialog({ open, onOpenChange, connection }: Props)
setModelTouched(false)
setIsDefault(false)
}
- }, [connection, open])
+ }
const meta = KIND_LABELS[kind]
diff --git a/frontend/src/components/agents/proposal-card.tsx b/frontend/src/components/agents/proposal-card.tsx
index f7fb5d71..1c8ca432 100644
--- a/frontend/src/components/agents/proposal-card.tsx
+++ b/frontend/src/components/agents/proposal-card.tsx
@@ -14,30 +14,7 @@ import {
transactions,
} from '@/lib/api'
-type ProposalKind =
- | 'categorize'
- | 'create_category'
- | 'create_budget'
- | 'create_payee_rule'
- | 'create_transaction'
- | 'create_recurring_transaction'
- | 'update_recurring_transaction'
- | 'cancel_recurring_transaction'
- | 'create_goal'
-
-interface ProposalData {
- kind?: ProposalKind
- proposed?: Record<string, unknown>
- target?: Record<string, unknown>
- changes?: Record<string, unknown>
- affected?: { id: string; description?: string; amount?: number; currency?: string }[]
- affected_count?: number
- target_category?: { id: string; name: string }
- name_collision?: { id: string; name: string }
- mode?: 'deactivate' | 'delete'
- apply_endpoint?: string
- error?: string
-}
+import type { ProposalKind, ProposalData } from '@/lib/agent-proposals'
interface Props {
toolCallId: string
@@ -409,22 +386,3 @@ async function applyProposal(data: ProposalData): Promise<string | void> {
}
}
}
-
-/** Heuristic: a tool result is a proposal if its data has a known kind. */
-export function isProposalData(data: unknown): data is ProposalData {
- if (!data || typeof data !== 'object') return false
- const k = (data as { kind?: unknown }).kind
- return typeof k === 'string' && [
- 'categorize', 'create_category', 'create_budget', 'create_payee_rule',
- 'create_transaction', 'create_recurring_transaction',
- 'update_recurring_transaction', 'cancel_recurring_transaction',
- 'create_goal',
- ].includes(k)
-}
-
-/** Treat the data as a proposal even when only `error` is present, since
- * a proposal that failed validation should still render a small error card
- * instead of a generic tool-debug chip. */
-export function isProposalToolName(name: string): boolean {
- return name.includes('propose_')
-}
diff --git a/frontend/src/components/bank-connect-dialog.tsx b/frontend/src/components/bank-connect-dialog.tsx
index e2815516..0965bffb 100644
--- a/frontend/src/components/bank-connect-dialog.tsx
+++ b/frontend/src/components/bank-connect-dialog.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import { useState, useEffect, useEffectEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useQueryClient } from '@tanstack/react-query'
import { PluggyConnect } from 'react-pluggy-connect'
@@ -40,6 +40,11 @@ export function BankConnectDialog({
// Only prompt for asset-sync when the provider actually imports holdings.
const needsInitialOptions = !reconnectConnectionId && supportsAssetSync
+ const onTokenError = useEffectEvent(() => {
+ toast.error(t('accounts.connectError'))
+ onClose()
+ })
+
useEffect(() => {
if (!open) {
setConnectToken(null)
@@ -59,8 +64,7 @@ export function BankConnectDialog({
if (!cancelled) setConnectToken(token)
} catch {
if (!cancelled) {
- toast.error(t('accounts.connectError'))
- onClose()
+ onTokenError()
}
}
}
diff --git a/frontend/src/components/connect-dialogs.test.tsx b/frontend/src/components/connect-dialogs.test.tsx
new file mode 100644
index 00000000..38f1875f
--- /dev/null
+++ b/frontend/src/components/connect-dialogs.test.tsx
@@ -0,0 +1,79 @@
+import { act, screen } from '@testing-library/react'
+import { beforeEach, expect, it, vi } from 'vitest'
+import { renderWithProviders } from '@/test/utils'
+import { ConnectorSelectDialog } from './connector-select-dialog'
+import { OAuthConnectDialog } from './oauth-connect-dialog'
+import { BankConnectDialog } from './bank-connect-dialog'
+
+const api = vi.hoisted(() => ({ getProviders: vi.fn(), listInstitutions: vi.fn(), getReconnectToken: vi.fn(), getConnectToken: vi.fn(), toastError: vi.fn() }))
+vi.mock('@/lib/api', () => ({ connections: api, auth: api }))
+vi.mock('sonner', () => ({ toast: { error: api.toastError } }))
+vi.mock('react-pluggy-connect', () => ({ PluggyConnect: ({ connectToken }: { connectToken: string }) => <div>{connectToken}</div> }))
+
+beforeEach(() => { vi.resetAllMocks() })
+
+it('ignores provider responses from a closed session when reopened', async () => {
+ let finish!: (data: unknown) => void
+ api.getProviders.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
+ .mockResolvedValueOnce([{ name: 'new', display_name: 'New provider', description: 'Synthetic', configured: true }])
+ const props = { onClose: vi.fn(), onSelect: vi.fn() }
+ const { rerender } = renderWithProviders(<ConnectorSelectDialog open {...props} />)
+ rerender(<ConnectorSelectDialog open={false} {...props} />)
+ rerender(<ConnectorSelectDialog open {...props} />)
+ await screen.findByText('New provider')
+ await act(async () => { finish([{ name: 'old', display_name: 'Old provider', configured: true }]) })
+ expect(screen.queryByText('Old provider')).not.toBeInTheDocument()
+ expect(screen.getByText('New provider')).toBeInTheDocument()
+})
+
+it('ignores an earlier country request after back navigation and another selection', async () => {
+ let finish!: (data: unknown) => void
+ api.listInstitutions.mockResolvedValueOnce({ countries: ['DE', 'GB'] })
+ .mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
+ .mockResolvedValueOnce({ institutions: [{ country: 'GB', name: 'new', display_name: 'New bank' }] })
+ const { user } = renderWithProviders(<OAuthConnectDialog open provider="synthetic" onClose={vi.fn()} />)
+ await user.click(await screen.findByText('DE'))
+ await user.click(screen.getByRole('button', { name: 'Back' }))
+ await user.click(screen.getByText('GB'))
+ await screen.findByText('New bank')
+ await act(async () => { finish({ institutions: [{ country: 'DE', name: 'old', display_name: 'Old bank' }] }) })
+ expect(screen.queryByText('Old bank')).not.toBeInTheDocument()
+ expect(screen.getByText('New bank')).toBeInTheDocument()
+})
+
+it('waits for banks in the remembered country instead of showing an empty result', async () => {
+ localStorage.setItem('securo:lastOAuthCountry', 'DE')
+ let finish!: (data: unknown) => void
+ api.listInstitutions.mockResolvedValueOnce({ countries: ['DE'] })
+ .mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
+ renderWithProviders(<OAuthConnectDialog open provider="synthetic" onClose={vi.fn()} />)
+ await screen.findByRole('button', { name: 'Back' })
+ expect(screen.queryByText('No institutions found.')).not.toBeInTheDocument()
+ await act(async () => { finish({ institutions: [{ country: 'DE', name: 'bank', display_name: 'Remembered bank' }] }) })
+ expect(screen.getByText('Remembered bank')).toBeInTheDocument()
+})
+
+it('uses the latest close callback without restarting a bank token request', async () => {
+ let reject!: (error: Error) => void
+ api.getReconnectToken.mockImplementation(() => new Promise((_, fail) => { reject = fail }))
+ const firstClose = vi.fn()
+ const latestClose = vi.fn()
+ const { rerender } = renderWithProviders(<BankConnectDialog open reconnectConnectionId="synthetic" onClose={firstClose} />)
+ rerender(<BankConnectDialog open reconnectConnectionId="synthetic" onClose={latestClose} />)
+ expect(api.getReconnectToken).toHaveBeenCalledTimes(1)
+ await act(async () => { reject(new Error('synthetic failure')) })
+ expect(firstClose).not.toHaveBeenCalled()
+ expect(latestClose).toHaveBeenCalledOnce()
+ expect(api.toastError).toHaveBeenCalledOnce()
+})
+
+it('ignores token failures after the bank dialog closes', async () => {
+ let reject!: (error: Error) => void
+ api.getReconnectToken.mockImplementation(() => new Promise((_, fail) => { reject = fail }))
+ const onClose = vi.fn()
+ const { rerender } = renderWithProviders(<BankConnectDialog open reconnectConnectionId="synthetic" onClose={onClose} />)
+ rerender(<BankConnectDialog open={false} reconnectConnectionId="synthetic" onClose={onClose} />)
+ await act(async () => { reject(new Error('late failure')) })
+ expect(onClose).not.toHaveBeenCalled()
+ expect(api.toastError).not.toHaveBeenCalled()
+})
diff --git a/frontend/src/components/connection-settings-dialog.tsx b/frontend/src/components/connection-settings-dialog.tsx
index 72b29349..61cdded5 100644
--- a/frontend/src/components/connection-settings-dialog.tsx
+++ b/frontend/src/components/connection-settings-dialog.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { connections } from '@/lib/api'
@@ -38,14 +38,16 @@ export function ConnectionSettingsDialog({
const [importPending, setImportPending] = useState(true)
const [syncAssets, setSyncAssets] = useState(true)
- useEffect(() => {
+ const [formSource, setFormSource] = useState<{ connection: typeof connection } | null>(null)
+ if (!formSource || formSource.connection !== connection) {
+ setFormSource({ connection })
if (connection) {
setDisplayName(connection.display_name ?? '')
setPayeeSource(connection.settings?.payee_source ?? 'auto')
setImportPending(connection.settings?.import_pending ?? true)
setSyncAssets(connection.settings?.sync_assets ?? true)
}
- }, [connection])
+ }
const mutation = useMutation({
mutationFn: () =>
diff --git a/frontend/src/components/connector-select-dialog.tsx b/frontend/src/components/connector-select-dialog.tsx
index 206e7303..ff85b013 100644
--- a/frontend/src/components/connector-select-dialog.tsx
+++ b/frontend/src/components/connector-select-dialog.tsx
@@ -25,22 +25,28 @@ interface ConnectorSelectDialogProps {
onSelect: (provider: Provider) => void
}
-export function ConnectorSelectDialog({ open, onClose, onSelect }: ConnectorSelectDialogProps) {
+export function ConnectorSelectDialog(props: ConnectorSelectDialogProps) {
+ return props.open ? <ConnectorSelectSession {...props} /> : null
+}
+
+function ConnectorSelectSession({ open, onClose, onSelect }: ConnectorSelectDialogProps) {
const { t } = useTranslation()
const [providers, setProviders] = useState<Provider[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
- if (!open) return
- setLoading(true)
+ let cancelled = false
connections.getProviders().then((data) => {
+ if (cancelled) return
setProviders(data)
setLoading(false)
}).catch(() => {
+ if (cancelled) return
setProviders([])
setLoading(false)
})
- }, [open])
+ return () => { cancelled = true }
+ }, [])
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
diff --git a/frontend/src/components/form-reset.test.tsx b/frontend/src/components/form-reset.test.tsx
new file mode 100644
index 00000000..43f55443
--- /dev/null
+++ b/frontend/src/components/form-reset.test.tsx
@@ -0,0 +1,29 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { expect, it, vi } from 'vitest'
+import { TransferDialog } from './transfer-dialog'
+import { renderWithProviders } from '@/test/utils'
+import type { Account } from '@/types'
+
+vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ user: null }) }))
+
+it('preserves a transfer draft on rerender and resets all amounts and accounts on reopen', () => {
+ const accounts = [
+ { id: 'a', name: 'Source', type: 'checking', currency: 'USD' },
+ { id: 'b', name: 'Destination', type: 'checking', currency: 'EUR' },
+ ] as Account[]
+ const props = { accounts, onClose: vi.fn(), onSave: vi.fn(), loading: false, defaultFromAccountId: 'a' }
+ const { rerender } = renderWithProviders(<TransferDialog {...props} open />)
+ fireEvent.change(screen.getAllByRole('combobox')[1], { target: { value: 'b' } })
+ const amounts = screen.getAllByRole('spinbutton')
+ fireEvent.change(amounts[0], { target: { value: '23' } })
+ fireEvent.change(amounts[1], { target: { value: '21' } })
+ rerender(<TransferDialog {...props} open />)
+ expect(screen.getAllByRole('spinbutton')[0]).toHaveValue(23)
+ expect(screen.getAllByRole('spinbutton')[1]).toHaveValue(21)
+ rerender(<TransferDialog {...props} open={false} />)
+ rerender(<TransferDialog {...props} open />)
+ expect(screen.getAllByRole('combobox')[0]).toHaveValue('a')
+ expect(screen.getAllByRole('combobox')[1]).toHaveValue('')
+ expect(screen.getAllByRole('spinbutton')).toHaveLength(1)
+ expect(screen.getByRole('spinbutton')).toHaveValue(null)
+})
diff --git a/frontend/src/components/global-chat-panel.tsx b/frontend/src/components/global-chat-panel.tsx
index 254b1628..3771450c 100644
--- a/frontend/src/components/global-chat-panel.tsx
+++ b/frontend/src/components/global-chat-panel.tsx
@@ -15,7 +15,7 @@
* Page context: each send forwards a `page_context` snapshot built
* from the active page's registration (or a synthesized fallback).
*/
-import { useEffect, useMemo, useState } from 'react'
+import { useMemo, useState } from 'react'
import { Dialog as DialogPrimitive } from 'radix-ui'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
@@ -140,12 +140,14 @@ export function GlobalChatPanel({ open, onOpenChange }: Props) {
// When the panel opens, default the inner view to chat (history view
// is opt-in). Conversation itself is NOT reset — the user explicitly
// clicks + to start a new one.
- useEffect(() => {
+ const [panelSource, setPanelSource] = useState<{ open: typeof open } | null>(null)
+ if (!panelSource || panelSource.open !== open) {
+ setPanelSource({ open })
if (open) {
setView('chat')
setFocusBump((n) => n + 1)
}
- }, [open])
+ }
return (
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
diff --git a/frontend/src/components/group-form.tsx b/frontend/src/components/group-form.tsx
index 24d97952..0be86500 100644
--- a/frontend/src/components/group-form.tsx
+++ b/frontend/src/components/group-form.tsx
@@ -5,7 +5,7 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import type { GroupKind } from '@/types'
-export const KIND_OPTIONS: { value: GroupKind; tKey: string }[] = [
+const KIND_OPTIONS: { value: GroupKind; tKey: string }[] = [
{ value: 'social', tKey: 'splitGroups.kind.social' },
{ value: 'cost_center', tKey: 'splitGroups.kind.cost_center' },
{ value: 'project', tKey: 'splitGroups.kind.project' },
diff --git a/frontend/src/components/oauth-connect-dialog.tsx b/frontend/src/components/oauth-connect-dialog.tsx
index f9849526..db358441 100644
--- a/frontend/src/components/oauth-connect-dialog.tsx
+++ b/frontend/src/components/oauth-connect-dialog.tsx
@@ -41,52 +41,52 @@ function countryLabel(code: string): string {
return REGION_NAMES.of(code) || code
}
-export function OAuthConnectDialog({ open, onClose, provider, supportsAssetSync = false }: OAuthConnectDialogProps) {
+export function OAuthConnectDialog(props: OAuthConnectDialogProps) {
+ return props.open ? <OAuthConnectSession key={props.provider} {...props} /> : null
+}
+
+function OAuthConnectSession({ open, onClose, provider, supportsAssetSync = false }: OAuthConnectDialogProps) {
const { t } = useTranslation()
const [step, setStep] = useState<'country' | 'bank'>('country')
const [country, setCountry] = useState<string | null>(null)
const [countries, setCountries] = useState<string[]>([])
const [institutions, setInstitutions] = useState<Institution[]>([])
- const [loading, setLoading] = useState(false)
- const [error, setError] = useState<string | null>(null)
+ const [loadingCountries, setLoadingCountries] = useState(true)
+ const [loadingBanks, setLoadingBanks] = useState(false)
+ const loading = loadingCountries || loadingBanks
+ const [error, setError] = useState(false)
const [redirecting, setRedirecting] = useState(false)
const [syncAssets, setSyncAssets] = useState(true)
- // Reset when dialog opens.
useEffect(() => {
- if (!open) return
- setStep('country')
- setCountry(null)
- setInstitutions([])
- setError(null)
- setRedirecting(false)
- setSyncAssets(true)
- setLoading(true)
+ let cancelled = false
connections
.listInstitutions(provider)
.then((data) => {
+ if (cancelled) return
setCountries(data.countries)
const stored = localStorage.getItem(LAST_COUNTRY_KEY)
if (stored && data.countries.includes(stored)) {
+ setLoadingBanks(true)
setCountry(stored)
setStep('bank')
}
})
- .catch(() => setError(t('accounts.loadingInstitutionsError')))
- .finally(() => setLoading(false))
- }, [open, provider, t])
+ .catch(() => { if (!cancelled) setError(true) })
+ .finally(() => { if (!cancelled) setLoadingCountries(false) })
+ return () => { cancelled = true }
+ }, [provider])
- // Load banks when a country is picked.
useEffect(() => {
- if (!open || !country || step !== 'bank') return
- setLoading(true)
- setError(null)
+ if (!country || step !== 'bank') return
+ let cancelled = false
connections
.listInstitutions(provider, country)
- .then((data) => setInstitutions(data.institutions))
- .catch(() => setError(t('accounts.loadingInstitutionsError')))
- .finally(() => setLoading(false))
- }, [open, provider, country, step, t])
+ .then((data) => { if (!cancelled) setInstitutions(data.institutions) })
+ .catch(() => { if (!cancelled) setError(true) })
+ .finally(() => { if (!cancelled) setLoadingBanks(false) })
+ return () => { cancelled = true }
+ }, [provider, country, step])
const sortedCountries = useMemo(
() =>
@@ -97,11 +97,19 @@ export function OAuthConnectDialog({ open, onClose, provider, supportsAssetSync
)
const handleCountrySelect = (code: string) => {
+ setLoadingBanks(true)
+ setError(false)
setCountry(code)
localStorage.setItem(LAST_COUNTRY_KEY, code)
setStep('bank')
}
+ const handleBack = () => {
+ setStep('country')
+ setLoadingBanks(false)
+ setError(false)
+ }
+
const handleBankSelect = async (institution: Institution) => {
if (!country) return
setRedirecting(true)
@@ -127,7 +135,7 @@ export function OAuthConnectDialog({ open, onClose, provider, supportsAssetSync
<DialogTitle className="flex items-center gap-2">
{step === 'bank' && (
<button
- onClick={() => setStep('country')}
+ onClick={handleBack}
className="text-muted-foreground hover:text-foreground"
aria-label={t('accounts.back')}
>
@@ -171,7 +179,7 @@ export function OAuthConnectDialog({ open, onClose, provider, supportsAssetSync
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
) : error ? (
- <div className="py-8 text-center text-sm text-destructive">{error}</div>
+ <div className="py-8 text-center text-sm text-destructive">{t('accounts.loadingInstitutionsError')}</div>
) : step === 'country' ? (
<div className="space-y-1 pt-2 max-h-[60vh] overflow-y-auto">
{sortedCountries.length === 0 ? (
@@ -232,7 +240,7 @@ export function OAuthConnectDialog({ open, onClose, provider, supportsAssetSync
))
)}
<div className="pt-2">
- <Button variant="ghost" size="sm" onClick={() => setStep('country')}>
+ <Button variant="ghost" size="sm" onClick={handleBack}>
<ChevronLeft size={14} className="mr-1" />
{t('accounts.back')}
</Button>
diff --git a/frontend/src/components/transaction-attachments.tsx b/frontend/src/components/transaction-attachments.tsx
index ec3cecf2..1c78eea8 100644
--- a/frontend/src/components/transaction-attachments.tsx
+++ b/frontend/src/components/transaction-attachments.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState, useEffect, useCallback } from 'react'
+import { useRef, useState, useEffect, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useDateLocale } from '@/hooks/use-display-locale'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
@@ -79,7 +79,7 @@ export function TransactionAttachments({
staleTime: 5 * 60 * 1000,
})
- const allowedExtensions = attachmentSettings?.allowed_extensions ?? ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'pdf']
+ const allowedExtensions = useMemo(() => attachmentSettings?.allowed_extensions ?? ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'pdf'], [attachmentSettings?.allowed_extensions])
const maxFileSize = (attachmentSettings?.max_file_size_mb ?? 10) * 1024 * 1024
const maxAttachments = attachmentSettings?.max_attachments_per_transaction ?? 10
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 233a66ac..a4bd66e9 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -118,21 +118,13 @@ export function TransactionDialog({
useState<PendingInstallmentEdit | null>(null)
const handlePreviewChange = useCallback((newPreview: AttachmentPreview | null) => {
- setPreview(prev => {
- if (prev?.url) URL.revokeObjectURL(prev.url)
- return newPreview
- })
+ setPreview(newPreview)
}, [])
- // Clean up preview when dialog closes
- useEffect(() => {
- if (!open) {
- setPreview(prev => {
- if (prev?.url) URL.revokeObjectURL(prev.url)
- return null
- })
- }
- }, [open])
+ if (!open && preview) setPreview(null)
+ useEffect(() => () => {
+ if (preview?.url) URL.revokeObjectURL(preview.url)
+ }, [preview])
const handleDownloadPreview = async () => {
if (!preview || !transaction) return
@@ -629,7 +621,7 @@ function TransactionForm({
staleTime: 5 * 60 * 1000,
enabled: isCreating,
})
- const allowedExtensions = attachmentSettings?.allowed_extensions ?? ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'pdf']
+ const allowedExtensions = useMemo(() => attachmentSettings?.allowed_extensions ?? ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'pdf'], [attachmentSettings?.allowed_extensions])
const maxFileSize = (attachmentSettings?.max_file_size_mb ?? 10) * 1024 * 1024
const maxAttachments = attachmentSettings?.max_attachments_per_transaction ?? 10
diff --git a/frontend/src/components/transfer-dialog.tsx b/frontend/src/components/transfer-dialog.tsx
index d3367ade..871d3e18 100644
--- a/frontend/src/components/transfer-dialog.tsx
+++ b/frontend/src/components/transfer-dialog.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo } from 'react'
+import { useState, useMemo } from 'react'
import { getAccountLabel, sortAccountsByDisplayName } from '@/lib/account-utils'
import { useTranslation } from 'react-i18next'
import { localDateString } from '@/lib/date-utils'
@@ -50,20 +50,19 @@ export function TransferDialog({
const [notes, setNotes] = useState('')
const [destinationAmount, setDestinationAmount] = useState('')
- // Reset form when dialog opens
- const resetForm = useCallback(() => {
- setFromAccountId(defaultFromAccountId || firstAccountId)
- setToAccountId('')
- setAmount('')
- setDate(localDateString())
- setDescription('')
- setNotes('')
- setDestinationAmount('')
- }, [defaultFromAccountId, firstAccountId])
-
- useEffect(() => {
- if (open) resetForm()
- }, [open, resetForm])
+ const [formSource, setFormSource] = useState<{ open: boolean; defaultFromAccountId?: string; firstAccountId: string } | null>(null)
+ if (!formSource || formSource.open !== open || formSource.defaultFromAccountId !== defaultFromAccountId || formSource.firstAccountId !== firstAccountId) {
+ setFormSource({ open, defaultFromAccountId, firstAccountId })
+ if (open) {
+ setFromAccountId(defaultFromAccountId || firstAccountId)
+ setToAccountId('')
+ setAmount('')
+ setDate(localDateString())
+ setDescription('')
+ setNotes('')
+ setDestinationAmount('')
+ }
+ }
const fromAccount = accounts.find((a) => a.id === fromAccountId)
const toAccount = accounts.find((a) => a.id === toAccountId)
diff --git a/frontend/src/components/ui/badge.tsx b/frontend/src/components/ui/badge.tsx
index beb56ed1..aabd91cd 100644
--- a/frontend/src/components/ui/badge.tsx
+++ b/frontend/src/components/ui/badge.tsx
@@ -45,4 +45,4 @@ function Badge({
)
}
-export { Badge, badgeVariants }
+export { Badge }
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index ff8bc309..3349f5e8 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -61,4 +61,4 @@ function Button({
)
}
-export { Button, buttonVariants }
+export { Button }
diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsx
index b4ec1985..4d7e0602 100644
--- a/frontend/src/components/ui/form.tsx
+++ b/frontend/src/components/ui/form.tsx
@@ -154,7 +154,6 @@ function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
}
export {
- useFormField,
Form,
FormItem,
FormLabel,
diff --git a/frontend/src/components/ui/tabs.tsx b/frontend/src/components/ui/tabs.tsx
index 7bf18aa7..cf338e43 100644
--- a/frontend/src/components/ui/tabs.tsx
+++ b/frontend/src/components/ui/tabs.tsx
@@ -86,4 +86,4 @@ function TabsContent({
)
}
-export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
+export { Tabs, TabsList, TabsTrigger, TabsContent }
diff --git a/frontend/src/contexts/auth-context.test.tsx b/frontend/src/contexts/auth-context.test.tsx
index f472215a..20be511a 100644
--- a/frontend/src/contexts/auth-context.test.tsx
+++ b/frontend/src/contexts/auth-context.test.tsx
@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { AuthProvider, useAuth } from '@/contexts/auth-context'
+import { AuthProvider } from '@/contexts/auth-provider'
+import { useAuth } from '@/contexts/auth-context'
import type { User } from '@/types'
import { createTestQueryClient } from '@/test/utils'
diff --git a/frontend/src/contexts/auth-context.ts b/frontend/src/contexts/auth-context.ts
new file mode 100644
index 00000000..fdd4cd19
--- /dev/null
+++ b/frontend/src/contexts/auth-context.ts
@@ -0,0 +1,30 @@
+import { createContext, useContext } from 'react'
+import type { User } from '@/types'
+
+export interface LoginResult {
+ requires_2fa: boolean
+ temp_token?: string
+ available_methods?: Array<'totp' | 'passkey'>
+}
+
+interface AuthContextType {
+ user: User | null
+ token: string | null
+ isLoading: boolean
+ login: (email: string, password: string) => Promise<LoginResult>
+ verify2fa: (tempToken: string, code: string) => Promise<void>
+ loginWithToken: (accessToken: string) => void
+ register: (email: string, password: string, preferences?: Record<string, string>) => Promise<void>
+ updateUser: (user: User) => void
+ logout: () => void
+}
+
+export const AuthContext = createContext<AuthContextType | null>(null)
+
+export function useAuth() {
+ const context = useContext(AuthContext)
+ if (!context) {
+ throw new Error('useAuth must be used within an AuthProvider')
+ }
+ return context
+}
diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-provider.tsx
similarity index 67%
rename from frontend/src/contexts/auth-context.tsx
rename to frontend/src/contexts/auth-provider.tsx
index 994d9e24..c39b25c2 100644
--- a/frontend/src/contexts/auth-context.tsx
+++ b/frontend/src/contexts/auth-provider.tsx
@@ -1,27 +1,9 @@
-import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
+import { useState, useEffect, useCallback, type ReactNode } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { auth } from '@/lib/api'
import type { User } from '@/types'
-interface LoginResult {
- requires_2fa: boolean
- temp_token?: string
- available_methods?: Array<'totp' | 'passkey'>
-}
-
-interface AuthContextType {
- user: User | null
- token: string | null
- isLoading: boolean
- login: (email: string, password: string) => Promise<LoginResult>
- verify2fa: (tempToken: string, code: string) => Promise<void>
- loginWithToken: (accessToken: string) => void
- register: (email: string, password: string, preferences?: Record<string, string>) => Promise<void>
- updateUser: (user: User) => void
- logout: () => void
-}
-
-const AuthContext = createContext<AuthContextType | null>(null)
+import { AuthContext, type LoginResult } from '@/contexts/auth-context'
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null)
@@ -29,19 +11,23 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [isLoading, setIsLoading] = useState(true)
const queryClient = useQueryClient()
+ if (!token && (user !== null || isLoading)) {
+ setUser(null)
+ setIsLoading(false)
+ }
+
useEffect(() => {
- if (token) {
- auth.me()
- .then(setUser)
- .catch(() => {
- localStorage.removeItem('token')
- setToken(null)
- })
- .finally(() => setIsLoading(false))
- } else {
- setUser(null)
- setIsLoading(false)
- }
+ if (!token) return
+ let cancelled = false
+ auth.me()
+ .then((me) => { if (!cancelled) setUser(me) })
+ .catch(() => {
+ if (cancelled) return
+ localStorage.removeItem('token')
+ setToken(null)
+ })
+ .finally(() => { if (!cancelled) setIsLoading(false) })
+ return () => { cancelled = true }
}, [token])
// Sync token across tabs via storage events
@@ -106,11 +92,3 @@ export function AuthProvider({ children }: { children: ReactNode }) {
</AuthContext.Provider>
)
}
-
-export function useAuth() {
- const context = useContext(AuthContext)
- if (!context) {
- throw new Error('useAuth must be used within an AuthProvider')
- }
- return context
-}
diff --git a/frontend/src/contexts/collection-filter-context.ts b/frontend/src/contexts/collection-filter-context.ts
new file mode 100644
index 00000000..8ed463fc
--- /dev/null
+++ b/frontend/src/contexts/collection-filter-context.ts
@@ -0,0 +1,23 @@
+import { createContext, useContext } from 'react'
+import type { Collection } from '@/types'
+
+export type CollectionFilterValue = {
+ collections: Collection[]
+ activeCollectionId: string | null
+ activeCollection: Collection | null
+ setActiveCollectionId: (id: string | null) => void
+ // null = all accounts (no filter); otherwise the active collection's account ids.
+ activeAccountIds: string[] | null
+ // null = no filter; otherwise the active collection's wallet (asset_group) ids.
+ activeWalletIds: string[] | null
+}
+
+export const CollectionFilterContext = createContext<CollectionFilterValue | null>(null)
+
+export function useCollectionFilter(): CollectionFilterValue {
+ const ctx = useContext(CollectionFilterContext)
+ if (!ctx) {
+ throw new Error('useCollectionFilter must be used within a CollectionFilterProvider')
+ }
+ return ctx
+}
diff --git a/frontend/src/contexts/collection-filter-context.tsx b/frontend/src/contexts/collection-filter-provider.tsx
similarity index 69%
rename from frontend/src/contexts/collection-filter-context.tsx
rename to frontend/src/contexts/collection-filter-provider.tsx
index f260fd37..92321c1e 100644
--- a/frontend/src/contexts/collection-filter-context.tsx
+++ b/frontend/src/contexts/collection-filter-provider.tsx
@@ -1,21 +1,9 @@
-import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
+import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { collections as collectionsApi } from '@/lib/api'
import { useWorkspace } from '@/contexts/workspace-context'
-import type { Collection } from '@/types'
+import { CollectionFilterContext, type CollectionFilterValue } from '@/contexts/collection-filter-context'
-type CollectionFilterValue = {
- collections: Collection[]
- activeCollectionId: string | null
- activeCollection: Collection | null
- setActiveCollectionId: (id: string | null) => void
- // null = all accounts (no filter); otherwise the active collection's account ids.
- activeAccountIds: string[] | null
- // null = no filter; otherwise the active collection's wallet (asset_group) ids.
- activeWalletIds: string[] | null
-}
-
-const CollectionFilterContext = createContext<CollectionFilterValue | null>(null)
const STORAGE_PREFIX = 'securo.activeCollection.'
export function CollectionFilterProvider({ children }: { children: ReactNode }) {
@@ -71,11 +59,3 @@ export function CollectionFilterProvider({ children }: { children: ReactNode })
<CollectionFilterContext.Provider value={value}>{children}</CollectionFilterContext.Provider>
)
}
-
-export function useCollectionFilter(): CollectionFilterValue {
- const ctx = useContext(CollectionFilterContext)
- if (!ctx) {
- throw new Error('useCollectionFilter must be used within a CollectionFilterProvider')
- }
- return ctx
-}
diff --git a/frontend/src/contexts/workspace-context.test.tsx b/frontend/src/contexts/workspace-context.test.tsx
index 01cfa404..23af54c8 100644
--- a/frontend/src/contexts/workspace-context.test.tsx
+++ b/frontend/src/contexts/workspace-context.test.tsx
@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { QueryClientProvider } from '@tanstack/react-query'
-import { WorkspaceProvider, useWorkspace } from '@/contexts/workspace-context'
+import { WorkspaceProvider } from '@/contexts/workspace-provider'
+import { useWorkspace } from '@/contexts/workspace-context'
import type { Workspace, WorkspaceRole } from '@/types'
import { createTestQueryClient } from '@/test/utils'
diff --git a/frontend/src/contexts/workspace-context.ts b/frontend/src/contexts/workspace-context.ts
new file mode 100644
index 00000000..cd6e87e9
--- /dev/null
+++ b/frontend/src/contexts/workspace-context.ts
@@ -0,0 +1,36 @@
+import { createContext, useContext } from 'react'
+import type { ModuleId } from '@/lib/modules'
+import type { Workspace, WorkspaceRole } from '@/types'
+
+interface WorkspaceContextType {
+ current: Workspace | null
+ workspaces: Workspace[]
+ isLoading: boolean
+ /** Switch the active workspace. Persists to localStorage and invalidates queries. */
+ switchWorkspace: (id: string) => Promise<void>
+ /** Re-fetch the list of workspaces the user can access. */
+ refresh: () => Promise<void>
+ /** Role of the current user inside the active workspace, or null if no active workspace. */
+ role: WorkspaceRole | null
+ /** True for owner OR manager (the manager has effective owner rights). */
+ canManage: boolean
+ /** True for owner, manager, OR editor — anyone allowed to mutate financial data. */
+ canWrite: boolean
+ /** Modules the active workspace shows, as resolved by the server. */
+ enabledModules: ModuleId[]
+ /**
+ * The single question the UI asks about modules. False while the
+ * workspace list is still loading, so nothing renders on a guess.
+ */
+ hasModule: (id: ModuleId) => boolean
+}
+
+export const WorkspaceContext = createContext<WorkspaceContextType | null>(null)
+
+export function useWorkspace() {
+ const ctx = useContext(WorkspaceContext)
+ if (!ctx) {
+ throw new Error('useWorkspace must be used within a WorkspaceProvider')
+ }
+ return ctx
+}
diff --git a/frontend/src/contexts/workspace-context.tsx b/frontend/src/contexts/workspace-provider.tsx
similarity index 72%
rename from frontend/src/contexts/workspace-context.tsx
rename to frontend/src/contexts/workspace-provider.tsx
index a4a20ce2..506d0c78 100644
--- a/frontend/src/contexts/workspace-context.tsx
+++ b/frontend/src/contexts/workspace-provider.tsx
@@ -1,34 +1,11 @@
-import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
+import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useAuth } from '@/contexts/auth-context'
import { workspaces as workspacesApi, WORKSPACE_STORAGE_KEY } from '@/lib/api'
import type { ModuleId } from '@/lib/modules'
-import type { Workspace, WorkspaceRole } from '@/types'
+import type { Workspace } from '@/types'
+import { WorkspaceContext } from '@/contexts/workspace-context'
-interface WorkspaceContextType {
- current: Workspace | null
- workspaces: Workspace[]
- isLoading: boolean
- /** Switch the active workspace. Persists to localStorage and invalidates queries. */
- switchWorkspace: (id: string) => Promise<void>
- /** Re-fetch the list of workspaces the user can access. */
- refresh: () => Promise<void>
- /** Role of the current user inside the active workspace, or null if no active workspace. */
- role: WorkspaceRole | null
- /** True for owner OR manager (the manager has effective owner rights). */
- canManage: boolean
- /** True for owner, manager, OR editor — anyone allowed to mutate financial data. */
- canWrite: boolean
- /** Modules the active workspace shows, as resolved by the server. */
- enabledModules: ModuleId[]
- /**
- * The single question the UI asks about modules. False while the
- * workspace list is still loading, so nothing renders on a guess.
- */
- hasModule: (id: ModuleId) => boolean
-}
-
-const WorkspaceContext = createContext<WorkspaceContextType | null>(null)
export function WorkspaceProvider({ children }: { children: ReactNode }) {
const { user, token, isLoading: authLoading } = useAuth()
@@ -135,11 +112,3 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) {
</WorkspaceContext.Provider>
)
}
-
-export function useWorkspace() {
- const ctx = useContext(WorkspaceContext)
- if (!ctx) {
- throw new Error('useWorkspace must be used within a WorkspaceProvider')
- }
- return ctx
-}
diff --git a/frontend/src/lib/account-type-config.ts b/frontend/src/lib/account-type-config.ts
new file mode 100644
index 00000000..0ae1f1f3
--- /dev/null
+++ b/frontend/src/lib/account-type-config.ts
@@ -0,0 +1,19 @@
+import type { ElementType } from 'react'
+import { Building2, PiggyBank, CreditCard, TrendingUp, Wallet } from 'lucide-react'
+
+// Account-type → icon/color, the fallback shown when an account has no bank
+// logo (manual accounts, and connected accounts whose provider exposes none).
+export const ACCOUNT_TYPE_CONFIG: Record<
+ string,
+ { icon: ElementType; color: string; bg: string; label: string }
+> = {
+ checking: { icon: Building2, color: 'text-indigo-600', bg: 'bg-indigo-100', label: 'accounts.typeChecking' },
+ savings: { icon: PiggyBank, color: 'text-emerald-600', bg: 'bg-emerald-100', label: 'accounts.typeSavings' },
+ credit_card: { icon: CreditCard, color: 'text-violet-600', bg: 'bg-violet-100', label: 'accounts.typeCreditCard' },
+ investment: { icon: TrendingUp, color: 'text-amber-600', bg: 'bg-amber-100', label: 'accounts.typeInvestment' },
+ wallet: { icon: Wallet, color: 'text-rose-600', bg: 'bg-rose-100', label: 'accounts.typeWallet' },
+}
+
+export function getAccountTypeConfig(type: string) {
+ return ACCOUNT_TYPE_CONFIG[type] ?? ACCOUNT_TYPE_CONFIG['checking']
+}
diff --git a/frontend/src/lib/agent-proposals.ts b/frontend/src/lib/agent-proposals.ts
new file mode 100644
index 00000000..bb72aff2
--- /dev/null
+++ b/frontend/src/lib/agent-proposals.ts
@@ -0,0 +1,43 @@
+export type ProposalKind =
+ | 'categorize'
+ | 'create_category'
+ | 'create_budget'
+ | 'create_payee_rule'
+ | 'create_transaction'
+ | 'create_recurring_transaction'
+ | 'update_recurring_transaction'
+ | 'cancel_recurring_transaction'
+ | 'create_goal'
+
+export interface ProposalData {
+ kind?: ProposalKind
+ proposed?: Record<string, unknown>
+ target?: Record<string, unknown>
+ changes?: Record<string, unknown>
+ affected?: { id: string; description?: string; amount?: number; currency?: string }[]
+ affected_count?: number
+ target_category?: { id: string; name: string }
+ name_collision?: { id: string; name: string }
+ mode?: 'deactivate' | 'delete'
+ apply_endpoint?: string
+ error?: string
+}
+
+/** Heuristic: a tool result is a proposal if its data has a known kind. */
+export function isProposalData(data: unknown): data is ProposalData {
+ if (!data || typeof data !== 'object') return false
+ const k = (data as { kind?: unknown }).kind
+ return typeof k === 'string' && [
+ 'categorize', 'create_category', 'create_budget', 'create_payee_rule',
+ 'create_transaction', 'create_recurring_transaction',
+ 'update_recurring_transaction', 'cancel_recurring_transaction',
+ 'create_goal',
+ ].includes(k)
+}
+
+/** Treat the data as a proposal even when only `error` is present, since
+ * a proposal that failed validation should still render a small error card
+ * instead of a generic tool-debug chip. */
+export function isProposalToolName(name: string): boolean {
+ return name.includes('propose_')
+}
diff --git a/frontend/src/lib/i18n.ts b/frontend/src/lib/i18n.ts
index 7bff9582..c70cf767 100644
--- a/frontend/src/lib/i18n.ts
+++ b/frontend/src/lib/i18n.ts
@@ -1,48 +1,45 @@
-import i18n from 'i18next'
+import i18n, { type BackendModule, type ResourceLanguage } from 'i18next'
import { initReactI18next } from 'react-i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import ptBR from '@/locales/pt-BR.json'
-import ptPT from '@/locales/pt-PT.json'
import en from '@/locales/en.json'
-import es from '@/locales/es.json'
-import pl from '@/locales/pl.json'
-import it from '@/locales/it.json'
-import ru from '@/locales/ru.json'
-import uk from '@/locales/uk.json'
-import de from '@/locales/de.json'
-import fr from '@/locales/fr.json'
-import nl from '@/locales/nl.json'
-import sk from '@/locales/sk.json'
-import el from '@/locales/el.json'
-import hi from '@/locales/hi.json'
-import ja from '@/locales/ja.json'
+
+// Keep the default and Brazilian Portuguese bundles available immediately;
+// other languages are separate build assets loaded by i18next when selected.
+const localeLoaders = import.meta.glob<{ default: ResourceLanguage }>([
+ '../locales/*.json', '!../locales/en.json', '!../locales/pt-BR.json',
+])
function syncHtmlLang(lng: string) {
document.documentElement.lang = lng
}
-i18n
+export const i18nReady = i18n
+ .use<BackendModule>({
+ type: 'backend',
+ init() {},
+ read(language, _namespace, callback) {
+ const load = localeLoaders[`../locales/${language}.json`]
+ if (!load) {
+ callback(null, {})
+ return
+ }
+ load().then(
+ ({ default: resource }) => callback(null, resource),
+ (error: Error) => callback(error, false),
+ )
+ },
+ })
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
'pt-BR': { translation: ptBR },
- 'pt-PT': { translation: ptPT },
en: { translation: en },
- es: { translation: es },
- pl: { translation: pl },
- it: { translation: it },
- ru: { translation: ru },
- uk: { translation: uk },
- de: { translation: de },
- fr: { translation: fr },
- nl: { translation: nl },
- sk: { translation: sk },
- el: { translation: el },
- hi: { translation: hi },
- ja: { translation: ja },
},
+ partialBundledLanguages: true,
+ initAsync: false,
fallbackLng: 'en',
// English is the default. Honour an explicit, persisted choice
// (querystring/localStorage/cookie) but do NOT auto-pick the browser
@@ -57,7 +54,7 @@ i18n
},
})
-syncHtmlLang(i18n.language)
+syncHtmlLang(i18n.language || 'en')
i18n.on('languageChanged', syncHtmlLang)
export type SupportedLang =
@@ -78,7 +75,7 @@ export type SupportedLang =
| 'ja'
// Single source of truth for language pickers. When adding a locale, register
-// the bundle above and add one entry here; every picker stays in sync instead
+// a locale JSON file and add one entry here; every picker stays in sync instead
// of each hand-rolling its own list (the setup screen's button row broke a
// little more with every translation PR before this existed).
export const SUPPORTED_LANGS: { code: SupportedLang; label: string }[] = [
diff --git a/frontend/src/locales/i18n-loading.test.ts b/frontend/src/locales/i18n-loading.test.ts
new file mode 100644
index 00000000..d90595f7
--- /dev/null
+++ b/frontend/src/locales/i18n-loading.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, expect, it, vi } from 'vitest'
+
+afterEach(() => {
+ vi.doUnmock('./de.json')
+ vi.resetModules()
+ window.history.replaceState({}, '', '/')
+})
+
+it('loads a selected locale on demand and keeps English fallback keys', async () => {
+ vi.resetModules()
+ const { default: i18n, i18nReady } = await import('@/lib/i18n')
+ await i18nReady
+ expect(i18n.hasResourceBundle('hi', 'translation')).toBe(false)
+ await i18n.changeLanguage('hi')
+ expect(i18n.hasResourceBundle('hi', 'translation')).toBe(true)
+ expect(i18n.t('nav.assets')).toBe((await import('./hi.json')).default.nav.assets)
+ i18n.addResource('en', 'translation', 'testOnlyFallback', 'English fallback')
+ expect(i18n.t('testOnlyFallback')).toBe('English fallback')
+ expect(document.documentElement.lang).toBe('hi')
+})
+
+it('finishes loading a persisted locale before initialization resolves', async () => {
+ localStorage.setItem('i18nextLng', 'de')
+ vi.resetModules()
+ const { default: i18n, i18nReady } = await import('@/lib/i18n')
+ await i18nReady
+ expect(i18n.language).toBe('de')
+ expect(i18n.t('nav.assets')).toBe((await import('./de.json')).default.nav.assets)
+ expect(document.documentElement.lang).toBe('de')
+})
+
+it('still initializes with English fallback if a selected locale asset fails', async () => {
+ localStorage.setItem('i18nextLng', 'de')
+ vi.doMock('./de.json', () => { throw new Error('synthetic unavailable locale asset') })
+ vi.resetModules()
+ const { default: i18n, i18nReady } = await import('@/lib/i18n')
+ await i18nReady
+ expect(i18n.hasResourceBundle('de', 'translation')).toBe(false)
+ expect(i18n.t('nav.assets')).toBe((await import('./en.json')).default.nav.assets)
+})
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 89ac5b11..04440df7 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -1,11 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
-import './lib/i18n'
+import { i18nReady } from './lib/i18n'
import App from './App.tsx'
-createRoot(document.getElementById('root')!).render(
- <StrictMode>
- <App />
- </StrictMode>,
-)
+// Honour a persisted language before rendering any translated UI.
+void i18nReady.then(() => {
+ createRoot(document.getElementById('root')!).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+ )
+})
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index ae7aaf0b..d802d771 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -1,4 +1,4 @@
-import { useState, useMemo, useEffect, useRef } from 'react'
+import { useState, useMemo } from 'react'
import { getAccountName } from '@/lib/account-utils'
import { useParams, Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
@@ -286,11 +286,61 @@ export default function AccountDetailPage() {
const [filterFrom, setFilterFrom] = useState(defaultFrom)
const [filterTo, setFilterTo] = useState(defaultTo)
const [showPrimary, setShowPrimary] = useState(false)
- const filterTouched = useRef(false)
- const handleFilterFromChange = (v: string) => { filterTouched.current = true; setFilterFrom(v) }
- const handleFilterToChange = (v: string) => { filterTouched.current = true; setFilterTo(v) }
+ const [filterTouched, setFilterTouched] = useState(false)
+ const handleFilterFromChange = (v: string) => { setFilterTouched(true); setFilterFrom(v) }
+ const handleFilterToChange = (v: string) => { setFilterTouched(true); setFilterTo(v) }
+ const { data: account, isLoading: accountLoading } = useQuery({
+ queryKey: ['accounts', id],
+ queryFn: () => accounts.get(id!),
+ enabled: !!id,
+ })
+
+ // Bills (faturas) from the provider's bills feed — issue #92. Only fetched
+ // for CC accounts; non-CC and CC-without-bills both return [] so the UI
+ // falls back to local cycle math wherever bills aren't available.
+ // Declared before the initial cycle selection and navigation helpers.
+ const { data: bills } = useQuery({
+ queryKey: ['accounts', id, 'bills'],
+ queryFn: () => accounts.bills(id!, 24),
+ enabled: !!id && account?.type === 'credit_card',
+ })
+ // Bills sorted oldest → newest, for indexing helpers below.
+ const billsAsc = useMemo(() => {
+ if (!bills) return []
+ return [...bills].sort((a, b) => a.due_date.localeCompare(b.due_date))
+ }, [bills])
+ // The bill, if any, the active filter currently corresponds to. We always
+ // set filterTo = bill.due_date when navigating to a bill, so the lookup is
+ // a simple equality check.
+ const activeBill = useMemo(() => {
+ if (!billsAsc.length) return null
+ return billsAsc.find(b => b.due_date === filterTo) ?? null
+ }, [billsAsc, filterTo])
+ // True when the user is on the trailing in-progress cycle (CC has bills,
+ // but the current view doesn't match any of them). Backend uses this to
+ // exclude already-billed txs from the cycle window so they don't double-
+ // count against the in-progress bar/total.
+ const isInProgressCycle = !activeBill && billsAsc.length > 0
+
+ const [cycleSource, setCycleSource] = useState<{ account: typeof account; bills: typeof bills } | null>(null)
+ if (!cycleSource || cycleSource.account !== account || cycleSource.bills !== bills) {
+ setCycleSource({ account, bills })
+ if (account?.type === 'credit_card' && !filterTouched) {
+ const today = format(new Date(), 'yyyy-MM-dd')
+ const upcomingIndex = billsAsc.findIndex(b => b.due_date >= today)
+ const upcoming = billsAsc[upcomingIndex]
+ const range = upcoming
+ ? rangeForBill(upcoming, upcomingIndex > 0 ? billsAsc[upcomingIndex - 1] : null)
+ : billsAsc.length > 0 && account.statement_close_day
+ ? creditCardCycleBoundaries(account.statement_close_day, new Date())
+ : defaultCycleForCreditCard(account.statement_close_day, account.payment_due_day, new Date())
+ setFilterFrom(range.start)
+ setFilterTo(range.end)
+ }
+ }
+
const shiftCycleBy = (direction: -1 | 1) => {
- filterTouched.current = true
+ setFilterTouched(true)
// Bill-aware nav: step through the bills list when we have it, so prev/next
// mirrors the bank's actual statements (handles dynamic close days).
if (billsAsc.length > 0) {
@@ -331,80 +381,6 @@ export default function AccountDetailPage() {
setFilterTo(format(addMonths(parseISO(filterTo + 'T00:00:00'), direction), 'yyyy-MM-dd'))
}
- const { data: account, isLoading: accountLoading } = useQuery({
- queryKey: ['accounts', id],
- queryFn: () => accounts.get(id!),
- enabled: !!id,
- })
-
- // Bills (faturas) from the provider's bills feed — issue #92. Only fetched
- // for CC accounts; non-CC and CC-without-bills both return [] so the UI
- // falls back to local cycle math wherever bills aren't available.
- // Declared early so the cycle-init useEffect and shiftCycleBy can read it.
- const { data: bills } = useQuery({
- queryKey: ['accounts', id, 'bills'],
- queryFn: () => accounts.bills(id!, 24),
- enabled: !!id && account?.type === 'credit_card',
- })
- // Bills sorted oldest → newest, for indexing helpers below.
- const billsAsc = useMemo(() => {
- if (!bills) return []
- return [...bills].sort((a, b) => a.due_date.localeCompare(b.due_date))
- }, [bills])
- // The bill, if any, the active filter currently corresponds to. We always
- // set filterTo = bill.due_date when navigating to a bill, so the lookup is
- // a simple equality check.
- const activeBill = useMemo(() => {
- if (!billsAsc.length) return null
- return billsAsc.find(b => b.due_date === filterTo) ?? null
- }, [billsAsc, filterTo])
- // True when the user is on the trailing in-progress cycle (CC has bills,
- // but the current view doesn't match any of them). Backend uses this to
- // exclude already-billed txs from the cycle window so they don't double-
- // count against the in-progress bar/total.
- const isInProgressCycle = !activeBill && billsAsc.length > 0
-
- useEffect(() => {
- if (!account || filterTouched.current) return
- if (account.type === 'credit_card') {
- // Default landing matches the existing UX: the bill the user is
- // about to pay (next due). With a bills feed we can prefer an
- // upcoming bank-reported bill; if today is past the newest bill,
- // fall through to local cycle math for the in-progress cycle so
- // the user sees what's accumulating on the next (not-yet-issued)
- // statement.
- if (billsAsc.length > 0) {
- const today = format(new Date(), 'yyyy-MM-dd')
- const upcoming = billsAsc.find(b => b.due_date >= today)
- if (upcoming) {
- const idx = billsAsc.indexOf(upcoming)
- const prev = idx > 0 ? billsAsc[idx - 1] : null
- const { start, end } = rangeForBill(upcoming, prev)
- setFilterFrom(start)
- setFilterTo(end)
- return
- }
- // Today is past the newest bill — use cycle-math range
- // [prev_close, next_close-1] so the prev-close-day tx (Brazilian:
- // belongs to next cycle) is in window. Backend's bill_id IS NULL
- // filter in the cycle-math fallback keeps already-billed txs out.
- if (account.statement_close_day) {
- const { start, end } = creditCardCycleBoundaries(account.statement_close_day, new Date())
- setFilterFrom(start)
- setFilterTo(end)
- return
- }
- }
- const { start, end } = defaultCycleForCreditCard(
- account.statement_close_day,
- account.payment_due_day,
- new Date(),
- )
- setFilterFrom(start)
- setFilterTo(end)
- }
- }, [account, billsAsc])
-
const { data: accountsList } = useQuery({
queryKey: ['accounts'],
queryFn: () => accounts.list(),
@@ -1011,7 +987,7 @@ export default function AccountDetailPage() {
size="sm"
className="text-muted-foreground hover:text-foreground min-h-[44px] min-w-[44px] px-3 shrink-0"
onClick={() => {
- filterTouched.current = false
+ setFilterTouched(false)
if (account?.type === 'credit_card') {
const { start, end } = defaultCycleForCreditCard(
account.statement_close_day,
@@ -1099,7 +1075,7 @@ export default function AccountDetailPage() {
key={i}
type="button"
onClick={() => {
- filterTouched.current = true
+ setFilterTouched(true)
setFilterFrom(c.start)
setFilterTo(c.end)
}}
@@ -1767,12 +1743,16 @@ function CreditCardSettingsDialog({
const [closeDay, setCloseDay] = useState('')
const [dueDay, setDueDay] = useState('')
- useEffect(() => {
- if (!open) return
- setCreditLimit(account.credit_limit != null ? String(account.credit_limit) : '')
- setCloseDay(account.statement_close_day != null ? String(account.statement_close_day) : '')
- setDueDay(account.payment_due_day != null ? String(account.payment_due_day) : '')
- }, [open, account.credit_limit, account.statement_close_day, account.payment_due_day])
+ const formKey = JSON.stringify([open, account.credit_limit, account.statement_close_day, account.payment_due_day])
+ const [previousFormKey, setPreviousFormKey] = useState<string | null>(null)
+ if (formKey !== previousFormKey) {
+ setPreviousFormKey(formKey)
+ if (open) {
+ setCreditLimit(account.credit_limit != null ? String(account.credit_limit) : '')
+ setCloseDay(account.statement_close_day != null ? String(account.statement_close_day) : '')
+ setDueDay(account.payment_due_day != null ? String(account.payment_due_day) : '')
+ }
+ }
const parseDay = (v: string): number | null => {
const n = parseInt(v, 10)
diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsx
index 2a283c2a..b36a0d44 100644
--- a/frontend/src/pages/accounts.tsx
+++ b/frontend/src/pages/accounts.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useMemo, useState } from 'react'
import { formatAccountMask, getAccountLabel, getAccountName } from '@/lib/account-utils'
import { getConnectionName } from '@/lib/connection-utils'
import { Link, useNavigate } from 'react-router-dom'
@@ -25,7 +25,8 @@ import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import type { Account, BankConnection } from '@/types'
import { RefreshCw, TriangleAlert, Unlink, Settings } from 'lucide-react'
-import { AccountIcon, ConnectionLogo, getAccountTypeConfig } from '@/components/account-icon'
+import { AccountIcon, ConnectionLogo } from '@/components/account-icon'
+import { getAccountTypeConfig } from '@/lib/account-type-config'
import { AccountPageActions } from '@/components/account-page-actions'
import { AccountRowActions } from '@/components/account-row-actions'
import { PageHeader } from '@/components/page-header'
@@ -693,7 +694,9 @@ function AccountDialog({
const [statementCloseDay, setStatementCloseDay] = useState(account?.statement_close_day?.toString() ?? '')
const [paymentDueDay, setPaymentDueDay] = useState(account?.payment_due_day?.toString() ?? '')
- useEffect(() => {
+ const [formSource, setFormSource] = useState<{ account: typeof account } | null>(null)
+ if (!formSource || formSource.account !== account) {
+ setFormSource({ account })
setName(account?.name ?? '')
setDisplayName(account?.display_name ?? '')
setType(account?.type ?? 'checking')
@@ -703,7 +706,7 @@ function AccountDialog({
setCreditLimit(account?.credit_limit?.toString() ?? '')
setStatementCloseDay(account?.statement_close_day?.toString() ?? '')
setPaymentDueDay(account?.payment_due_day?.toString() ?? '')
- }, [account])
+ }
return (
<Dialog open={open} onOpenChange={onClose}>
diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsx
index c4906f51..54afddba 100644
--- a/frontend/src/pages/assets.tsx
+++ b/frontend/src/pages/assets.tsx
@@ -495,7 +495,7 @@ export default function AssetsPage() {
return Math.round(current * 100) / 100
}, [formMethod, formPurchasePrice, formGrowthRate, formGrowthType, formGrowthFrequency, formGrowthStartDate, formPurchaseDate])
- const activeAssets = assetsList?.filter(a => !a.sell_date && !a.is_archived) ?? []
+ const activeAssets = useMemo(() => assetsList?.filter(a => !a.sell_date && !a.is_archived) ?? [], [assetsList])
const soldAssets = assetsList?.filter(a => a.sell_date) ?? []
// Debounced ticker search. Runs only when the market-price method is
@@ -2771,7 +2771,9 @@ function AddHoldingTransactionDialog({
const [fee, setFee] = useState('')
const [date, setDate] = useState(localDateString)
- useEffect(() => {
+ const [formSource, setFormSource] = useState<{ assetId: typeof assetId } | null>(null)
+ if (!formSource || formSource.assetId !== assetId) {
+ setFormSource({ assetId })
if (assetId) {
setKind('buy')
setQuantity('')
@@ -2779,7 +2781,7 @@ function AddHoldingTransactionDialog({
setFee('')
setDate(localDateString())
}
- }, [assetId])
+ }
const saveMutation = useMutation({
mutationFn: () =>
diff --git a/frontend/src/pages/collections.tsx b/frontend/src/pages/collections.tsx
index f3f90220..c435be76 100644
--- a/frontend/src/pages/collections.tsx
+++ b/frontend/src/pages/collections.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
@@ -168,12 +168,14 @@ function CollectionDialog({
const [selected, setSelected] = useState<Set<string>>(new Set())
const [selectedWallets, setSelectedWallets] = useState<Set<string>>(new Set())
- useEffect(() => {
+ const [formSource, setFormSource] = useState<{ collection: typeof collection; open: typeof open } | null>(null)
+ if (!formSource || formSource.collection !== collection || formSource.open !== open) {
+ setFormSource({ collection, open })
setName(collection?.name ?? '')
setColor(collection?.color ?? SWATCHES[0])
setSelected(new Set(collection?.account_ids ?? []))
setSelectedWallets(new Set(collection?.wallet_ids ?? []))
- }, [collection, open])
+ }
const toggleIn = (setter: typeof setSelected) => (id: string) =>
setter((prev) => {
diff --git a/frontend/src/pages/group-detail.tsx b/frontend/src/pages/group-detail.tsx
index 2e597416..a333e18f 100644
--- a/frontend/src/pages/group-detail.tsx
+++ b/frontend/src/pages/group-detail.tsx
@@ -515,7 +515,7 @@ export default function GroupDetailPage() {
month: new Date(month + '-01').toLocaleString(dateLocale, { month: 'short' }),
total: Number(total.toFixed(2)),
}))
- }, [groupTxs, locale, dateLocale])
+ }, [groupTxs, dateLocale])
// Group spending broken down by category — for the stacked horizontal
// bar. We sum debits only (income/credits aren't "spending"). When a
diff --git a/frontend/src/pages/payees.tsx b/frontend/src/pages/payees.tsx
index 1d1b297d..f0e05474 100644
--- a/frontend/src/pages/payees.tsx
+++ b/frontend/src/pages/payees.tsx
@@ -93,21 +93,19 @@ export default function PayeesPage() {
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [payeesToDelete, setPayeesToDelete] = useState<string[]>([])
const [sort, setSort] = useState<PayeeSort>(() => loadPayeeSort())
- const prevSearchRef = useRef<string | null>(null)
+ const [previousSearch, setPreviousSearch] = useState(() => searchParams.toString())
const summaryRef = useRef<HTMLDivElement>(null)
- // Sync state from URL when navigating
- useEffect(() => {
- const searchStr = searchParams.toString()
- if (prevSearchRef.current === searchStr) return
- prevSearchRef.current = searchStr
-
+ // Navigation replaces the draft and applied filters together.
+ const currentSearch = searchParams.toString()
+ if (previousSearch !== currentSearch) {
+ setPreviousSearch(currentSearch)
const nextQ = searchParams.get('q') ?? ''
setSearch(nextQ)
setSearchQuery(nextQ)
setFilterType(searchParams.get('type') ?? '')
setFilterFavorites(searchParams.get('is_favorite') === 'true')
- }, [searchParams])
+ }
// Sync states back to URL searchParams
useEffect(() => {
@@ -136,11 +134,12 @@ export default function PayeesPage() {
}
}, [search])
- // Clear selection on filter or search query change
- useEffect(() => {
+ const [selectionFilter, setSelectionFilter] = useState({ searchQuery, filterType, filterFavorites })
+ if (selectionFilter.searchQuery !== searchQuery || selectionFilter.filterType !== filterType || selectionFilter.filterFavorites !== filterFavorites) {
+ setSelectionFilter({ searchQuery, filterType, filterFavorites })
setSelectedIds(new Set())
setLastSelectedId(null)
- }, [searchQuery, filterType, filterFavorites])
+ }
useEffect(() => {
if (!summaryPayee) return
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index 6872781a..becb5678 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -768,7 +768,7 @@ export default function TransactionsPage() {
// Tag filtering is now applied server-side, so the visible list and the
// page count both reflect the same filtered total — issue #88.
- const filteredItems = data?.items ?? []
+ const filteredItems = useMemo(() => data?.items ?? [], [data?.items])
const selectableItems = filteredItems.filter(tx => !tx.is_shared)
// Group transactions by date for the mobile card view
diff --git a/frontend/src/pages/workspace-settings.tsx b/frontend/src/pages/workspace-settings.tsx
index 47c774fb..3f5bf509 100644
--- a/frontend/src/pages/workspace-settings.tsx
+++ b/frontend/src/pages/workspace-settings.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDateLocale } from '@/hooks/use-display-locale'
@@ -97,15 +97,19 @@ export default function WorkspaceSettingsPage() {
const [removeTarget, setRemoveTarget] = useState<WorkspaceMember | null>(null)
const [archiveOpen, setArchiveOpen] = useState(false)
- useEffect(() => {
- if (!current) return
- setEditName(current.name)
- setEditCurrency(current.default_currency)
- setEditLocale(current.locale ?? '')
- setEditJurisdiction(current.tax_jurisdiction ?? '')
- setEditIcon(current.icon ?? DEFAULT_WORKSPACE_ICON)
- setEditColor(current.color ?? DEFAULT_WORKSPACE_COLOR)
- }, [current?.id, current?.name, current?.default_currency, current?.locale, current?.tax_jurisdiction, current?.icon, current?.color])
+ const formKey = JSON.stringify([current?.id, current?.name, current?.default_currency, current?.locale, current?.tax_jurisdiction, current?.icon, current?.color])
+ const [previousFormKey, setPreviousFormKey] = useState<string | null>(null)
+ if (formKey !== previousFormKey) {
+ setPreviousFormKey(formKey)
+ if (current) {
+ setEditName(current.name)
+ setEditCurrency(current.default_currency)
+ setEditLocale(current.locale ?? '')
+ setEditJurisdiction(current.tax_jurisdiction ?? '')
+ setEditIcon(current.icon ?? DEFAULT_WORKSPACE_ICON)
+ setEditColor(current.color ?? DEFAULT_WORKSPACE_COLOR)
+ }
+ }
// Which jurisdictions ship a pack. An empty choice is valid, not missing:
// with none set, documents are stored as free text with no mask.
diff --git a/frontend/src/test/chart-environment.test.tsx b/frontend/src/test/chart-environment.test.tsx
new file mode 100644
index 00000000..154d9f3a
--- /dev/null
+++ b/frontend/src/test/chart-environment.test.tsx
@@ -0,0 +1,21 @@
+import { render, waitFor } from '@testing-library/react'
+import { expect, it, vi } from 'vitest'
+import { Line, LineChart, ResponsiveContainer } from 'recharts'
+
+it('measures a real responsive chart without hiding console warnings', async () => {
+ const warn = vi.spyOn(console, 'warn')
+ try {
+ const { container } = render(
+ <ResponsiveContainer width="100%" height="100%">
+ <LineChart data={[{ value: 1 }, { value: 2 }]}>
+ <Line dataKey="value" isAnimationActive={false} />
+ </LineChart>
+ </ResponsiveContainer>,
+ )
+ await waitFor(() => expect(container.querySelector('svg')).toHaveAttribute('width', '800'))
+ expect(container.querySelector('svg')).toHaveAttribute('height', '300')
+ expect(warn).not.toHaveBeenCalled()
+ } finally {
+ warn.mockRestore()
+ }
+})
diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts
index eb83b6be..47b766b2 100644
--- a/frontend/src/test/setup.ts
+++ b/frontend/src/test/setup.ts
@@ -11,6 +11,22 @@
import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach, vi } from 'vitest'
+import { createElement, type ComponentProps } from 'react'
+
+vi.mock('recharts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('recharts')>()
+ return {
+ ...actual,
+ // Use the same test viewport before the first ResizeObserver notification.
+ // Keep the actual container/charts so their SVG rendering is exercised.
+ ResponsiveContainer(props: ComponentProps<typeof actual.ResponsiveContainer>) {
+ return createElement(actual.ResponsiveContainer, {
+ initialDimension: { width: 800, height: 300 },
+ ...props,
+ })
+ },
+ }
+})
// Testing Library only auto-cleans when vitest runs with `globals: true`, and
// this project imports `describe`/`it`/`expect` explicitly instead. Unmount by
@@ -45,9 +61,36 @@ class MockObserver {
}
}
-// Recharts' ResponsiveContainer and several Radix primitives construct one of
-// these on mount.
-globalThis.ResizeObserver = MockObserver as unknown as typeof ResizeObserver
+// jsdom has no layout. Give chart containers a deterministic viewport while
+// retaining normal jsdom measurements for every other element.
+const getBoundingClientRect = HTMLElement.prototype.getBoundingClientRect
+HTMLElement.prototype.getBoundingClientRect = function () {
+ return this.classList.contains('recharts-responsive-container')
+ ? DOMRect.fromRect({ width: 800, height: 300 })
+ : getBoundingClientRect.call(this)
+}
+
+class MockResizeObserver {
+ private callback: ResizeObserverCallback
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback
+ }
+
+ observe(target: Element) {
+ const contentRect = target.getBoundingClientRect()
+ const size = [{ inlineSize: contentRect.width, blockSize: contentRect.height }]
+ this.callback([{
+ target, contentRect, borderBoxSize: size, contentBoxSize: size,
+ devicePixelContentBoxSize: size,
+ }], this)
+ }
+
+ unobserve() {}
+ disconnect() {}
+}
+
+globalThis.ResizeObserver = MockResizeObserver
globalThis.IntersectionObserver =
MockObserver as unknown as typeof IntersectionObserver
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index c7b3c7a3..e3847adf 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -25,9 +25,7 @@ export default defineConfig(async ({ mode }) => {
__APP_VERSION__: JSON.stringify(appVersion),
},
build: {
- // Translation resources are loaded eagerly so language changes remain
- // synchronous. The largest generated chunk is still below 1 MB raw
- // (roughly 306 KB gzip), so use that as the intentional warning budget.
+ // Keep the existing per-chunk budget; optional locales load on demand.
chunkSizeWarningLimit: 1000,
// Emit hashed JS/CSS into `static/` instead of Vite's default `assets/`.
// The default collides with our `/assets` SPA route: nginx's
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
index 990e6f6e..bca0833a 100644
--- a/frontend/vitest.config.ts
+++ b/frontend/vitest.config.ts
@@ -11,9 +11,12 @@ export default defineConfig({
__APP_VERSION__: JSON.stringify('0.0.0-test'),
},
resolve: {
- alias: {
- '@': path.resolve(import.meta.dirname, './src'),
- },
+ alias: [
+ { find: '@', replacement: path.resolve(import.meta.dirname, './src') },
+ // The application uses the browser build; Node/jsdom needs PDF.js's
+ // supported Node entry point when testing real module imports.
+ { find: /^pdfjs-dist$/, replacement: 'pdfjs-dist/legacy/build/pdf.mjs' },
+ ],
},
test: {
// jsdom for everything, not only the component tests. The pure-function