diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py index 2c42b2279..24c84ab0b 100644 --- a/deeptutor/services/config/provider_runtime.py +++ b/deeptutor/services/config/provider_runtime.py @@ -8,6 +8,7 @@ from typing import Any from urllib.parse import urlparse from deeptutor.services.imagegen.config import ImagegenConfig +from deeptutor.services.keypool import primary_api_key from deeptutor.services.model_selection import LLMSelection, apply_llm_selection_to_catalog from deeptutor.services.provider_registry import ( NANOBOT_LLM_PROVIDERS, @@ -596,12 +597,6 @@ def _as_api_key(value: Any) -> str | list[str]: return _as_str(value) -def _primary_api_key(value: str | list[str]) -> str: - return ( - value[0] if isinstance(value, list) and value else value if isinstance(value, str) else "" - ) - - def _to_headers(value: Any) -> dict[str, str]: if isinstance(value, dict): return {str(k): str(v) for k, v in value.items() if str(k).strip() and v is not None} @@ -688,7 +683,7 @@ def _choose_resolved_provider( explicit_spec = find_by_name(hint) if hint else None detected_gateway = find_gateway( provider_name=None, - api_key=_primary_api_key(api_key) or None, + api_key=primary_api_key(api_key), api_base=api_base or None, ) # Keep backward compatibility: old `binding=openai` should not block diff --git a/deeptutor/services/keypool.py b/deeptutor/services/keypool.py index e6bb2d00e..a4d87dc38 100644 --- a/deeptutor/services/keypool.py +++ b/deeptutor/services/keypool.py @@ -65,10 +65,13 @@ def primary_api_key(value: str | list[str] | None) -> str | None: through would render as ``"['sk-a', 'sk-b']"`` in an ``Authorization`` header — a 401 whose cause is invisible. Reduce at the boundary instead, and reduce in one place so every such boundary agrees which key is first. + + An empty key is not a key, in either shape: ``""``, ``[]`` and ``[""]`` + all answer ``None``, so a caller can test the result rather than having + to know which spelling the configuration happened to use. """ - if isinstance(value, list): - return value[0] if value else None - return value or None + first = value[0] if isinstance(value, list) and value else value + return first or None if isinstance(first, str) else None __all__ = ["KeyPool", "primary_api_key"] diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.py index 9b093c278..118c906a9 100644 --- a/deeptutor/services/llm/config.py +++ b/deeptutor/services/llm/config.py @@ -126,10 +126,12 @@ class LLMConfig: return replace(self, **(update or {})) def get_api_key(self) -> str: - """Return the API key string for provider consumers.""" - if isinstance(self.api_key, list): - return self.api_key[0] if self.api_key else "" - return self.api_key + """Return the API key string for provider consumers. + + The empty string, not ``None``, because callers here test it for + truthiness and pass it straight into a provider argument. + """ + return primary_api_key(self.api_key) or "" _LLM_CONFIG_CACHE: LLMConfig | None = None diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.py index 97181b057..b84931dc4 100644 --- a/deeptutor/services/llm/provider_factory.py +++ b/deeptutor/services/llm/provider_factory.py @@ -46,7 +46,7 @@ def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> t def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider: """Construct one provider, importing only the selected backend SDK.""" provider_name = llm_config.provider_name or llm_config.binding - primary_api_key = llm_config.get_api_key() + api_key = llm_config.get_api_key() spec = find_by_name(provider_name) backend = spec.backend if spec else "openai_compat" @@ -68,14 +68,14 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider: ) provider = build_codebuddy_provider( - api_key=primary_api_key or None, + api_key=api_key or None, default_model=llm_config.model, ) elif backend == "azure_openai": from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider provider = AzureOpenAIProvider( - api_key=primary_api_key, + api_key=api_key, api_base=llm_config.effective_url or llm_config.base_url or "", default_model=llm_config.model, extra_headers=llm_config.extra_headers or None, @@ -85,7 +85,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider: from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider provider = AnthropicProvider( - api_key=primary_api_key or None, + api_key=api_key or None, api_base=llm_config.effective_url or llm_config.base_url or None, default_model=llm_config.model, extra_headers=llm_config.extra_headers or None, diff --git a/tests/services/partners/conftest.py b/tests/services/partners/conftest.py index 78608efc5..a28d2e639 100644 --- a/tests/services/partners/conftest.py +++ b/tests/services/partners/conftest.py @@ -22,9 +22,17 @@ def partners_root(tmp_path, monkeypatch) -> Path: Everything the partners layer touches resolves through ``deeptutor.multi_user.paths`` — the partners data dir is anchored at the admin workspace root and partner scopes are synthetic ``UserScope``s — so - patching that module is sufficient to keep tests off the real ``data/``. + patching that module covers the partners layer itself. + + ``identity`` is a second front, and patching ``paths`` does *not* reach it: + it binds ``AUTH_DIR = SYSTEM_ROOT / "auth"`` at import, so a later + ``setattr`` on ``paths.SYSTEM_ROOT`` leaves its module-level file constants + pointing at the real ``data/system/auth/``. Any test that saves a user was + therefore writing into the developer's own account store, and reading it + back — which made the outcome depend on who already had an account there, + since the first account in a store is force-promoted to admin. """ - from deeptutor.multi_user import paths + from deeptutor.multi_user import identity, paths project_root = tmp_path admin_root = (project_root / "data").resolve() @@ -34,6 +42,13 @@ def partners_root(tmp_path, monkeypatch) -> Path: monkeypatch.setattr(paths, "SYSTEM_ROOT", admin_root / "system") monkeypatch.setattr(paths, "_path_services", {}) + auth_dir = admin_root / "system" / "auth" + monkeypatch.setattr(identity, "AUTH_DIR", auth_dir) + monkeypatch.setattr(identity, "USERS_FILE", auth_dir / "users.json") + monkeypatch.setattr(identity, "SECRET_FILE", auth_dir / "auth_secret") + monkeypatch.setattr(identity, "LEGACY_USERS_FILE", project_root / "legacy_users.json") + monkeypatch.setattr(identity, "LEGACY_SECRET_FILE", project_root / "legacy_secret") + admin_root.mkdir(parents=True, exist_ok=True) return admin_root / "partners" diff --git a/tests/services/partners/test_channel_links.py b/tests/services/partners/test_channel_links.py index 7657476e0..de64ea9b6 100644 --- a/tests/services/partners/test_channel_links.py +++ b/tests/services/partners/test_channel_links.py @@ -22,12 +22,21 @@ from tests.services.partners.scripts import finish @pytest.fixture def alice(partners_root): - """A real account — identity is re-read from the user store on every turn.""" + """A real, **non-admin** account — identity is re-read on every turn. + + The admin is saved first on purpose. The first account in a store is + force-promoted to admin regardless of the role asked for, and an admin's + scope *is* the shared pool — so an alice who happened to be first would + make "her private history" and "the shared pool" the same directory, and + every assertion that they differ would pass or fail on account order. + """ from deeptutor.multi_user import identity from deeptutor.services.partners.interaction import actor_for_account - identity.save_user("alice", "hash", "user") - return actor_for_account(identity.get_user("alice")["id"]) + identity.save_user("root", "hash", "admin") + record = identity.save_user("alice", "hash", "user") + assert record["role"] == "user", "alice must not be the store's first account" + return actor_for_account(record["id"]) # ── code lifecycle ──────────────────────────────────────────── @@ -208,7 +217,6 @@ async def test_link_command_binds_the_sender_mid_conversation(partners_root, fak @pytest.mark.asyncio async def test_link_command_refuses_a_group_chat(partners_root, fake_orchestrator): - runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus()) code = links.issue_link_code("ada", "u_alice").code diff --git a/tests/services/test_keypool.py b/tests/services/test_keypool.py index 246423a62..79312d221 100644 --- a/tests/services/test_keypool.py +++ b/tests/services/test_keypool.py @@ -2,7 +2,7 @@ from __future__ import annotations import pytest -from deeptutor.services.keypool import KeyPool +from deeptutor.services.keypool import KeyPool, primary_api_key def test_keypool_rotates_in_round_robin_order() -> None: @@ -79,3 +79,30 @@ def test_keypool_prefers_the_soonest_recovering_key_when_all_are_cooling( now["value"] = 20.0 assert pool.next() == "key-a" + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("sk-a", "sk-a"), + (["sk-a"], "sk-a"), + (["sk-a", "sk-b"], "sk-a"), + # An empty key is not a key, in either spelling — so a caller can test + # the result instead of knowing which shape the config happened to use. + ("", None), + (None, None), + ([], None), + ([""], None), + ], +) +def test_primary_api_key_reduces_every_configured_shape(value, expected) -> None: + assert primary_api_key(value) == expected + + +def test_llm_config_get_api_key_uses_the_same_reduction() -> None: + """``LLMConfig.get_api_key`` is a ``-> str`` front door, not a second copy.""" + from deeptutor.services.llm.config import LLMConfig + + for value in ("sk-a", ["sk-a", "sk-b"], "", [], [""]): + config = LLMConfig(api_key=value, model="gpt-5") + assert config.get_api_key() == (primary_api_key(value) or "") diff --git a/web/tests/ask-user-segments.test.ts b/web/tests/ask-user-segments.test.ts index ad50235f5..f27179220 100644 --- a/web/tests/ask-user-segments.test.ts +++ b/web/tests/ask-user-segments.test.ts @@ -48,15 +48,27 @@ const resolved = (toolCallId: string) => }); test("reasoning produced after a card becomes its own segment below it", () => { - const before = event("thinking", { call_id: "round-1" }, "planning a question"); - const after = event("thinking", { call_id: "round-2" }, "grading their answer"); + const before = event( + "thinking", + { call_id: "round-1" }, + "planning a question", + ); + const after = event( + "thinking", + { call_id: "round-2" }, + "grading their answer", + ); const segments = extractMessageSegments([ before, askUserCard("call-1"), resolved("call-1"), after, - event("content", { call_id: "round-2", call_kind: "agent_loop_round" }, "Correct!"), + event( + "content", + { call_id: "round-2", call_kind: "agent_loop_round" }, + "Correct!", + ), ]); assert.deepEqual( @@ -78,7 +90,11 @@ test("the pre-card rounds stay with the top activity block", () => { const leading = leadingTraceEvents(events, extractMessageSegments(events)); - assert.deepEqual(leading, [before, askUserCard("call-1"), resolved("call-1")]); + assert.deepEqual(leading, [ + before, + askUserCard("call-1"), + resolved("call-1"), + ]); }); test("a turn with no card keeps every event in the top block", () => {