DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(video-learning): separate Invidious account adapters (#1211)
Bingxi Zhaoc45f0ec58b96
diff --git a/deeptutor/video_learning/invidious_account.py b/deeptutor/video_learning/invidious_account.pyindex ad89344a2..9b99b218d 100644--- a/deeptutor/video_learning/invidious_account.py+++ b/deeptutor/video_learning/invidious_account.py@@ -8,21 +8,16 @@ owner-private secrets tree. No password or browser cookie is handled here.from __future__ import annotations-from dataclasses import dataclassfrom datetime import datetime, timezone-import hashlibimport jsonimport os-from pathlib import Pathimport secrets-import statimport timefrom typing import Anyfrom urllib.parse import urlencode, urlparse-import httpx--from deeptutor.multi_user.paths import owner_secrets_dir+import deeptutor.video_learning.invidious_account_client as _client+import deeptutor.video_learning.invidious_account_storage as _storagefrom deeptutor.video_learning.service import (TimedMediaError,load_video_learning_settings,@@ -34,133 +29,12 @@ FLOW_TIMEOUT_S = 600.0PUBLIC_URL_ENV = "DEEPTUTOR_PUBLIC_URL"DEFAULT_PUBLIC_URL = "http://localhost:3782"ACCOUNT_SCOPES = ("GET:preferences", "POST:tokens/unregister")-_SECRETS_SUBDIR = ("private", "video-learning-invidious")_MAX_TOKEN_BYTES = 8192--@dataclass(frozen=True, slots=True)-class _PendingFlow:- owner_id: str- api_base_url: str- callback_url: str- expires_at: float---def _asset_dir(owner_id: str) -> Path:- path = owner_secrets_dir(owner_id)- for part in _SECRETS_SUBDIR:- path = path / part- path.mkdir(parents=True, exist_ok=True)- os.chmod(path, stat.S_IRWXU)- return path---def _store_path(owner_id: str) -> Path:- return _asset_dir(owner_id) / "account.json"---def _pending_dir(owner_id: str) -> Path:- path = _asset_dir(owner_id) / "pending"- path.mkdir(parents=True, exist_ok=True)- os.chmod(path, stat.S_IRWXU)- return path---def _flow_path(owner_id: str, state: str) -> Path:- # State never becomes a path segment. Besides avoiding traversal hazards,- # hashing keeps a filesystem backup from disclosing a still-live callback- # state to someone who can list filenames but not read owner-private files.- digest = hashlib.sha256(state.encode("utf-8")).hexdigest()- return _pending_dir(owner_id) / f"{digest}.json"---def _read_json(path: Path) -> dict[str, Any]:- try:- payload = json.loads(path.read_text(encoding="utf-8"))- except (OSError, UnicodeError, json.JSONDecodeError):- return {}- return payload if isinstance(payload, dict) else {}---def _write_private_json(path: Path, payload: dict[str, Any]) -> None:- temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")- try:- descriptor = os.open(- temporary,- os.O_WRONLY | os.O_CREAT | os.O_EXCL,- stat.S_IRUSR | stat.S_IWUSR,- )- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:- handle.write(json.dumps(payload, ensure_ascii=False, indent=2))- handle.flush()- os.fsync(handle.fileno())- os.replace(temporary, path)- finally:- temporary.unlink(missing_ok=True)---def _pending_flow(path: Path) -> _PendingFlow | None:- payload = _read_json(path)- owner_id = payload.get("owner_id")- api_base_url = payload.get("api_base_url")- callback_url = payload.get("callback_url")- expires_at = payload.get("expires_at")- if (- not isinstance(owner_id, str)- or not owner_id- or not isinstance(api_base_url, str)- or not api_base_url- or not isinstance(callback_url, str)- or not callback_url- or not isinstance(expires_at, (int, float))- ):- return None- return _PendingFlow(- owner_id=owner_id,- api_base_url=api_base_url,- callback_url=callback_url,- expires_at=float(expires_at),- )---def _purge_expired(owner_id: str, now: float | None = None) -> None:- current = time.time() if now is None else now- for path in _pending_dir(owner_id).glob("*.json"):- flow = _pending_flow(path)- if flow is None or flow.owner_id != owner_id or flow.expires_at <= current:- path.unlink(missing_ok=True)---def _consume_pending_flow(owner_id: str, state: str) -> _PendingFlow | None:- if not state:- return None- source = _flow_path(owner_id, state)- claim = source.with_name(f".{source.name}.{secrets.token_hex(8)}.claim")- try:- # Same-filesystem rename is the one-time claim. It works across Uvicorn- # workers and across restarts, unlike a process-local dictionary.- source.rename(claim)- except FileNotFoundError:- return None- try:- flow = _pending_flow(claim)- finally:- claim.unlink(missing_ok=True)- if flow is None or flow.owner_id != owner_id or flow.expires_at <= time.time():- return None- return flow---def _read(owner_id: str) -> dict[str, Any]:- return _read_json(_store_path(owner_id))---def _write(owner_id: str, payload: dict[str, Any]) -> None:- _write_private_json(_store_path(owner_id), payload)---def _forget(owner_id: str) -> None:- _store_path(owner_id).unlink(missing_ok=True)+# Explicit call seams let the workflow tests substitute transport behavior+# without making filesystem persistence part of the same mock boundary.+_request_preferences = _client.request_preferences+_revoke_token = _client.revoke_tokendef _configured_public_url() -> str:@@ -207,27 +81,20 @@ def begin_invidious_account_authorization(*, owner_id: str, redirect_uri: str) -):raise TimedMediaError("Invidious callback URL must be a plain HTTP(S) URL.")- _purge_expired(owner_id)+ _storage.purge_expired(owner_id)state = secrets.token_urlsafe(32)separator = "&" if parsed_redirect.query else "?"callback_url = f"{redirect_uri}{separator}{urlencode({'state': state})}"authorize_url = f"{base}/authorize_token?{urlencode({'scopes': ','.join(ACCOUNT_SCOPES), 'callback_url': callback_url})}"- # Starting again replaces the prior pending consent for this owner and- # instance. The browser can then follow only the most recent redirect.- for path in _pending_dir(owner_id).glob("*.json"):- flow = _pending_flow(path)- if flow is None or flow.owner_id != owner_id or flow.api_base_url == base:- path.unlink(missing_ok=True)- _write_private_json(- _flow_path(owner_id, state),- {- "version": 1,- "owner_id": owner_id,- "api_base_url": base,- "callback_url": callback_url,- "expires_at": time.time() + FLOW_TIMEOUT_S,- },+ _storage.replace_pending_flow(+ state=state,+ flow=_storage.PendingFlow(+ owner_id=owner_id,+ api_base_url=base,+ callback_url=callback_url,+ expires_at=time.time() + FLOW_TIMEOUT_S,+ ),)return authorize_url@@ -268,10 +135,6 @@ def _scopes_include_required(scopes: Any) -> bool:return set(ACCOUNT_SCOPES).issubset(set(scopes))-def _bearer_token(token: dict[str, Any]) -> str:- return json.dumps(token, ensure_ascii=False, separators=(",", ":"))--def _stored_token_is_usable(token: Any) -> bool:if not isinstance(token, dict):return False@@ -287,40 +150,18 @@ def _stored_token_is_usable(token: Any) -> bool:return not (isinstance(expire, int) and expire <= datetime.now(timezone.utc).timestamp())-async def _request_preferences(*, api_base_url: str, token: dict[str, Any]) -> dict[str, Any]:- async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:- try:- response = await client.get(- f"{api_base_url}/api/v1/auth/preferences",- headers={"Authorization": f"Bearer {_bearer_token(token)}"},- )- except httpx.HTTPError as exc:- raise TimedMediaError("Invidious account verification request failed.") from exc- if response.status_code != 200:- raise TimedMediaError(- f"Invidious account verification failed with HTTP {response.status_code}."- )- try:- preferences = response.json()- except ValueError as exc:- raise TimedMediaError("Invidious returned invalid account preferences.") from exc- if not isinstance(preferences, dict):- raise TimedMediaError("Invidious returned invalid account preferences.")- return preferences--async def complete_invidious_account_authorization(*, owner_id: str, state: str, token: str) -> dict[str, Any]:- _purge_expired(owner_id)- flow = _consume_pending_flow(owner_id, state)+ _storage.purge_expired(owner_id)+ flow = _storage.consume_pending_flow(owner_id, state)if flow is None:raise TimedMediaError("Invidious account callback is unknown, expired, or already used.")parsed_token = _parse_token(token)await _request_preferences(api_base_url=flow.api_base_url, token=parsed_token)- _write(+ _storage.write_account(owner_id,{"version": 1,@@ -334,7 +175,7 @@ async def complete_invidious_account_authorization(def invidious_account_status(owner_id: str) -> dict[str, Any]:- payload = _read(owner_id)+ payload = _storage.read_account(owner_id)token = payload.get("token")base = payload.get("api_base_url")scopes = payload.get("scopes")@@ -353,30 +194,17 @@ def invidious_account_status(owner_id: str) -> dict[str, Any]:}-async def _revoke_token(*, api_base_url: str, token: dict[str, Any]) -> None:- async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:- response = await client.post(- f"{api_base_url}/api/v1/auth/tokens/unregister",- headers={"Authorization": f"Bearer {_bearer_token(token)}"},- json={"session": token["session"]},- )- if response.status_code < 200 or response.status_code >= 300:- raise TimedMediaError(- f"Invidious account disconnection failed with HTTP {response.status_code}."- )--async def disconnect_invidious_account(*, owner_id: str) -> dict[str, Any]:- payload = _read(owner_id)+ payload = _storage.read_account(owner_id)token = payload.get("token")base = payload.get("api_base_url")if not _stored_token_is_usable(token) or not isinstance(base, str) or not base:- _forget(owner_id)+ _storage.forget_account(owner_id)return {"connected": False}try:await _revoke_token(api_base_url=base, token=token)- except httpx.HTTPError as exc:+ except _client.InvidiousTransportError as exc:raise TimedMediaError("Invidious account disconnection request failed. The saved connection was kept so it can be retried.") from exc@@ -385,7 +213,7 @@ async def disconnect_invidious_account(*, owner_id: str) -> dict[str, Any]:# so would leave a valid token registered upstream with no local revoke.raise- _forget(owner_id)+ _storage.forget_account(owner_id)return {"connected": False}diff --git a/deeptutor/video_learning/invidious_account_client.py b/deeptutor/video_learning/invidious_account_client.pynew file mode 100644index 000000000..6fc25de07--- /dev/null+++ b/deeptutor/video_learning/invidious_account_client.py@@ -0,0 +1,64 @@+"""HTTP boundary for the Invidious account API."""++from __future__ import annotations++import json+from typing import Any++import httpx++from deeptutor.video_learning.service import TimedMediaError+++class InvidiousTransportError(RuntimeError):+ """The Invidious instance could not be reached."""+++def bearer_token(token: dict[str, Any]) -> str:+ return json.dumps(token, ensure_ascii=False, separators=(",", ":"))+++async def request_preferences(*, api_base_url: str, token: dict[str, Any]) -> dict[str, Any]:+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:+ try:+ response = await client.get(+ f"{api_base_url}/api/v1/auth/preferences",+ headers={"Authorization": f"Bearer {bearer_token(token)}"},+ )+ except httpx.HTTPError as exc:+ raise TimedMediaError("Invidious account verification request failed.") from exc+ if response.status_code != 200:+ raise TimedMediaError(+ f"Invidious account verification failed with HTTP {response.status_code}."+ )+ try:+ preferences = response.json()+ except ValueError as exc:+ raise TimedMediaError("Invidious returned invalid account preferences.") from exc+ if not isinstance(preferences, dict):+ raise TimedMediaError("Invidious returned invalid account preferences.")+ return preferences+++async def revoke_token(*, api_base_url: str, token: dict[str, Any]) -> None:+ try:+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:+ response = await client.post(+ f"{api_base_url}/api/v1/auth/tokens/unregister",+ headers={"Authorization": f"Bearer {bearer_token(token)}"},+ json={"session": token["session"]},+ )+ except httpx.HTTPError as exc:+ raise InvidiousTransportError from exc+ if response.status_code < 200 or response.status_code >= 300:+ raise TimedMediaError(+ f"Invidious account disconnection failed with HTTP {response.status_code}."+ )+++__all__ = [+ "InvidiousTransportError",+ "bearer_token",+ "request_preferences",+ "revoke_token",+]diff --git a/deeptutor/video_learning/invidious_account_storage.py b/deeptutor/video_learning/invidious_account_storage.pynew file mode 100644index 000000000..a77f40d09--- /dev/null+++ b/deeptutor/video_learning/invidious_account_storage.py@@ -0,0 +1,177 @@+"""Owner-private persistence for Invidious account authorization.++This module owns filesystem layout, permissions, atomic publication, and the+one-time pending-flow claim. It deliberately knows nothing about HTTP or the+authorization workflow that consumes the records.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass+import hashlib+import json+import os+from pathlib import Path+import secrets+import stat+import time+from typing import Any++from deeptutor.multi_user.paths import owner_secrets_dir++_SECRETS_SUBDIR = ("private", "video-learning-invidious")+++@dataclass(frozen=True, slots=True)+class PendingFlow:+ owner_id: str+ api_base_url: str+ callback_url: str+ expires_at: float+++def asset_dir(owner_id: str) -> Path:+ path = owner_secrets_dir(owner_id)+ for part in _SECRETS_SUBDIR:+ path = path / part+ path.mkdir(parents=True, exist_ok=True)+ os.chmod(path, stat.S_IRWXU)+ return path+++def account_path(owner_id: str) -> Path:+ return asset_dir(owner_id) / "account.json"+++def pending_dir(owner_id: str) -> Path:+ path = asset_dir(owner_id) / "pending"+ path.mkdir(parents=True, exist_ok=True)+ os.chmod(path, stat.S_IRWXU)+ return path+++def flow_path(owner_id: str, state: str) -> Path:+ # State never becomes a path segment. Besides avoiding traversal hazards,+ # hashing keeps a filesystem backup from disclosing a still-live callback+ # state to someone who can list filenames but not read owner-private files.+ digest = hashlib.sha256(state.encode("utf-8")).hexdigest()+ return pending_dir(owner_id) / f"{digest}.json"+++def read_json(path: Path) -> dict[str, Any]:+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError):+ return {}+ return payload if isinstance(payload, dict) else {}+++def write_private_json(path: Path, payload: dict[str, Any]) -> None:+ temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")+ try:+ descriptor = os.open(+ temporary,+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,+ stat.S_IRUSR | stat.S_IWUSR,+ )+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ handle.write(json.dumps(payload, ensure_ascii=False, indent=2))+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary, path)+ finally:+ temporary.unlink(missing_ok=True)+++def pending_flow(path: Path) -> PendingFlow | None:+ payload = read_json(path)+ owner_id = payload.get("owner_id")+ api_base_url = payload.get("api_base_url")+ callback_url = payload.get("callback_url")+ expires_at = payload.get("expires_at")+ if (+ not isinstance(owner_id, str)+ or not owner_id+ or not isinstance(api_base_url, str)+ or not api_base_url+ or not isinstance(callback_url, str)+ or not callback_url+ or not isinstance(expires_at, (int, float))+ ):+ return None+ return PendingFlow(+ owner_id=owner_id,+ api_base_url=api_base_url,+ callback_url=callback_url,+ expires_at=float(expires_at),+ )+++def purge_expired(owner_id: str, now: float | None = None) -> None:+ current = time.time() if now is None else now+ for path in pending_dir(owner_id).glob("*.json"):+ flow = pending_flow(path)+ if flow is None or flow.owner_id != owner_id or flow.expires_at <= current:+ path.unlink(missing_ok=True)+++def replace_pending_flow(*, state: str, flow: PendingFlow) -> None:+ """Publish one flow after invalidating older flows for the same instance."""+ for path in pending_dir(flow.owner_id).glob("*.json"):+ existing = pending_flow(path)+ if (+ existing is None+ or existing.owner_id != flow.owner_id+ or existing.api_base_url == flow.api_base_url+ ):+ path.unlink(missing_ok=True)+ write_private_json(+ flow_path(flow.owner_id, state),+ {"version": 1, **asdict(flow)},+ )+++def consume_pending_flow(owner_id: str, state: str) -> PendingFlow | None:+ if not state:+ return None+ source = flow_path(owner_id, state)+ claim = source.with_name(f".{source.name}.{secrets.token_hex(8)}.claim")+ try:+ # Same-filesystem rename is the one-time claim. It works across Uvicorn+ # workers and across restarts, unlike a process-local dictionary.+ source.rename(claim)+ except FileNotFoundError:+ return None+ try:+ flow = pending_flow(claim)+ finally:+ claim.unlink(missing_ok=True)+ if flow is None or flow.owner_id != owner_id or flow.expires_at <= time.time():+ return None+ return flow+++def read_account(owner_id: str) -> dict[str, Any]:+ return read_json(account_path(owner_id))+++def write_account(owner_id: str, payload: dict[str, Any]) -> None:+ write_private_json(account_path(owner_id), payload)+++def forget_account(owner_id: str) -> None:+ account_path(owner_id).unlink(missing_ok=True)+++__all__ = [+ "PendingFlow",+ "consume_pending_flow",+ "flow_path",+ "forget_account",+ "purge_expired",+ "read_account",+ "read_json",+ "replace_pending_flow",+ "write_account",+ "write_private_json",+]diff --git a/docs/adr/0004-invidious-account-boundaries.md b/docs/adr/0004-invidious-account-boundaries.mdnew file mode 100644index 000000000..5926b2d95--- /dev/null+++ b/docs/adr/0004-invidious-account-boundaries.md@@ -0,0 +1,64 @@+# ADR-0004: Separate Invidious Account Workflow, Storage, and Transport++## Status++Accepted++## Context++The Invidious account module initially combined three security-sensitive+responsibilities: authorization workflow decisions, owner-private filesystem+persistence, and upstream HTTP requests. The public surface was small, but a+change to token validation could accidentally affect atomic state claims or+transport behavior because all three concerns shared one implementation file.++Pending callbacks also have stricter storage requirements than ordinary+settings: state must not become a path segment, records must be private, and a+callback must be claimed exactly once across workers and process restarts.+Those invariants need an explicit owner independent of the web workflow.++## Decision++- `invidious_account.py` remains the application facade. It validates workflow+ input, chooses scopes, coordinates verification, and exposes the public API.+- `invidious_account_storage.py` owns filesystem layout, permissions, atomic+ JSON publication, expiration cleanup, and one-time pending-flow claims.+- `invidious_account_client.py` owns bearer serialization and all HTTP calls to+ the configured Invidious instance.+- Dependencies point inward from the facade to those two adapters. The storage+ adapter does not import HTTP or workflow services, and callers outside video+ learning continue to use only the facade.+- The persisted JSON shapes, callback lifetime, public functions, and+ user-facing errors remain unchanged.++## Consequences++### Positive++- Filesystem and cross-worker invariants can evolve without touching OAuth-like+ workflow or HTTP code.+- Transport tests patch the transport module directly, making network ownership+ visible.+- The facade is short enough to review as a state transition rather than as a+ mixture of storage and protocol mechanics.++### Negative++- Two private transport call seams remain in the facade so workflow tests can+ substitute upstream behavior without mocking filesystem persistence.+- The feature now spans three modules instead of one.++### Neutral++- This does not introduce a general credential-store abstraction; the unusual+ one-time claim semantics remain local to Invidious accounts.++## Alternatives Considered++- Keep the single module and group functions by comments: rejected because it+ preserves shared implementation ownership and hidden transport coupling.+- Introduce a repository-wide OAuth framework: rejected because Invidious uses+ a provider-specific signed-token callback and there is not yet a second flow+ with the same lifecycle.+- Move only HTTP calls: rejected because the more important concurrency and+ permission invariants would still be embedded in the workflow facade.diff --git a/tests/video_learning/test_invidious_account.py b/tests/video_learning/test_invidious_account.pyindex ecc2a2cbd..36f56f3ca 100644--- a/tests/video_learning/test_invidious_account.py+++ b/tests/video_learning/test_invidious_account.py@@ -15,6 +15,8 @@ import pytestfrom deeptutor.api.routers import video_learningfrom deeptutor.multi_user import pathsfrom deeptutor.video_learning import invidious_account as account+from deeptutor.video_learning import invidious_account_client as account_client+from deeptutor.video_learning import invidious_account_storage as account_storagefrom deeptutor.video_learning.service import TimedMediaError@@ -89,7 +91,7 @@ def test_authorization_uses_minimal_scopes_and_one_time_state(assert urlsplit(url).path == "/authorize_token"assert query["scopes"] == [",".join(account.ACCOUNT_SCOPES)]- pending = account._flow_path("u_ada", state)+ pending = account_storage.flow_path("u_ada", state)assert pending.is_file()assert stat.S_IMODE(pending.stat().st_mode) == 0o600@@ -165,13 +167,13 @@ def test_pending_callback_claim_is_atomic_across_workers(with ThreadPoolExecutor(max_workers=2) as executor:claimed = list(executor.map(- lambda _: account._consume_pending_flow("u_ada", state),+ lambda _: account_storage.consume_pending_flow("u_ada", state),range(2),))assert sum(flow is not None for flow in claimed) == 1- assert not account._flow_path("u_ada", state).exists()+ assert not account_storage.flow_path("u_ada", state).exists()def test_expired_callback_is_rejected_and_never_writes_a_token(@@ -182,10 +184,10 @@ def test_expired_callback_is_rejected_and_never_writes_a_token(owner_id="u_ada", redirect_uri="https://app.example.test/callback")state = _state_from_authorize_url(url)- pending = account._flow_path("u_ada", state)- payload = account._read_json(pending)+ pending = account_storage.flow_path("u_ada", state)+ payload = account_storage.read_json(pending)payload["expires_at"] = 0- account._write_private_json(pending, payload)+ account_storage.write_private_json(pending, payload)with pytest.raises(TimedMediaError):asyncio.run(@@ -219,7 +221,7 @@ def test_failed_preference_verification_never_writes_a_token(configured_instance: str,monkeypatch: pytest.MonkeyPatch,) -> None:- original_client = account.httpx.AsyncClient+ original_client = account_client.httpx.AsyncClientdef refusing_client(**kwargs: object) -> object:def handler(request: httpx.Request) -> httpx.Response:@@ -227,7 +229,7 @@ def test_failed_preference_verification_never_writes_a_token(return original_client(transport=httpx.MockTransport(handler), **kwargs)- monkeypatch.setattr(account.httpx, "AsyncClient", refusing_client)+ monkeypatch.setattr(account_client.httpx, "AsyncClient", refusing_client)url = account.begin_invidious_account_authorization(owner_id="u_ada", redirect_uri="https://app.example.test/callback")@@ -248,7 +250,7 @@ def test_preference_network_failure_is_a_user_facing_error() -> None:import json- original_client = account.httpx.AsyncClient+ original_client = account_client.httpx.AsyncClientdef offline_client(**kwargs: object) -> object:def handler(request: httpx.Request) -> httpx.Response:@@ -256,7 +258,7 @@ def test_preference_network_failure_is_a_user_facing_error(return original_client(transport=httpx.MockTransport(handler), **kwargs)- monkeypatch.setattr(account.httpx, "AsyncClient", offline_client)+ monkeypatch.setattr(account_client.httpx, "AsyncClient", offline_client)with pytest.raises(TimedMediaError, match="verification request failed"):asyncio.run(@@ -271,7 +273,7 @@ def test_disconnect_revokes_upstream_and_removes_only_the_local_secret(configured_instance: str,monkeypatch: pytest.MonkeyPatch,) -> None:- account._write(+ account_storage.write_account("u_ada",{"version": 1,@@ -281,7 +283,7 @@ def test_disconnect_revokes_upstream_and_removes_only_the_local_secret("token": {"session": "v1:test-session", "signature": "test-signature"},},)- account._write(+ account_storage.write_account("u_bob",{"version": 1,@@ -315,7 +317,7 @@ def test_failed_upstream_disconnect_keeps_the_saved_connection_for_retry(configured_instance: str,monkeypatch: pytest.MonkeyPatch,) -> None:- account._write(+ account_storage.write_account("u_ada",{"version": 1,@@ -326,7 +328,7 @@ def test_failed_upstream_disconnect_keeps_the_saved_connection_for_retry(},)- original_client = account.httpx.AsyncClient+ original_client = account_client.httpx.AsyncClientdef failing_client(**kwargs: object) -> object:def handler(request: httpx.Request) -> httpx.Response:@@ -334,13 +336,44 @@ def test_failed_upstream_disconnect_keeps_the_saved_connection_for_retry(return original_client(transport=httpx.MockTransport(handler), **kwargs)- monkeypatch.setattr(account.httpx, "AsyncClient", failing_client)+ monkeypatch.setattr(account_client.httpx, "AsyncClient", failing_client)with pytest.raises(TimedMediaError, match="failed with HTTP 503"):asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))assert account.invidious_account_status("u_ada")["connected"] is True+def test_disconnect_network_failure_is_user_facing_and_keeps_connection(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:test-session", "signature": "test-signature"},+ },+ )++ original_client = account_client.httpx.AsyncClient++ def offline_client(**kwargs: object) -> object:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("offline", request=request)++ return original_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", offline_client)++ with pytest.raises(TimedMediaError, match="disconnection request failed"):+ asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))+ assert account.invidious_account_status("u_ada")["connected"] is True++def test_public_url_override_is_the_only_remote_callback_origin(configured_instance: str,monkeypatch: pytest.MonkeyPatch,@@ -376,7 +409,7 @@ def test_invidious_requests_use_bearer_json_and_unregister_session(token = json.loads(_token())requests: list[httpx.Request] = []- original_client = account.httpx.AsyncClient+ original_client = account_client.httpx.AsyncClientdef recording_client(**kwargs: object) -> object:def handler(request: httpx.Request) -> httpx.Response:@@ -387,7 +420,7 @@ def test_invidious_requests_use_bearer_json_and_unregister_session(return original_client(transport=httpx.MockTransport(handler), **kwargs)- monkeypatch.setattr(account.httpx, "AsyncClient", recording_client)+ monkeypatch.setattr(account_client.httpx, "AsyncClient", recording_client)preferences = asyncio.run(account._request_preferences(api_base_url=configured_instance, token=token)@@ -400,7 +433,7 @@ def test_invidious_requests_use_bearer_json_and_unregister_session("/api/v1/auth/preferences","/api/v1/auth/tokens/unregister",]- expected_authorization = f"Bearer {account._bearer_token(token)}"+ expected_authorization = f"Bearer {account_client.bearer_token(token)}"assert all(request.headers["authorization"] == expected_authorization for request in requests)assert json.loads(requests[-1].content) == {"session": "v1:test-session"}@@ -409,7 +442,7 @@ def test_status_rejects_expired_or_incomplete_stored_tokens(system_root: Path,configured_instance: str,) -> None:- account._write(+ account_storage.write_account("u_ada",{"version": 1,@@ -421,7 +454,7 @@ def test_status_rejects_expired_or_incomplete_stored_tokens()assert account.invidious_account_status("u_ada")["connected"] is True- account._write(+ account_storage.write_account("u_ada",{"version": 1,@@ -441,7 +474,7 @@ def test_disconnect_removes_an_expired_local_connection_without_upstream_call() -> None:from datetime import datetime, timezone- account._write(+ account_storage.write_account("u_ada",{"version": 1,@@ -503,7 +536,7 @@ def test_router_authorize_callback_status_and_disconnect(assert callback.headers["cache-control"] == "no-store"assert "v1:test-session" not in callback.text- account._write(+ account_storage.write_account("u_ada",{"version": 1,