|
| 1 | +"""Regression test: chat endpoints honour ``workspace_sessions`` routing. |
| 2 | +
|
| 3 | +Bug (pre-fix): in workspace mode each repo has its own ``wiki.db`` |
| 4 | +registered under ``app.state.workspace_sessions[repo_id]``. The |
| 5 | +chat endpoint resolved ``repo_id`` against the primary's session |
| 6 | +factory (``app.state.session_factory``), which doesn't contain the |
| 7 | +non-primary repos' rows. Result: every chat request to a |
| 8 | +non-primary repo 404'd with ``Repository {repo_id} not found``, |
| 9 | +even though the same id is listed in ``GET /api/repos`` and |
| 10 | +``GET /api/workspace.repos[].repo_id``. |
| 11 | +
|
| 12 | +Fix: ``chat_messages`` now uses |
| 13 | +:func:`repowise.server.deps.resolve_request_session_factory`, |
| 14 | +which mirrors the routing logic that ``get_db_session`` (used by |
| 15 | +the conversation endpoints) already encoded. |
| 16 | +
|
| 17 | +The test below builds a minimal FastAPI app with one primary repo |
| 18 | +in the global session factory and a non-primary repo in |
| 19 | +``workspace_sessions``, and asserts that POST /chat/messages on |
| 20 | +the *non-primary* id passes the lookup (i.e. does not 404 on the |
| 21 | +``Repository ... not found`` branch). |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +from contextlib import asynccontextmanager |
| 27 | +from datetime import UTC, datetime |
| 28 | +from unittest.mock import AsyncMock, patch |
| 29 | + |
| 30 | +import pytest |
| 31 | +from httpx import ASGITransport, AsyncClient |
| 32 | +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine |
| 33 | +from sqlalchemy.pool import StaticPool |
| 34 | + |
| 35 | +from fastapi import FastAPI |
| 36 | +from fastapi.responses import JSONResponse |
| 37 | +from repowise.core.persistence.database import init_db |
| 38 | +from repowise.core.persistence.models import Repository |
| 39 | +from repowise.server.routers import chat |
| 40 | + |
| 41 | + |
| 42 | +_NOW = datetime(2026, 4, 12, 10, 0, 0, tzinfo=UTC) |
| 43 | + |
| 44 | + |
| 45 | +async def _make_factory_with_repo(*, repo_id: str, name: str): |
| 46 | + """Build an in-memory async session factory containing one repo row.""" |
| 47 | + engine = create_async_engine( |
| 48 | + "sqlite+aiosqlite:///:memory:", |
| 49 | + connect_args={"check_same_thread": False}, |
| 50 | + poolclass=StaticPool, |
| 51 | + ) |
| 52 | + await init_db(engine) |
| 53 | + factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) |
| 54 | + async with factory() as session: |
| 55 | + session.add( |
| 56 | + Repository( |
| 57 | + id=repo_id, |
| 58 | + name=name, |
| 59 | + url=f"https://example.com/{name}", |
| 60 | + local_path=f"/workspace/{name}", |
| 61 | + default_branch="main", |
| 62 | + settings_json="{}", |
| 63 | + created_at=_NOW, |
| 64 | + updated_at=_NOW, |
| 65 | + ) |
| 66 | + ) |
| 67 | + await session.commit() |
| 68 | + return factory |
| 69 | + |
| 70 | + |
| 71 | +def _build_app(*, primary_factory, workspace_sessions: dict) -> FastAPI: |
| 72 | + @asynccontextmanager |
| 73 | + async def noop_lifespan(app: FastAPI): |
| 74 | + yield |
| 75 | + |
| 76 | + app = FastAPI(title="chat-workspace-test", lifespan=noop_lifespan) |
| 77 | + |
| 78 | + @app.exception_handler(LookupError) |
| 79 | + async def _lookup(_request, exc): |
| 80 | + return JSONResponse(status_code=404, content={"detail": str(exc)}) |
| 81 | + |
| 82 | + app.state.session_factory = primary_factory |
| 83 | + app.state.workspace_sessions = workspace_sessions |
| 84 | + app.include_router(chat.router) |
| 85 | + return app |
| 86 | + |
| 87 | + |
| 88 | +@pytest.mark.asyncio |
| 89 | +async def test_chat_messages_resolves_non_primary_repo_in_workspace_mode(): |
| 90 | + """Pin the workspace-routing fix: the non-primary id must NOT 404.""" |
| 91 | + primary = await _make_factory_with_repo(repo_id="primary-id", name="primary") |
| 92 | + non_primary = await _make_factory_with_repo( |
| 93 | + repo_id="non-primary-id", name="non-primary" |
| 94 | + ) |
| 95 | + |
| 96 | + app = _build_app( |
| 97 | + primary_factory=primary, |
| 98 | + workspace_sessions={"non-primary-id": non_primary}, |
| 99 | + ) |
| 100 | + |
| 101 | + # Stop after the chat handler has resolved the repo by replacing |
| 102 | + # the chat-provider factory; if the lookup 404s, this never runs. |
| 103 | + fake_provider = AsyncMock() |
| 104 | + fake_provider.provider_name = "openai" |
| 105 | + |
| 106 | + with ( |
| 107 | + patch( |
| 108 | + "repowise.server.routers.chat.get_chat_provider_instance", |
| 109 | + return_value=fake_provider, |
| 110 | + ), |
| 111 | + ): |
| 112 | + transport = ASGITransport(app=app) |
| 113 | + async with AsyncClient( |
| 114 | + transport=transport, base_url="http://testserver" |
| 115 | + ) as client: |
| 116 | + response = await client.post( |
| 117 | + "/api/repos/non-primary-id/chat/messages", |
| 118 | + json={"message": "hi"}, |
| 119 | + ) |
| 120 | + |
| 121 | + # Pre-fix this returned 404 "Repository non-primary-id not found". |
| 122 | + # Post-fix the lookup succeeds — the 422 here is the next branch |
| 123 | + # ("Provider does not support streaming chat") because our fake |
| 124 | + # provider isn't a ChatProvider. Either 200 (full happy path) or |
| 125 | + # 422 (provider check) proves the workspace routing worked. |
| 126 | + assert response.status_code != 404, response.text |
| 127 | + |
| 128 | + |
| 129 | +@pytest.mark.asyncio |
| 130 | +async def test_chat_messages_still_finds_primary_repo(): |
| 131 | + """Single-factory fallback: when ``repo_id`` isn't in |
| 132 | + ``workspace_sessions``, the resolver falls back to |
| 133 | + ``app.state.session_factory`` — covers single-repo mode AND the |
| 134 | + primary repo of a workspace, both of which keep the row in the |
| 135 | + global factory.""" |
| 136 | + primary = await _make_factory_with_repo(repo_id="primary-id", name="primary") |
| 137 | + app = _build_app(primary_factory=primary, workspace_sessions={}) |
| 138 | + |
| 139 | + fake_provider = AsyncMock() |
| 140 | + fake_provider.provider_name = "openai" |
| 141 | + |
| 142 | + with patch( |
| 143 | + "repowise.server.routers.chat.get_chat_provider_instance", |
| 144 | + return_value=fake_provider, |
| 145 | + ): |
| 146 | + transport = ASGITransport(app=app) |
| 147 | + async with AsyncClient( |
| 148 | + transport=transport, base_url="http://testserver" |
| 149 | + ) as client: |
| 150 | + response = await client.post( |
| 151 | + "/api/repos/primary-id/chat/messages", |
| 152 | + json={"message": "hi"}, |
| 153 | + ) |
| 154 | + |
| 155 | + assert response.status_code != 404, response.text |
0 commit comments