Coverage for app / router / app / dashboards / setup.py: 91%
46 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Generative dashboard setup.
3``POST /app/dashboards/generate`` — describe a board in a sentence and get a
4reviewable proposal back. Creates nothing.
6There is deliberately no ``create-from-config`` sibling here, unlike agent,
7skillset and toolkit setup: ``POST /app/dashboards`` already accepts inline
8widgets, and a reviewed proposal is exactly that shape. The frontend posts the
9proposal (minus any tiles the user removed) straight to the normal create
10endpoint, so generated and hand-built boards take the same path into the
11database and there is only one place that can create one.
13Everything the model returns is re-validated in
14``app.services.dashboards.generator`` against the same renderers that guard
15hand-built widgets, so a hallucinated widget type, an unusable feed URL or a
16malformed config is dropped with a warning rather than persisted.
17"""
19import logging
21from fastapi import APIRouter, Depends, HTTPException, status
22from sqlalchemy.orm import Session
24from app.db.postgres.crud_schemas import Schema
25from app.db.postgres.enums import GenerationEnum
26from app.db.postgres.models import User
27from app.dependency.base import get_db
28from app.dependency.user.context import get_current_user
29from app.dependency.workspace import request_workspace
30from app.router.app.agents.setup import _resolve_generation_model
31from app.services import generation as generation_service
32from app.services.ai_client import AIServiceError
33from app.services.dashboards.generator import (
34 DashboardGenerationError,
35 DashboardGenerationUnavailable,
36 generate_dashboard,
37)
39logger = logging.getLogger(__name__)
41dashboard_setup_router = APIRouter(prefix="/dashboards", tags=["App - Dashboard Setup"])
43#: What a person is told when no model can design the board.
44NO_MODEL_DETAIL = "No model is available to generate the dashboard."
47@dashboard_setup_router.post(
48 "/generate", response_model=Schema.Dashboard.GenerationProposal
49)
50def generate(
51 body: Schema.Dashboard.GenerateRequest,
52 db: Session = Depends(get_db),
53 current_user: User = Depends(get_current_user),
54):
55 """Compose a dashboard from a description, for review before creating.
57 The proposal carries a ``generation_id`` the frontend passes to
58 ``POST /app/dashboards``. Since generated and hand-built boards share
59 that one create path, the id is the only thing that tells them apart —
60 without it a generated board is indistinguishable from a hand-built one.
61 """
62 try:
63 model_info = _resolve_generation_model(body.ai_model_id)
64 except AIServiceError as exc:
65 # Logged, never echoed: the exception carries svc-ai's response.
66 logger.error("Could not resolve a dashboard generation model: %s", exc)
67 run = generation_service.start(
68 db,
69 flow=GenerationEnum.Flow.dashboard_setup,
70 actor=current_user,
71 arguments=body.model_dump(),
72 )
73 generation_service.fail(db, run, error=NO_MODEL_DETAIL)
74 db.commit()
75 raise HTTPException(
76 status_code=status.HTTP_502_BAD_GATEWAY, detail=NO_MODEL_DETAIL
77 ) from exc
79 run = generation_service.start(
80 db,
81 flow=GenerationEnum.Flow.dashboard_setup,
82 actor=current_user,
83 arguments=body.model_dump(),
84 model_info=model_info,
85 )
87 try:
88 with generation_service.metered(db, run):
89 proposal = generate_dashboard(
90 db,
91 description=body.description,
92 user_id=current_user.id,
93 provider=model_info["provider"]["name"],
94 model_name=model_info["model_name"],
95 model_id=str(model_info["id"]) if model_info.get("id") else None,
96 generation_id=run.id,
97 workspace=request_workspace(db, current_user),
98 )
99 except DashboardGenerationError as exc:
100 # The model ran but produced nothing usable — the user's description
101 # is the thing to change, so this is a 422 rather than a 502.
102 generation_service.fail(db, run, error=str(exc))
103 db.commit()
104 raise HTTPException(
105 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
106 ) from exc
107 except DashboardGenerationUnavailable as exc:
108 # The model could not be asked; its message is written to be shown.
109 generation_service.fail(db, run, error=str(exc))
110 db.commit()
111 raise HTTPException(
112 status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)
113 ) from exc
114 except AIServiceError as exc:
115 logger.error("Dashboard generation failed: %s", exc)
116 generation_service.fail(db, run, error=str(exc))
117 db.commit()
118 raise HTTPException(
119 status_code=status.HTTP_502_BAD_GATEWAY,
120 detail="Could not reach the model service to generate the dashboard.",
121 ) from exc
123 generation_service.record_warnings(run, proposal.get("warnings"))
124 db.commit()
126 return Schema.Dashboard.GenerationProposal(**proposal, generation_id=run.id)