File size: 5,041 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""Explicit test composition for the API adapter."""

import asyncio
from collections.abc import Mapping, MutableMapping

from fastapi import FastAPI

from free_claude_code.api.app import create_app
from free_claude_code.api.ports import ApiServices
from free_claude_code.application.code_sessions import CodeApplicationPort
from free_claude_code.application.connected_accounts import ConnectedAccountPort
from free_claude_code.application.model_metadata import ProviderModelRefreshResult
from free_claude_code.config.loader import ManagedConfigStore
from free_claude_code.config.provider_catalog import PROVIDER_CATALOG
from free_claude_code.config.settings import Settings
from free_claude_code.providers.base import BaseProvider
from free_claude_code.providers.runtime import ProviderRuntime
from free_claude_code.runtime.application import ApplicationRuntime, RestartCallback
from free_claude_code.runtime.configuration import ConfigurationService
from free_claude_code.runtime.provider_manager import ProviderRuntimeManager
from tests.config.credential_support import credential_edit
from tests.web_tools_support import StubWebToolsClient


def post_config(client, path, *, json):
    values = json.get("values", {})
    credential_keys = {
        d.credential_env for d in PROVIDER_CATALOG.values() if d.credential_env
    }
    if credential_keys.intersection(values):
        config = client.get("/admin/api/config").json()
        fields = {field["key"]: field for field in config["fields"]}
        values = {
            key: credential_edit(fields[key]["value"], value)
            if key in credential_keys
            else value
            for key, value in values.items()
        }
    return client.post(path, json=json | {"values": values})


class ApiTestRuntime(ProviderRuntimeManager):
    """API-only tests supply metadata explicitly; startup/discovery has separate tests."""

    def _catalog_task(self, generation, provider_id, *, refresh=False):
        if refresh:
            return super()._catalog_task(generation, provider_id, refresh=True)
        task = generation.catalog_tasks.get(provider_id)
        if task is None:

            async def supplied_catalog():
                generation.initialized.add(provider_id)
                return ProviderModelRefreshResult()

            task = asyncio.create_task(supplied_catalog())
            generation.catalog_tasks[provider_id] = task
        return task


def create_test_app(
    settings: Settings | None = None,
    *,
    providers: MutableMapping[str, BaseProvider] | None = None,
    restart_callback: RestartCallback | None = None,
    connected_accounts: Mapping[str, ConnectedAccountPort] | None = None,
    code: CodeApplicationPort | None = None,
) -> FastAPI:
    """Build an API app with explicit in-memory runtime services."""
    store = ManagedConfigStore()
    store.initialize()  # API-only tests do not run the production ASGI lifespan.
    settings = settings or store.read().settings
    connected_accounts = dict(connected_accounts or {})

    def connected_provider_ids() -> tuple[str, ...]:
        return tuple(
            provider_id
            for provider_id, account in connected_accounts.items()
            if account.is_connected()
        )

    if providers is None:
        manager = ApiTestRuntime(
            settings,
            connected_provider_ids=connected_provider_ids,
        )
    else:
        manager = ApiTestRuntime(
            settings,
            runtime_factory=lambda snapshot, admission_registry, history_cache=None: (
                ProviderRuntime(
                    snapshot,
                    admission_registry,
                    None,
                    {
                        (provider_id, 1): provider
                        for provider_id, provider in providers.items()
                    },
                )
            ),
            connected_provider_ids=connected_provider_ids,
        )
    runtime = ApplicationRuntime(
        manager,
        configuration=ConfigurationService(store),
        transcriber=None,
        restart_callback=restart_callback,
        connected_accounts=connected_accounts,
    )
    return create_app(
        ApiServices(
            requests=manager,
            admin=runtime,
            tasks=runtime,
            code=code,
            web_tools=StubWebToolsClient(),
        )
    )


def runtime_for_app(app: FastAPI) -> ApplicationRuntime:
    """Return the runtime supplied by :func:`create_test_app`."""
    runtime = app.state.services.admin
    if not isinstance(runtime, ApplicationRuntime):
        raise TypeError("Test app does not use ApplicationRuntime")
    return runtime


def provider_manager_for_app(app: FastAPI) -> ProviderRuntimeManager:
    """Return the provider manager supplied by :func:`create_test_app`."""
    manager = app.state.services.requests
    if not isinstance(manager, ProviderRuntimeManager):
        raise TypeError("Test app does not use ProviderRuntimeManager")
    return manager