Coverage for downtify/doctor_ai_routes.py: 89%
84 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Routes of the Doctor's AI helper (:mod:`downtify.doctor_ai`).
3``/api/doctor/ai/...`` is the page's side, admin-only: start and stop
4the helper, the "may apply from the chat" switch, and the suggestions
5with Apply / Dismiss. ``/api/doctor/ai/mcp`` is the assistant's side:
6the MCP endpoint, outside the sign-in rules (an assistant has no
7Downtify account) and guarded by the helper's own key instead.
8"""
10from __future__ import annotations
12import json
13from typing import Any
15from fastapi import APIRouter, Depends, HTTPException, Request, Response
16from pydantic import BaseModel, Field
18from . import doctor_ai, doctor_ai_sections # noqa: F401 # registers tools
19from .admin_access import admin_user
20from .doctor_ai import ToolError, helper
22router = APIRouter(prefix='/api/doctor/ai', dependencies=[Depends(admin_user)])
23mcp_router = APIRouter()
25#: Where assistants connect, relative to the server's address.
26MCP_PATH = '/api/doctor/ai/mcp'
29def _status() -> dict[str, Any]:
30 doctor_ai.refresh_states()
31 return {**helper.status(), 'mcp_path': MCP_PATH}
34@router.get('')
35def ai_status() -> dict[str, Any]:
36 """Whether the helper runs, its key and its suggestions."""
38 return _status()
41@router.post('/start')
42def ai_start(user_id: int = Depends(admin_user)) -> dict[str, Any]:
43 """Start the helper with a new key (a running one gets a new key)."""
45 helper.start(user_id)
46 return _status()
49@router.post('/stop')
50def ai_stop() -> dict[str, Any]:
51 helper.stop()
52 return _status()
55class AiSettings(BaseModel):
56 can_apply: bool
59@router.put('/settings')
60def ai_settings(payload: AiSettings) -> dict[str, Any]:
61 """The "may apply what you agreed to in the chat" switch."""
63 if not helper.running:
64 raise HTTPException(409, detail={'code': 'ai_not_running'})
65 helper.can_apply = payload.can_apply
66 return _status()
69class SuggestionIds(BaseModel):
70 ids: list[str] = Field(min_length=1, max_length=500)
73@router.post('/apply')
74async def ai_apply(
75 payload: SuggestionIds, user_id: int = Depends(admin_user)
76) -> dict[str, Any]:
77 """Apply waiting suggestions as one Doctor job."""
79 try:
80 result = await doctor_ai.apply(payload.ids, by='page', user_id=user_id)
81 except ToolError as exc:
82 raise HTTPException(
83 409, detail={'code': 'ai_apply_failed', 'message': str(exc)}
84 ) from None
85 return {**_status(), 'applied': result}
88@router.post('/dismiss')
89def ai_dismiss(payload: SuggestionIds) -> dict[str, Any]:
90 helper.remove(payload.ids)
91 return _status()
94@router.post('/clear')
95def ai_clear() -> dict[str, Any]:
96 """Forget applied and failed suggestions."""
98 helper.clear_finished()
99 return _status()
102# ---------------------------------------------------------------------------
103# MCP endpoint
104# ---------------------------------------------------------------------------
107def _plain(status: int, message: str, **headers: str) -> Response:
108 return Response(
109 json.dumps({'error': message}),
110 status_code=status,
111 media_type='application/json',
112 headers=headers,
113 )
116def _guard(request: Request) -> Response | None:
117 if not helper.running:
118 return _plain(
119 503,
120 'The Downtify AI helper is off. Start it in Settings > '
121 'Doctor > AI helper.',
122 )
123 if not helper.check(request.headers.get('authorization', '')):
124 return _plain(
125 401,
126 'Wrong or old key: copy the current one from Settings > '
127 'Doctor > AI helper.',
128 **{'WWW-Authenticate': 'Bearer'},
129 )
130 return None
133@mcp_router.post(MCP_PATH)
134async def mcp_post(request: Request) -> Response:
135 refused = _guard(request)
136 if refused is not None:
137 return refused
138 body = await request.body()
139 try:
140 message = doctor_ai.parse(body)
141 except ValueError:
142 return Response(
143 json.dumps(
144 doctor_ai._error(None, doctor_ai.PARSE_ERROR, 'Parse error')
145 ),
146 status_code=400,
147 media_type='application/json',
148 )
149 if isinstance(message, list):
150 answers = [
151 a for a in [await doctor_ai.handle(m) for m in message] if a
152 ]
153 if not answers:
154 return Response(status_code=202)
155 return Response(
156 json.dumps(answers, ensure_ascii=False),
157 media_type='application/json',
158 )
159 answer = await doctor_ai.handle(message)
160 if answer is None:
161 return Response(status_code=202)
162 return Response(
163 json.dumps(answer, ensure_ascii=False),
164 media_type='application/json',
165 )
168@mcp_router.get(MCP_PATH)
169@mcp_router.delete(MCP_PATH)
170async def mcp_other(request: Request) -> Response:
171 """No event stream and no sessions: every answer comes with its POST."""
173 refused = _guard(request)
174 if refused is not None:
175 return refused
176 return Response(status_code=405, headers={'Allow': 'POST'})