Coverage for app / router / app / dashboards / router.py: 89%

325 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Dashboards — user-composed boards of widgets. 

2 

3A dashboard is a grid of tiles the user arranges themselves. One board per 

4owner may be flagged ``is_home``; the rest are specialist boards (a research 

5board, a spend board, a media-comparison board) they create and order. 

6 

7Widget *types* live in a backend registry rather than in the frontend — see 

8``app.services.dashboards.widgets``. ``GET /widget-types`` serves that 

9registry, so the widget picker gains a card whenever a renderer is added. 

10 

11Dynamic widgets (automations, comparisons) carry a cached result plus the 

12cadence it should be regenerated at. ``GET /{id}`` returns the cache 

13immediately and queues a background refresh for anything stale, so a board 

14always paints at once and catches up behind the user. 

15""" 

16 

17import logging 

18from typing import Optional 

19from uuid import UUID 

20 

21from fastapi import ( 

22 APIRouter, 

23 BackgroundTasks, 

24 Depends, 

25 HTTPException, 

26 Path, 

27 Query, 

28 status, 

29) 

30from fastapi.responses import Response 

31from sqlalchemy.exc import IntegrityError 

32from sqlalchemy.orm import Session 

33 

34from app.db.postgres.crud_schemas import Schema 

35from app.db.postgres.enums import BackgroundEnum, DashboardEnum, HistoryEnum 

36from app.db.postgres.models import Agent, Dashboard, DashboardWidget, Knowledge, User 

37from app.dependency.base import get_db 

38from app.dependency.workspace import owner_for, request_workspace 

39from app.dependency.resource_access import ( 

40 annotated, 

41 scoped, 

42 SYSTEM_READ_ONLY_DETAIL, 

43 verify_resource_access, 

44 verify_resource_read, 

45 verify_owner_scope, 

46) 

47from app.dependency.user.context import get_current_user 

48from app.router.app.history.router import register_history_routes 

49from app.services import documents as documents_service 

50from app.services import generation as generation_service 

51from app.services import history as history_service 

52from app.services.dashboards import refresh as refresh_service 

53from app.services.dashboards import widgets as widget_registry 

54from app.util import document_images 

55 

56logger = logging.getLogger(__name__) 

57 

58Trigger = BackgroundEnum.Trigger 

59 

60dashboard_router = APIRouter(prefix="/dashboards", tags=["App - Dashboards"]) 

61 

62 

63# --------------------------------------------------------------------------- 

64# Helpers 

65# --------------------------------------------------------------------------- 

66 

67 

68def _get_dashboard(db: Session, dashboard_id: UUID) -> Dashboard: 

69 dashboard = db.get(Dashboard, dashboard_id) 

70 if not dashboard: 

71 raise HTTPException( 

72 status_code=status.HTTP_404_NOT_FOUND, detail="Dashboard not found" 

73 ) 

74 return dashboard 

75 

76 

77def _owned_dashboard(db: Session, dashboard_id: UUID, current_user: User) -> Dashboard: 

78 """A board the caller may change — never a built-in one.""" 

79 dashboard = _get_dashboard(db, dashboard_id) 

80 verify_resource_access(dashboard, current_user, db) 

81 return dashboard 

82 

83 

84def _readable_dashboard( 

85 db: Session, dashboard_id: UUID, current_user: User 

86) -> Dashboard: 

87 """A board the caller may open: their own, or a built-in one.""" 

88 dashboard = _get_dashboard(db, dashboard_id) 

89 verify_resource_read(dashboard, current_user, db) 

90 return dashboard 

91 

92 

93def dashboard_children_snapshot(db: Session, dashboard_id: UUID) -> dict: 

94 """A board's current tiles, for its version's ``children_snapshot``. 

95 

96 A board's own columns are little more than a name and an accent — the 

97 tiles are the board. Cached widget results are deliberately not captured: 

98 they churn on every refresh and are not an edit. 

99 """ 

100 widgets = [ 

101 { 

102 "widget_id": str(row.id), 

103 "widget_type": str(row.widget_type), 

104 "title": row.title, 

105 } 

106 for row in db.query(DashboardWidget) 

107 .filter(DashboardWidget.dashboard_id == dashboard_id) 

108 .order_by(DashboardWidget.position.asc()) 

109 .all() 

110 ] 

111 return {"widgets": widgets} 

112 

113 

114def _widgets_of(db: Session, dashboard_id: UUID) -> list[DashboardWidget]: 

115 return ( 

116 db.query(DashboardWidget) 

117 .filter(DashboardWidget.dashboard_id == dashboard_id) 

118 .order_by(DashboardWidget.position) 

119 .all() 

120 ) 

121 

122 

123def _get_widget(db: Session, dashboard: Dashboard, widget_id: UUID) -> DashboardWidget: 

124 widget = db.get(DashboardWidget, widget_id) 

125 if widget is None or widget.dashboard_id != dashboard.id: 

126 raise HTTPException( 

127 status_code=status.HTTP_404_NOT_FOUND, detail="Widget not found" 

128 ) 

129 return widget 

130 

131 

132def _owner_filter(query, dashboard: Dashboard): 

133 """Narrow ``query`` to the same owner as ``dashboard``. 

134 

135 Used when a change to one board has to consider its siblings — setting a 

136 home board, or reordering. 

137 """ 

138 if dashboard.owner_organisation_id is not None: 

139 return query.filter( 

140 Dashboard.owner_organisation_id == dashboard.owner_organisation_id 

141 ) 

142 if dashboard.owner_project_id is not None: 

143 return query.filter(Dashboard.owner_project_id == dashboard.owner_project_id) 

144 return query.filter(Dashboard.owner_user_id == dashboard.owner_user_id) 

145 

146 

147def _conflict(exc: IntegrityError) -> HTTPException: 

148 """Turn a constraint violation into a message the user can act on. 

149 

150 Board names are unique per owner and only one board per owner may be 

151 home, both via partial unique indexes; either surfaces here as a 409 

152 rather than a 500. 

153 """ 

154 detail = str(getattr(exc, "orig", exc)) 

155 if "uq_dashboard_name" in detail: 

156 return HTTPException( 

157 status_code=status.HTTP_409_CONFLICT, 

158 detail="You already have a dashboard with that name.", 

159 ) 

160 if "uq_dashboard_home" in detail: 

161 return HTTPException( 

162 status_code=status.HTTP_409_CONFLICT, 

163 detail="Another dashboard is already set as home.", 

164 ) 

165 return HTTPException( 

166 status_code=status.HTTP_409_CONFLICT, 

167 detail="That change conflicts with an existing dashboard.", 

168 ) 

169 

170 

171#: What a ``ResourceRef`` kind resolves to, and how it is named in an error. 

172_REFERENCE_MODELS = { 

173 "agent": (Agent, "Agent"), 

174 "knowledge": (Knowledge, "Knowledge source"), 

175} 

176 

177 

178def _validated_config(widget_type, config: dict, db: Session, current_user) -> dict: 

179 """Run a widget's config through its renderer, as a 422 on failure. 

180 

181 Every resource the validated config names (``WidgetRenderer.references``) 

182 is then checked against the user saving it: the renderer only 

183 shape-checks ids, and a tile naming somebody else's agent would otherwise 

184 run that agent on every refresh — or, for a network tile, draw somebody 

185 else's graph. A generated tile's target is checked again when it 

186 generates, scoped to the board's owner. 

187 """ 

188 try: 

189 renderer = widget_registry.get_renderer(widget_type) 

190 validated = renderer.validate_config(config or {}) 

191 except widget_registry.WidgetConfigError as exc: 

192 raise HTTPException( 

193 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) 

194 ) from exc 

195 for ref in renderer.references(validated): 

196 model, noun = _REFERENCE_MODELS[ref.kind] 

197 try: 

198 row = db.get(model, UUID(str(ref.id))) 

199 except ValueError: 

200 row = None 

201 if row is None: 

202 raise HTTPException( 

203 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

204 detail=f"{noun} {ref.id} not found.", 

205 ) 

206 verify_resource_read(row, current_user, db) 

207 if ref.source_type and getattr(row, "source_type", None) != ref.source_type: 

208 raise HTTPException( 

209 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

210 detail=f"{row.name} is not a {ref.source_type} source.", 

211 ) 

212 return validated 

213 

214 

215def _read(dashboard: Dashboard, widget_count: int) -> Schema.Dashboard.Read: 

216 return Schema.Dashboard.Read( 

217 id=dashboard.id, 

218 name=dashboard.name, 

219 description=dashboard.description, 

220 icon=dashboard.icon, 

221 accent=dashboard.accent, 

222 is_home=bool(dashboard.is_home), 

223 position=dashboard.position or 0, 

224 owner_user_id=dashboard.owner_user_id, 

225 owner_organisation_id=dashboard.owner_organisation_id, 

226 owner_project_id=dashboard.owner_project_id, 

227 created_at=dashboard.created_at, 

228 updated_at=dashboard.updated_at, 

229 widget_count=widget_count, 

230 is_ai_generated=bool(dashboard.is_ai_generated), 

231 generation_id=dashboard.generation_id, 

232 # Built by hand, so every field has to be named: leaving this out 

233 # served the built-in boards as the user's own, with controls the 

234 # API refuses (see the hand-built response trap on repositories). 

235 is_system=dashboard.is_system is True, 

236 origin=getattr(dashboard, "origin", None), 

237 home_workspace=getattr(dashboard, "home_workspace", None), 

238 cloned_from_id=getattr(dashboard, "cloned_from_id", None), 

239 cloned_from_version=getattr(dashboard, "cloned_from_version", None), 

240 ) 

241 

242 

243def _read_with_widgets( 

244 dashboard: Dashboard, 

245 widgets: list[DashboardWidget], 

246 refreshing: bool = False, 

247) -> Schema.Dashboard.ReadWithWidgets: 

248 base = _read(dashboard, len(widgets)) 

249 return Schema.Dashboard.ReadWithWidgets( 

250 **base.model_dump(), 

251 widgets=[Schema.DashboardWidget.Read.model_validate(w) for w in widgets], 

252 refreshing=refreshing, 

253 ) 

254 

255 

256def _queue_stale_refreshes( 

257 db: Session, 

258 widgets: list[DashboardWidget], 

259 background_tasks: BackgroundTasks, 

260) -> bool: 

261 """Claim and queue every stale dynamic widget. Returns whether any were.""" 

262 stale = refresh_service.stale_widgets(widgets) 

263 for widget in stale: 

264 refresh_service.mark_refreshing(db, widget) 

265 background_tasks.add_task( 

266 refresh_service.refresh_widget_task, widget.id, Trigger.view 

267 ) 

268 return bool(stale) 

269 

270 

271# --------------------------------------------------------------------------- 

272# Widget type catalogue 

273# 

274# Declared before /{dashboard_id} so the literal path is not captured as a 

275# dashboard id. 

276# --------------------------------------------------------------------------- 

277 

278 

279@dashboard_router.get( 

280 "/widget-types", response_model=list[Schema.DashboardWidget.TypeSpec] 

281) 

282def list_widget_types(): 

283 """Every widget type the backend can render, for the widget picker.""" 

284 return widget_registry.catalogue() 

285 

286 

287@dashboard_router.get( 

288 "/message-lists", response_model=list[Schema.DashboardWidget.ListTarget] 

289) 

290def list_message_lists( 

291 db: Session = Depends(get_db), 

292 current_user: User = Depends(get_current_user), 

293): 

294 """Every saved-messages widget on the request workspace's own boards. 

295 

296 Powers the "save to dashboard" picker in chat: one request, flat, rather 

297 than a board fetch per board. A chat in an organisation offers its 

298 boards, never the person's personal ones, nor a parent's inherited ones 

299 (read-only in a project). 

300 """ 

301 rows = ( 

302 db.query(DashboardWidget, Dashboard) 

303 .join(Dashboard, DashboardWidget.dashboard_id == Dashboard.id) 

304 .filter( 

305 request_workspace(db, current_user).owns(Dashboard), 

306 DashboardWidget.widget_type == DashboardEnum.WidgetType.message_list, 

307 ) 

308 .order_by(Dashboard.is_home.desc(), Dashboard.position, Dashboard.name) 

309 .all() 

310 ) 

311 return [ 

312 Schema.DashboardWidget.ListTarget( 

313 dashboard_id=dashboard.id, 

314 dashboard_name=dashboard.name, 

315 dashboard_is_home=bool(dashboard.is_home), 

316 widget_id=widget.id, 

317 widget_title=widget.title, 

318 item_count=len(((widget.config or {}).get("items")) or []), 

319 ) 

320 for widget, dashboard in rows 

321 ] 

322 

323 

324# --------------------------------------------------------------------------- 

325# Dashboard CRUD 

326# --------------------------------------------------------------------------- 

327 

328 

329@dashboard_router.get("", response_model=list[Schema.Dashboard.Read]) 

330def list_dashboards( 

331 workspace: Optional[str] = None, 

332 owner_organisation_id: Optional[UUID] = None, 

333 owner_project_id: Optional[UUID] = None, 

334 include_system: bool = False, 

335 db: Session = Depends(get_db), 

336 current_user: User = Depends(get_current_user), 

337): 

338 """The caller's boards — and, with ``include_system``, the built-in boards 

339 after them, in their declared order. 

340 

341 Opt-in, as for agents and rules: the Overview counts "your boards" from 

342 this listing. Only the personal listing offers them. 

343 """ 

344 where, ws = scoped( 

345 Dashboard, 

346 current_user, 

347 db, 

348 workspace=workspace, 

349 owner_organisation_id=owner_organisation_id, 

350 owner_project_id=owner_project_id, 

351 ) 

352 query = db.query(Dashboard).filter(where) 

353 

354 dashboards = query.order_by( 

355 Dashboard.is_home.desc(), Dashboard.position, Dashboard.name 

356 ).all() 

357 # Built-ins follow the user's own; every workspace offers them. 

358 if include_system and ( 

359 workspace or not (owner_organisation_id or owner_project_id) 

360 ): 

361 dashboards = [ 

362 *dashboards, 

363 *db.query(Dashboard) 

364 .filter(Dashboard.is_system.is_(True)) 

365 .order_by(Dashboard.position, Dashboard.name) 

366 .all(), 

367 ] 

368 

369 annotated(dashboards, ws) 

370 counts = _widget_counts(db, [d.id for d in dashboards]) 

371 return [_read(d, counts.get(d.id, 0)) for d in dashboards] 

372 

373 

374def _widget_counts(db: Session, dashboard_ids: list[UUID]) -> dict[UUID, int]: 

375 """Widget totals per dashboard, as one query rather than N.""" 

376 if not dashboard_ids: 

377 return {} 

378 rows = ( 

379 db.query(DashboardWidget.dashboard_id) 

380 .filter(DashboardWidget.dashboard_id.in_(dashboard_ids)) 

381 .all() 

382 ) 

383 counts: dict[UUID, int] = {} 

384 for row in rows: 

385 key = row[0] if isinstance(row, tuple) else getattr(row, "dashboard_id", row) 

386 counts[key] = counts.get(key, 0) + 1 

387 return counts 

388 

389 

390@dashboard_router.get( 

391 "/{dashboard_id}", response_model=Schema.Dashboard.ReadWithWidgets 

392) 

393def get_dashboard( 

394 dashboard_id: UUID, 

395 background_tasks: BackgroundTasks, 

396 db: Session = Depends(get_db), 

397 current_user: User = Depends(get_current_user), 

398): 

399 """Read a board, queueing a refresh for any dynamic widget gone stale. 

400 

401 A built-in board is readable by everyone, and anyone's view may queue its 

402 stale tiles: those cache only what belongs to nobody, and a claimed tile 

403 is not queued twice (``refresh.mark_refreshing``).""" 

404 dashboard = _readable_dashboard(db, dashboard_id, current_user) 

405 widgets = _widgets_of(db, dashboard.id) 

406 refreshing = _queue_stale_refreshes(db, widgets, background_tasks) 

407 return _read_with_widgets(dashboard, widgets, refreshing) 

408 

409 

410@dashboard_router.post( 

411 "", 

412 response_model=Schema.Dashboard.ReadWithWidgets, 

413 status_code=status.HTTP_201_CREATED, 

414) 

415def create_dashboard( 

416 body: Schema.Dashboard.Create, 

417 db: Session = Depends(get_db), 

418 current_user: User = Depends(get_current_user), 

419): 

420 """Create a board, optionally seeded with widgets from a template. 

421 

422 Also the landing point for a reviewed generation proposal: when the body 

423 carries a ``generation_id``, the board is stamped as generated and the 

424 run is marked applied, so a generated board is distinguishable from a 

425 hand-built one and resolves back to the description that produced it. 

426 """ 

427 data = body.model_dump(exclude={"widgets", "generation_id"}) 

428 if not data.get("owner_organisation_id") and not data.get("owner_project_id"): 

429 # The workspace the request was made in (app/dependency/workspace.py). 

430 data.update(owner_for(db, current_user, model=Dashboard)) 

431 verify_owner_scope(data, current_user, db, model=Dashboard) 

432 

433 run = generation_service.resolve(db, body.generation_id, current_user) 

434 

435 # Validate every inline widget before writing anything, so a bad tile 

436 # does not leave a half-built board behind. 

437 seeded = [ 

438 (w, _validated_config(w.widget_type, w.config, db, current_user)) 

439 for w in body.widgets 

440 ] 

441 

442 dashboard = Dashboard(**data) 

443 generation_service.stamp([dashboard], run) 

444 try: 

445 db.add(dashboard) 

446 db.flush() 

447 for index, (spec, config) in enumerate(seeded): 

448 db.add( 

449 DashboardWidget( 

450 dashboard_id=dashboard.id, 

451 widget_type=spec.widget_type, 

452 title=spec.title, 

453 config=config, 

454 x=spec.x, 

455 y=spec.y, 

456 w=spec.w, 

457 h=spec.h, 

458 position=spec.position or index, 

459 refresh_interval_seconds=spec.refresh_interval_seconds, 

460 ) 

461 ) 

462 generation_service.apply( 

463 db, 

464 run, 

465 target_resource_type=HistoryEnum.ResourceType.dashboard, 

466 target_resource_id=dashboard.id, 

467 ) 

468 db.commit() 

469 db.refresh(dashboard) 

470 history_service.record_version( 

471 db, 

472 resource_type=HistoryEnum.ResourceType.dashboard, 

473 model=Dashboard, 

474 resource=dashboard, 

475 action=HistoryEnum.Action.created, 

476 actor=current_user, 

477 children_resolver=lambda: dashboard_children_snapshot(db, dashboard.id), 

478 ) 

479 db.commit() 

480 except IntegrityError as exc: 

481 db.rollback() 

482 raise _conflict(exc) from exc 

483 except Exception: 

484 db.rollback() 

485 logger.exception("Failed to create dashboard") 

486 raise 

487 

488 return _read_with_widgets(dashboard, _widgets_of(db, dashboard.id)) 

489 

490 

491@dashboard_router.patch("/{dashboard_id}", response_model=Schema.Dashboard.Read) 

492def update_dashboard( 

493 dashboard_id: UUID, 

494 body: Schema.Dashboard.Update, 

495 db: Session = Depends(get_db), 

496 current_user: User = Depends(get_current_user), 

497): 

498 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

499 for field, value in body.model_dump(exclude_unset=True).items(): 

500 setattr(dashboard, field, value) 

501 history_service.record_version( 

502 db, 

503 resource_type=HistoryEnum.ResourceType.dashboard, 

504 model=Dashboard, 

505 resource=dashboard, 

506 action=HistoryEnum.Action.updated, 

507 actor=current_user, 

508 children_resolver=lambda: dashboard_children_snapshot(db, dashboard_id), 

509 ) 

510 try: 

511 db.commit() 

512 db.refresh(dashboard) 

513 except IntegrityError as exc: 

514 db.rollback() 

515 raise _conflict(exc) from exc 

516 except Exception: 

517 db.rollback() 

518 logger.exception("Failed to update dashboard %s", dashboard_id) 

519 raise 

520 return _read(dashboard, len(_widgets_of(db, dashboard.id))) 

521 

522 

523@dashboard_router.delete("/{dashboard_id}", status_code=status.HTTP_204_NO_CONTENT) 

524def delete_dashboard( 

525 dashboard_id: UUID, 

526 db: Session = Depends(get_db), 

527 current_user: User = Depends(get_current_user), 

528): 

529 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

530 history_service.record_version( 

531 db, 

532 resource_type=HistoryEnum.ResourceType.dashboard, 

533 model=Dashboard, 

534 resource=dashboard, 

535 action=HistoryEnum.Action.deleted, 

536 actor=current_user, 

537 children_resolver=lambda: dashboard_children_snapshot(db, dashboard_id), 

538 ) 

539 db.delete(dashboard) 

540 db.commit() 

541 

542 

543@dashboard_router.post("/{dashboard_id}/home", response_model=Schema.Dashboard.Read) 

544def set_home_dashboard( 

545 dashboard_id: UUID, 

546 db: Session = Depends(get_db), 

547 current_user: User = Depends(get_current_user), 

548): 

549 """Make this the owner's home board, demoting whichever held the flag. 

550 

551 Both writes land in one transaction — the partial unique index would 

552 reject the promotion otherwise. 

553 """ 

554 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

555 

556 siblings = ( 

557 _owner_filter(db.query(Dashboard), dashboard) 

558 .filter(Dashboard.is_home.is_(True)) 

559 .all() 

560 ) 

561 try: 

562 for sibling in siblings: 

563 if sibling.id != dashboard.id: 

564 sibling.is_home = False 

565 db.flush() 

566 dashboard.is_home = True 

567 db.commit() 

568 db.refresh(dashboard) 

569 except IntegrityError as exc: 

570 db.rollback() 

571 raise _conflict(exc) from exc 

572 except Exception: 

573 db.rollback() 

574 logger.exception("Failed to set dashboard %s as home", dashboard_id) 

575 raise 

576 return _read(dashboard, len(_widgets_of(db, dashboard.id))) 

577 

578 

579# --------------------------------------------------------------------------- 

580# Widgets 

581# --------------------------------------------------------------------------- 

582 

583 

584@dashboard_router.post( 

585 "/{dashboard_id}/widgets", 

586 response_model=Schema.DashboardWidget.Read, 

587 status_code=status.HTTP_201_CREATED, 

588) 

589def add_widget( 

590 dashboard_id: UUID, 

591 body: Schema.DashboardWidget.Create, 

592 background_tasks: BackgroundTasks, 

593 db: Session = Depends(get_db), 

594 current_user: User = Depends(get_current_user), 

595): 

596 """Add a tile. Dynamic tiles generate their first result immediately.""" 

597 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

598 config = _validated_config(body.widget_type, body.config, db, current_user) 

599 

600 widget = DashboardWidget( 

601 dashboard_id=dashboard.id, 

602 widget_type=body.widget_type, 

603 title=body.title, 

604 config=config, 

605 x=body.x, 

606 y=body.y, 

607 w=body.w, 

608 h=body.h, 

609 position=body.position, 

610 refresh_interval_seconds=body.refresh_interval_seconds, 

611 ) 

612 try: 

613 db.add(widget) 

614 db.commit() 

615 db.refresh(widget) 

616 except Exception: 

617 db.rollback() 

618 logger.exception("Failed to add widget to dashboard %s", dashboard_id) 

619 raise 

620 

621 if widget_registry.get_renderer(widget.widget_type).is_dynamic: 

622 refresh_service.mark_refreshing(db, widget) 

623 background_tasks.add_task( 

624 refresh_service.refresh_widget_task, widget.id, Trigger.created 

625 ) 

626 

627 return Schema.DashboardWidget.Read.model_validate(widget) 

628 

629 

630@dashboard_router.patch( 

631 "/{dashboard_id}/widgets/{widget_id}", 

632 response_model=Schema.DashboardWidget.Read, 

633) 

634def update_widget( 

635 dashboard_id: UUID, 

636 widget_id: UUID, 

637 body: Schema.DashboardWidget.Update, 

638 background_tasks: BackgroundTasks, 

639 db: Session = Depends(get_db), 

640 current_user: User = Depends(get_current_user), 

641): 

642 """Edit a tile. Changing a dynamic tile's config regenerates its result.""" 

643 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

644 widget = _get_widget(db, dashboard, widget_id) 

645 

646 changes = body.model_dump(exclude_unset=True) 

647 config_changed = False 

648 if "config" in changes: 

649 new_config = _validated_config( 

650 widget.widget_type, changes["config"], db, current_user 

651 ) 

652 config_changed = new_config != (widget.config or {}) 

653 changes["config"] = new_config 

654 

655 for field, value in changes.items(): 

656 setattr(widget, field, value) 

657 

658 try: 

659 db.commit() 

660 db.refresh(widget) 

661 except Exception: 

662 db.rollback() 

663 logger.exception("Failed to update widget %s", widget_id) 

664 raise 

665 

666 # A tile whose prompt or subjects changed is showing an answer to the old 

667 # question, so regenerate rather than wait for the interval to lapse. 

668 if config_changed and widget_registry.get_renderer(widget.widget_type).is_dynamic: 

669 refresh_service.mark_refreshing(db, widget) 

670 background_tasks.add_task( 

671 refresh_service.refresh_widget_task, widget.id, Trigger.updated 

672 ) 

673 

674 return Schema.DashboardWidget.Read.model_validate(widget) 

675 

676 

677@dashboard_router.delete( 

678 "/{dashboard_id}/widgets/{widget_id}", status_code=status.HTTP_204_NO_CONTENT 

679) 

680def delete_widget( 

681 dashboard_id: UUID, 

682 widget_id: UUID, 

683 db: Session = Depends(get_db), 

684 current_user: User = Depends(get_current_user), 

685): 

686 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

687 widget = _get_widget(db, dashboard, widget_id) 

688 db.delete(widget) 

689 db.commit() 

690 

691 

692@dashboard_router.put( 

693 "/{dashboard_id}/layout", response_model=list[Schema.DashboardWidget.Read] 

694) 

695def save_layout( 

696 dashboard_id: UUID, 

697 body: Schema.DashboardWidget.LayoutUpdate, 

698 db: Session = Depends(get_db), 

699 current_user: User = Depends(get_current_user), 

700): 

701 """Persist the whole grid in one write after a drag or resize. 

702 

703 Placements for widgets on another board are ignored rather than rejected, 

704 so a stale client cannot move tiles it should not see. 

705 """ 

706 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

707 widgets = {w.id: w for w in _widgets_of(db, dashboard.id)} 

708 

709 for index, placement in enumerate(body.placements): 

710 widget = widgets.get(placement.id) 

711 if widget is None: 

712 continue 

713 widget.x = placement.x 

714 widget.y = placement.y 

715 widget.w = placement.w 

716 widget.h = placement.h 

717 widget.position = index 

718 

719 try: 

720 db.commit() 

721 except Exception: 

722 db.rollback() 

723 logger.exception("Failed to save layout for dashboard %s", dashboard_id) 

724 raise 

725 

726 return [ 

727 Schema.DashboardWidget.Read.model_validate(w) 

728 for w in _widgets_of(db, dashboard.id) 

729 ] 

730 

731 

732@dashboard_router.post( 

733 "/{dashboard_id}/widgets/{widget_id}/refresh", 

734 response_model=Schema.DashboardWidget.Read, 

735 status_code=status.HTTP_202_ACCEPTED, 

736) 

737def refresh_widget_now( 

738 dashboard_id: UUID, 

739 widget_id: UUID, 

740 background_tasks: BackgroundTasks, 

741 db: Session = Depends(get_db), 

742 current_user: User = Depends(get_current_user), 

743): 

744 """Force a dynamic tile to regenerate, ignoring its interval. 

745 

746 Refreshing is using the board, so a reader may; but not a built-in 

747 board, whose cached tiles are shared by every user and whose refresh 

748 spends the platform's money.""" 

749 dashboard = _readable_dashboard(db, dashboard_id, current_user) 

750 if getattr(dashboard, "is_system", False) is True: 

751 raise HTTPException( 

752 status_code=status.HTTP_403_FORBIDDEN, detail=SYSTEM_READ_ONLY_DETAIL 

753 ) 

754 widget = _get_widget(db, dashboard, widget_id) 

755 

756 if not widget_registry.get_renderer(widget.widget_type).is_dynamic: 

757 raise HTTPException( 

758 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

759 detail=f"Widget type '{widget.widget_type}' has nothing to refresh.", 

760 ) 

761 

762 refresh_service.mark_refreshing(db, widget) 

763 background_tasks.add_task( 

764 refresh_service.refresh_widget_task, widget.id, Trigger.manual 

765 ) 

766 return Schema.DashboardWidget.Read.model_validate(widget) 

767 

768 

769# --------------------------------------------------------------------------- 

770# A tile's document 

771# 

772# Rendered from the tile's latest stored answer, never from anything sent 

773# with the request (``app.services.documents``): its ```document fence, or 

774# with the tile's PDF on, its answer laid out. Anyone who may open the board 

775# may download it, a built-in board's included. 

776# --------------------------------------------------------------------------- 

777 

778 

779@dashboard_router.get( 

780 "/{dashboard_id}/widgets/{widget_id}/document.pdf", 

781 response_class=Response, 

782 responses={200: {"content": {"application/pdf": {}}}}, 

783) 

784def download_widget_document( 

785 dashboard_id: UUID, 

786 widget_id: UUID, 

787 index: int = Query(default=0, ge=0, le=100), 

788 db: Session = Depends(get_db), 

789 current_user: User = Depends(get_current_user), 

790): 

791 """The tile's latest answer as a PDF. ``index`` picks among the 

792 documents it holds.""" 

793 dashboard = _readable_dashboard(db, dashboard_id, current_user) 

794 widget = _get_widget(db, dashboard, widget_id) 

795 renderer = widget_registry.get_renderer(widget.widget_type) 

796 document = renderer.document(widget, index) 

797 if document is None: 

798 raise HTTPException( 

799 status_code=status.HTTP_404_NOT_FOUND, 

800 detail="This tile has no downloadable document.", 

801 ) 

802 return documents_service.pdf_response( 

803 document, 

804 footer=documents_service.widget_footer(dashboard, widget), 

805 when=documents_service.widget_refreshed_at(widget), 

806 ) 

807 

808 

809@dashboard_router.get( 

810 "/{dashboard_id}/widgets/{widget_id}/images/{asset}", 

811 response_class=Response, 

812 responses={200: {"content": {"image/png": {}, "image/jpeg": {}}}}, 

813) 

814def widget_document_image( 

815 dashboard_id: UUID, 

816 widget_id: UUID, 

817 asset: str = Path(pattern=document_images.ASSET_ID.pattern), 

818 db: Session = Depends(get_db), 

819 current_user: User = Depends(get_current_user), 

820): 

821 """An image a document in the tile's latest answer shows — the copy 

822 svc-ai stored when it made the document, and only one that document 

823 names.""" 

824 dashboard = _readable_dashboard(db, dashboard_id, current_user) 

825 widget = _get_widget(db, dashboard, widget_id) 

826 payload = widget.cache_payload if isinstance(widget.cache_payload, dict) else {} 

827 return documents_service.image_response( 

828 documents_service.document_fences(payload.get("markdown")), asset 

829 ) 

830 

831 

832# --------------------------------------------------------------------------- 

833# Saved-message items 

834# 

835# Appending server-side rather than having the client PATCH a rewritten config 

836# keeps two concurrent saves from clobbering one another, and means the chat UI 

837# never has to read the widget before writing to it. 

838# --------------------------------------------------------------------------- 

839 

840 

841def _list_widget(db: Session, dashboard: Dashboard, widget_id: UUID) -> DashboardWidget: 

842 widget = _get_widget(db, dashboard, widget_id) 

843 if widget.widget_type != DashboardEnum.WidgetType.message_list: 

844 raise HTTPException( 

845 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

846 detail=f"Widget type '{widget.widget_type}' does not hold a list.", 

847 ) 

848 return widget 

849 

850 

851def _store_items(db: Session, widget: DashboardWidget, items: list[dict]) -> None: 

852 # JSON columns are replaced wholesale, not mutated in place — assigning a 

853 # new dict is what marks the attribute dirty for SQLAlchemy. 

854 widget.config = {**(widget.config or {}), "items": items} 

855 try: 

856 db.add(widget) 

857 db.commit() 

858 db.refresh(widget) 

859 except Exception: 

860 db.rollback() 

861 logger.exception("Failed to store items on widget %s", widget.id) 

862 raise 

863 

864 

865@dashboard_router.post( 

866 "/{dashboard_id}/widgets/{widget_id}/items", 

867 response_model=Schema.DashboardWidget.Read, 

868 status_code=status.HTTP_201_CREATED, 

869) 

870def save_item( 

871 dashboard_id: UUID, 

872 widget_id: UUID, 

873 body: Schema.DashboardWidget.SaveItem, 

874 db: Session = Depends(get_db), 

875 current_user: User = Depends(get_current_user), 

876): 

877 """Save a chat message into a saved-messages widget. 

878 

879 Newest first, trimmed to the widget's ``max_items`` so a list a user keeps 

880 saving into stays a readable tile rather than growing without bound. 

881 """ 

882 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

883 widget = _list_widget(db, dashboard, widget_id) 

884 

885 renderer = widget_registry.get_renderer(widget.widget_type) 

886 try: 

887 item = renderer.normalise_item(body.model_dump(exclude_none=True)) 

888 except widget_registry.WidgetConfigError as exc: 

889 raise HTTPException( 

890 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) 

891 ) from exc 

892 

893 config = widget.config or {} 

894 max_items = config.get("max_items") or 25 

895 items = [item, *(config.get("items") or [])][:max_items] 

896 _store_items(db, widget, items) 

897 return Schema.DashboardWidget.Read.model_validate(widget) 

898 

899 

900@dashboard_router.delete( 

901 "/{dashboard_id}/widgets/{widget_id}/items/{item_id}", 

902 response_model=Schema.DashboardWidget.Read, 

903) 

904def delete_item( 

905 dashboard_id: UUID, 

906 widget_id: UUID, 

907 item_id: str, 

908 db: Session = Depends(get_db), 

909 current_user: User = Depends(get_current_user), 

910): 

911 """Remove one saved message from a list.""" 

912 dashboard = _owned_dashboard(db, dashboard_id, current_user) 

913 widget = _list_widget(db, dashboard, widget_id) 

914 

915 existing = (widget.config or {}).get("items") or [] 

916 remaining = [item for item in existing if item.get("id") != item_id] 

917 if len(remaining) == len(existing): 

918 raise HTTPException( 

919 status_code=status.HTTP_404_NOT_FOUND, detail="Saved message not found" 

920 ) 

921 

922 _store_items(db, widget, remaining) 

923 return Schema.DashboardWidget.Read.model_validate(widget) 

924 

925 

926register_history_routes( 

927 dashboard_router, 

928 resource_type=HistoryEnum.ResourceType.dashboard, 

929 model=Dashboard, 

930 not_found_detail="Dashboard not found", 

931 # A built-in board's history is its release history, readable by all. 

932 access_check=verify_resource_read, 

933)