File size: 14,764 Bytes
d7637ba
5db99fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437a804
 
 
 
 
 
 
092f909
 
 
437a804
 
b103510
437a804
b103510
 
 
437a804
 
 
092f909
 
b103510
 
 
 
 
 
 
 
 
092f909
437a804
092f909
 
 
 
 
 
d7637ba
092f909
 
437a804
092f909
 
437a804
092f909
 
 
d7637ba
 
 
 
092f909
d7637ba
 
 
 
092f909
d7637ba
 
092f909
d7637ba
 
 
 
 
 
5db99fa
d7637ba
 
b103510
d7637ba
 
 
5db99fa
b103510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9a83ae
 
5db99fa
 
b103510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db99fa
437a804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db99fa
 
 
 
 
 
 
 
 
 
 
437a804
5db99fa
d7637ba
5db99fa
 
 
 
 
c9a83ae
5db99fa
 
 
 
 
437a804
 
 
d7637ba
 
 
 
 
 
 
 
 
437a804
c9a83ae
 
 
437a804
c9a83ae
437a804
 
 
 
 
 
d7637ba
 
 
437a804
 
 
d7637ba
 
 
 
437a804
d7637ba
 
437a804
d7637ba
437a804
 
 
 
d7637ba
437a804
 
c9a83ae
437a804
b103510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437a804
 
d7637ba
 
 
 
 
 
 
 
 
437a804
 
d7637ba
437a804
 
d7637ba
437a804
 
 
d7637ba
 
 
437a804
 
 
5db99fa
437a804
 
5db99fa
d7637ba
437a804
5db99fa
437a804
 
 
5db99fa
 
c9a83ae
437a804
 
 
c9a83ae
437a804
 
 
c9a83ae
437a804
 
 
c9a83ae
437a804
 
 
 
 
c9a83ae
437a804
 
 
 
 
c9a83ae
437a804
 
 
c9a83ae
437a804
 
 
 
c9a83ae
437a804
 
 
 
 
c9a83ae
437a804
 
 
 
 
 
 
c9a83ae
 
5db99fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77324b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
"""Tests for premium model handling in backend/routes/agent.py."""

import sys
from pathlib import Path
from types import SimpleNamespace

import pytest
from fastapi import HTTPException

_BACKEND_DIR = Path(__file__).resolve().parent.parent.parent / "backend"
if str(_BACKEND_DIR) not in sys.path:
    sys.path.insert(0, str(_BACKEND_DIR))

from routes import agent  # noqa: E402


@pytest.fixture(autouse=True)
def _reset_quota_store():
    agent.user_quotas._reset_for_tests()
    yield
    agent.user_quotas._reset_for_tests()


def _premium_session(model: str = agent.DEFAULT_PREMIUM_MODEL_ID):
    return SimpleNamespace(
        claude_counted=False,
        session=SimpleNamespace(
            config=SimpleNamespace(model_name=model),
            premium_user_billed=False,
        ),
    )


def test_premium_model_predicate_uses_router_ids_only():
    assert agent._is_premium_model(agent.DEFAULT_PREMIUM_MODEL_ID)
    assert agent._is_premium_model(agent.DEFAULT_OPUS_MODEL_ID)
    assert agent._is_premium_model(agent.DEFAULT_GPT_MODEL_ID)
    assert not agent._is_pro_only_premium_model(agent.DEFAULT_PREMIUM_MODEL_ID)
    assert agent._is_pro_only_premium_model(agent.DEFAULT_OPUS_MODEL_ID)
    assert agent._is_pro_only_premium_model(agent.DEFAULT_GPT_MODEL_ID)
    assert agent._is_user_billed(agent.DEFAULT_PREMIUM_MODEL_ID)
    assert not agent._is_premium_model("moonshotai/Kimi-K2.6")
    assert not agent._is_premium_model("unsupported/model")


def test_available_models_mark_opus_and_gpt_as_pro_only():
    models = {model["id"]: model for model in agent.AVAILABLE_MODELS}

    assert models[agent.DEFAULT_PREMIUM_MODEL_ID]["label"] == "Claude Sonnet 4.6"
    assert models[agent.DEFAULT_PREMIUM_MODEL_ID]["minimum_plan"] == "free"
    assert models[agent.DEFAULT_OPUS_MODEL_ID]["minimum_plan"] == "pro"
    assert models[agent.DEFAULT_GPT_MODEL_ID]["minimum_plan"] == "pro"


@pytest.mark.asyncio
async def test_default_session_uses_configured_default_model():
    model = await agent._model_override_for_new_session(None, None)

    assert model is None


@pytest.mark.asyncio
async def test_explicit_premium_session_allowed_for_authenticated_user():
    model = await agent._model_override_for_new_session(
        None,
        agent.DEFAULT_PREMIUM_MODEL_ID,
    )

    assert model == agent.DEFAULT_PREMIUM_MODEL_ID


@pytest.mark.asyncio
async def test_switching_to_premium_model_is_allowed_for_authenticated_user(
    monkeypatch,
):
    updated = []

    async def fake_check_session_access(session_id, user, request=None):
        assert session_id == "s1"
        assert user["user_id"] == "u1"
        return SimpleNamespace(user_id="u1")

    async def fake_update_session_model(session_id, model_id):
        updated.append((session_id, model_id))

    monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)
    monkeypatch.setattr(
        agent.session_manager,
        "update_session_model",
        fake_update_session_model,
    )

    response = await agent.set_session_model(
        "s1",
        {"model": agent.DEFAULT_PREMIUM_MODEL_ID},
        request=None,
        user={"user_id": "u1", "plan": "free"},
    )

    assert response == {"session_id": "s1", "model": agent.DEFAULT_PREMIUM_MODEL_ID}
    assert updated == [("s1", agent.DEFAULT_PREMIUM_MODEL_ID)]


@pytest.mark.asyncio
async def test_switching_to_pro_only_premium_model_is_allowed_for_pro_user(
    monkeypatch,
):
    updated = []

    async def fake_check_session_access(session_id, user, request=None):
        assert session_id == "s1"
        assert user["user_id"] == "u1"
        return SimpleNamespace(user_id="u1")

    async def fake_update_session_model(session_id, model_id):
        updated.append((session_id, model_id))

    monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)
    monkeypatch.setattr(
        agent.session_manager,
        "update_session_model",
        fake_update_session_model,
    )

    response = await agent.set_session_model(
        "s1",
        {"model": agent.DEFAULT_GPT_MODEL_ID},
        request=None,
        user={"user_id": "u1", "plan": "pro"},
    )

    assert response == {"session_id": "s1", "model": agent.DEFAULT_GPT_MODEL_ID}
    assert updated == [("s1", agent.DEFAULT_GPT_MODEL_ID)]


@pytest.mark.asyncio
async def test_switching_to_pro_only_premium_model_is_rejected_for_free_user(
    monkeypatch,
):
    async def fake_check_session_access(session_id, user, request=None):
        return SimpleNamespace(user_id=user["user_id"])

    async def fail_if_updated(session_id, model_id):
        raise AssertionError("free users should not switch to pro-only models")

    monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)
    monkeypatch.setattr(agent.session_manager, "update_session_model", fail_if_updated)

    with pytest.raises(HTTPException) as exc_info:
        await agent.set_session_model(
            "s1",
            {"model": agent.DEFAULT_GPT_MODEL_ID},
            request=None,
            user={"user_id": "u1", "plan": "free"},
        )

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail["error"] == "model_requires_pro"


@pytest.mark.asyncio
async def test_switching_to_unknown_model_id_is_rejected(monkeypatch):
    async def fake_check_session_access(session_id, user, request=None):
        return SimpleNamespace(user_id=user["user_id"])

    monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)

    with pytest.raises(HTTPException) as exc_info:
        await agent.set_session_model(
            "s1",
            {"model": "unsupported/model"},
            request=None,
            user={"user_id": "u1", "plan": "free"},
        )

    assert exc_info.value.status_code == 400
    assert "Unknown model" in exc_info.value.detail


@pytest.mark.asyncio
async def test_premium_quota_charges_without_user_billing_inside_allowance(monkeypatch):
    persisted = []

    async def fake_persist_session_snapshot(agent_session):
        persisted.append(agent_session)

    monkeypatch.setattr(
        agent.session_manager,
        "persist_session_snapshot",
        fake_persist_session_snapshot,
    )

    agent_session = _premium_session()

    await agent._enforce_premium_model_quota(
        {"user_id": "u1", "plan": "free"},
        agent_session,
    )

    assert agent_session.claude_counted is True
    assert agent_session.session.premium_user_billed is False
    assert persisted == [agent_session]
    assert await agent.user_quotas.get_claude_used_today("u1") == 1


@pytest.mark.asyncio
async def test_free_user_gets_two_subsidized_premium_sessions_then_user_billing(
    monkeypatch,
):
    async def fake_persist_session_snapshot(_agent_session):
        return None

    monkeypatch.setattr(
        agent.session_manager,
        "persist_session_snapshot",
        fake_persist_session_snapshot,
    )

    first = _premium_session()
    await agent._enforce_premium_model_quota({"user_id": "g1", "plan": "free"}, first)
    assert first.session.premium_user_billed is False

    second = _premium_session()
    await agent._enforce_premium_model_quota({"user_id": "g1", "plan": "free"}, second)
    assert second.session.premium_user_billed is False

    third = _premium_session()
    await agent._enforce_premium_model_quota({"user_id": "g1", "plan": "free"}, third)
    assert third.session.premium_user_billed is True
    assert await agent.user_quotas.get_claude_used_today("g1") == 2


@pytest.mark.asyncio
async def test_free_model_does_not_consume_premium_quota(monkeypatch):
    async def fail_if_persisted(_agent_session):
        raise AssertionError("free model should not consume premium quota")

    monkeypatch.setattr(
        agent.session_manager,
        "persist_session_snapshot",
        fail_if_persisted,
    )

    agent_session = _premium_session("moonshotai/Kimi-K2.6")

    await agent._enforce_premium_model_quota(
        {"user_id": "u1", "plan": "free"},
        agent_session,
    )

    assert agent_session.claude_counted is False
    assert await agent.user_quotas.get_claude_used_today("u1") == 0


@pytest.mark.asyncio
async def test_free_user_cannot_spend_quota_on_pro_only_premium_model(monkeypatch):
    async def fail_if_persisted(_agent_session):
        raise AssertionError("rejected model should not persist quota state")

    monkeypatch.setattr(
        agent.session_manager,
        "persist_session_snapshot",
        fail_if_persisted,
    )

    agent_session = _premium_session(agent.DEFAULT_OPUS_MODEL_ID)

    with pytest.raises(HTTPException) as exc_info:
        await agent._enforce_premium_model_quota(
            {"user_id": "u1", "plan": "free"},
            agent_session,
        )

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail["error"] == "model_requires_pro"
    assert agent_session.claude_counted is False
    assert await agent.user_quotas.get_claude_used_today("u1") == 0


@pytest.mark.asyncio
async def test_downgraded_user_cannot_continue_counted_pro_only_session(monkeypatch):
    async def fail_if_persisted(_agent_session):
        raise AssertionError("already-counted rejected session should not persist")

    monkeypatch.setattr(
        agent.session_manager,
        "persist_session_snapshot",
        fail_if_persisted,
    )

    agent_session = _premium_session(agent.DEFAULT_OPUS_MODEL_ID)
    agent_session.claude_counted = True

    with pytest.raises(HTTPException) as exc_info:
        await agent._enforce_premium_model_quota(
            {"user_id": "u1", "plan": "free"},
            agent_session,
        )

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail["error"] == "model_requires_pro"
    assert agent_session.claude_counted is True
    assert await agent.user_quotas.get_claude_used_today("u1") == 0


@pytest.mark.asyncio
async def test_pro_user_uses_pro_premium_quota(monkeypatch):
    async def fake_persist_session_snapshot(_agent_session):
        return None

    monkeypatch.setattr(
        agent.session_manager,
        "persist_session_snapshot",
        fake_persist_session_snapshot,
    )

    for index in range(2):
        agent_session = _premium_session()
        await agent._enforce_premium_model_quota(
            {"user_id": "pro-user", "plan": "pro"},
            agent_session,
        )
        assert agent_session.claude_counted is True
        assert agent_session.session.premium_user_billed is False
        assert await agent.user_quotas.get_claude_used_today("pro-user") == index + 1


@pytest.mark.asyncio
async def test_pro_user_billable_overflow_also_bills_user(monkeypatch):
    async def fake_persist(_agent_session):
        return None

    monkeypatch.setattr(agent.session_manager, "persist_session_snapshot", fake_persist)
    monkeypatch.setattr(agent.user_quotas, "daily_cap_for", lambda plan: 1)

    await agent._enforce_premium_model_quota(
        {"user_id": "p1", "plan": "pro"}, _premium_session()
    )
    over = _premium_session()
    await agent._enforce_premium_model_quota({"user_id": "p1", "plan": "pro"}, over)
    assert over.session.premium_user_billed is True


@pytest.mark.asyncio
async def test_restore_summary_enforces_premium_quota_before_seed(monkeypatch):
    events = []
    agent_session = _premium_session()

    class Request:
        headers = {}
        cookies = {}

    async def fake_create_session(**kwargs):
        events.append(("create", kwargs["model"]))
        return "s1"

    async def fake_check_session_access(
        session_id, user, request, preload_sandbox=True
    ):
        events.append(("check", session_id, preload_sandbox))
        return agent_session

    async def fake_enforce_quota(user, session):
        assert user["user_id"] == "u1"
        assert session is agent_session
        session.session.premium_user_billed = True
        events.append(("quota", session.session.config.model_name))

    async def fake_seed(session_id, messages):
        events.append(("seed", session_id, agent_session.session.premium_user_billed))
        return len(messages)

    monkeypatch.setattr(agent.session_manager, "create_session", fake_create_session)
    monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)
    monkeypatch.setattr(agent, "_enforce_premium_model_quota", fake_enforce_quota)
    monkeypatch.setattr(agent.session_manager, "seed_from_summary", fake_seed)

    response = await agent.restore_session_summary(
        Request(),
        {"messages": [{"role": "user", "content": "resume this"}]},
        {"user_id": "u1", "plan": "free"},
    )

    assert response.session_id == "s1"
    assert events == [
        ("create", None),
        ("check", "s1", False),
        ("quota", agent.DEFAULT_PREMIUM_MODEL_ID),
        ("seed", "s1", True),
    ]


@pytest.mark.asyncio
async def test_user_quota_response_uses_premium_fields_only(monkeypatch):
    async def fake_get_used_today(user_id):
        assert user_id == "u1"
        return 2

    monkeypatch.setattr(agent.user_quotas, "get_claude_used_today", fake_get_used_today)
    monkeypatch.setattr(agent.user_quotas, "daily_cap_for", lambda plan: 5)

    response = await agent.get_user_quota({"user_id": "u1", "plan": "pro"})

    assert response == {
        "plan": "pro",
        "premium_used_today": 2,
        "premium_daily_cap": 5,
        "premium_remaining": 3,
    }


@pytest.mark.asyncio
async def test_set_session_yolo_calls_manager_with_cap_presence(monkeypatch):
    async def fake_check_session_access(session_id, user, request=None):
        assert session_id == "s1"
        assert user["user_id"] == "u1"
        return object()

    calls = []

    async def fake_update_session_auto_approval(session_id, **kwargs):
        calls.append((session_id, kwargs))
        return {
            "enabled": kwargs["enabled"],
            "cost_cap_usd": 7.5,
            "estimated_spend_usd": 0.0,
            "remaining_usd": 7.5,
        }

    monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)
    monkeypatch.setattr(
        agent.session_manager,
        "update_session_auto_approval",
        fake_update_session_auto_approval,
    )

    response = await agent.set_session_yolo(
        "s1",
        agent.SessionYoloRequest(enabled=True, cost_cap_usd=7.5),
        {"user_id": "u1"},
    )

    assert response["enabled"] is True
    assert response["remaining_usd"] == 7.5
    assert calls == [
        (
            "s1",
            {
                "enabled": True,
                "cost_cap_usd": 7.5,
                "cap_provided": True,
            },
        )
    ]