Coverage for app / router / app / activity / router.py: 98%
125 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"""The account-wide activity feed — the audit trail read across resources.
3``register_history_routes`` answers "what happened to *this* resource".
4These endpoints answer the other half of the question an operator actually
5asks: "what happened, across everything I have?" Same ``ResourceVersion``
6rows underneath, read sideways instead of down, so a change shows up in the
7feed for free the moment a resource starts recording history — there is no
8second write path to keep in step, and nothing to add per resource type.
10Inference is deliberately *not* merged in here. Conversations and LLM
11invocations already have read paths of their own (``/app/conversations``,
12``/app/stats/invocations``) with their own shapes and their own scoping; a
13union endpoint would have to flatten all three into a lowest-common-
14denominator row and re-implement two sets of filters. The client composes
15the streams instead, which keeps each one honest about its own payload.
17Read-only by design, like ``/app/generations``: an editable audit trail is
18not one.
19"""
21import logging
22from datetime import datetime
23from typing import Optional
24from uuid import UUID
26from fastapi import APIRouter, Depends, HTTPException, Query, status
27from sqlalchemy.orm import Session
29from app.db.postgres.crud_schemas import Schema
30from app.db.postgres.enums import BackgroundEnum, HistoryEnum
31from app.db.postgres.models import GenerationRun, ResourceVersion, User
32from app.dependency.base import get_db
33from app.dependency.user.context import get_current_user
34from app.dependency.workspace import request_workspace
35from app.services import background_activity
36from app.services import diff as diff_service
38logger = logging.getLogger(__name__)
40activity_router = APIRouter(prefix="/activity", tags=["App - Activity"])
42#: Hard ceiling on a single page, so a client cannot ask for the whole trail.
43MAX_LIMIT = 500
46def _scoped(db: Session, current_user: User):
47 """Base query for versions the caller is entitled to see.
49 Scoped by *actor*: the feed is "what have I done", which is the question
50 the page asks. And by the request's workspace: a version's snapshot
51 holds its resource's owner columns as they stood (``history``), so a
52 personal edit stays in Personal and an organisation's in the
53 organisation, even for a resource since deleted. Superusers see every
54 actor's, within the workspace.
56 Per-resource history stays the place to see another member's edits to a
57 resource you can access, since it can check the live resource.
58 """
59 query = db.query(ResourceVersion).filter(
60 _in_workspace(request_workspace(db, current_user))
61 )
62 if not current_user.is_superuser:
63 query = query.filter(ResourceVersion.actor_user_id == current_user.id)
64 return query
67def _in_workspace(ws):
68 """SQL: versions of what ``ws`` owned — by the snapshot's owner columns,
69 and the organisation's or project's own versions."""
70 from sqlalchemy import and_, or_
72 from app.db.postgres.enums import HistoryEnum
73 from app.services.workspace import WorkspaceKind
75 V = ResourceVersion
76 org = V.snapshot["owner_organisation_id"].as_string()
77 project = V.snapshot["owner_project_id"].as_string()
78 H = HistoryEnum.ResourceType
79 if ws.kind is WorkspaceKind.organisation:
80 return or_(
81 org == str(ws.id),
82 and_(V.resource_type == H.organisation, V.resource_id == ws.id),
83 )
84 if ws.kind is WorkspaceKind.project:
85 return or_(
86 project == str(ws.id),
87 and_(V.resource_type == H.project, V.resource_id == ws.id),
88 )
89 return and_(org.is_(None), project.is_(None), V.resource_type != H.organisation)
92def _snapshot(version: ResourceVersion) -> dict:
93 return version.snapshot if isinstance(version.snapshot, dict) else {}
96def _resource_name(version: ResourceVersion) -> Optional[str]:
97 """The resource's name as it stood at this version.
99 Read from the snapshot rather than the live row on purpose: a deleted
100 resource has no live row, and that is exactly the event whose label
101 matters most. ``title`` covers resources that name themselves that way.
102 """
103 snapshot = _snapshot(version)
104 for key in ("name", "title", "display_name"):
105 value = snapshot.get(key)
106 if isinstance(value, str) and value.strip():
107 return value
108 return None
111def _generation_ref(
112 generation: Optional[GenerationRun],
113) -> Optional[Schema.History.GenerationRef]:
114 if not generation:
115 return None
116 return Schema.History.GenerationRef(
117 id=generation.id,
118 flow=generation.flow,
119 status=generation.status,
120 provider=generation.provider,
121 model_name=generation.model_name,
122 created_at=generation.created_at,
123 )
126def _event_fields(
127 version: ResourceVersion,
128 actor: Optional[User],
129 generation: Optional[GenerationRun],
130) -> dict:
131 generation_id = getattr(version, "generation_id", None)
132 return {
133 "id": version.id,
134 "resource_type": version.resource_type,
135 "resource_id": version.resource_id,
136 "resource_name": _resource_name(version),
137 "action": version.action,
138 "version_number": version.version_number,
139 "changed_fields": version.changed_fields or [],
140 "actor_user_id": version.actor_user_id,
141 "actor_name": actor.name if actor else None,
142 "actor_email": actor.email if actor else None,
143 # Prefer the version's own link, falling back to the snapshot flag so
144 # rows written before generation runs existed still read correctly —
145 # same precedence the per-resource history uses.
146 "is_ai_generated": (
147 True if generation_id else _snapshot(version).get("is_ai_generated")
148 ),
149 "generation_id": generation_id,
150 "generation": _generation_ref(generation),
151 "created_at": version.created_at,
152 }
155def _resolve_actors(db: Session, versions: list[ResourceVersion]) -> dict[UUID, User]:
156 """One query for the whole page rather than one per row."""
157 actor_ids = {v.actor_user_id for v in versions if v.actor_user_id}
158 if not actor_ids:
159 return {}
160 return {u.id: u for u in db.query(User).filter(User.id.in_(actor_ids)).all()}
163def _resolve_generations(
164 db: Session, versions: list[ResourceVersion]
165) -> dict[UUID, GenerationRun]:
166 generation_ids = {
167 gid for v in versions if (gid := getattr(v, "generation_id", None))
168 }
169 if not generation_ids:
170 return {}
171 return {
172 g.id: g
173 for g in db.query(GenerationRun)
174 .filter(GenerationRun.id.in_(generation_ids))
175 .all()
176 }
179def _matches_search(version: ResourceVersion, needle: str) -> bool:
180 """Substring match over the fields a reader can actually see on a row.
182 Done in Python because the only useful text — the resource's name — lives
183 inside the JSON snapshot, where a portable ``LIKE`` is not available
184 across the SQLite used in tests and the Postgres used everywhere else.
185 """
186 haystack = " ".join(
187 part
188 for part in (
189 _resource_name(version),
190 str(version.resource_type.value if version.resource_type else ""),
191 str(version.resource_id),
192 str(version.action.value if version.action else ""),
193 " ".join(version.changed_fields or []),
194 )
195 if part
196 ).lower()
197 return needle in haystack
200@activity_router.get("", response_model=Schema.Activity.EventList)
201def list_activity(
202 resource_type: Optional[list[HistoryEnum.ResourceType]] = Query(default=None),
203 action: Optional[HistoryEnum.Action] = None,
204 generated_only: bool = False,
205 since: Optional[datetime] = None,
206 search: Optional[str] = None,
207 limit: int = 100,
208 offset: int = 0,
209 db: Session = Depends(get_db),
210 current_user: User = Depends(get_current_user),
211):
212 """The caller's resource changes, newest first.
214 ``total`` counts everything matching the filters, not just this page, so
215 a client can show "showing 100 of 4,213" without a second request.
216 """
217 limit = max(1, min(limit, MAX_LIMIT))
218 offset = max(0, offset)
220 query = _scoped(db, current_user)
221 if resource_type:
222 query = query.filter(ResourceVersion.resource_type.in_(resource_type))
223 if action:
224 query = query.filter(ResourceVersion.action == action)
225 if since:
226 query = query.filter(ResourceVersion.created_at >= since)
227 if generated_only:
228 query = query.filter(ResourceVersion.generation_id.isnot(None))
230 rows = query.order_by(ResourceVersion.created_at.desc()).all()
232 needle = (search or "").strip().lower()
233 if needle:
234 rows = [row for row in rows if _matches_search(row, needle)]
236 total = len(rows)
237 page = rows[offset : offset + limit]
239 actors = _resolve_actors(db, page)
240 generations = _resolve_generations(db, page)
242 return Schema.Activity.EventList(
243 events=[
244 Schema.Activity.Event(
245 **_event_fields(
246 version,
247 actors.get(version.actor_user_id),
248 generations.get(getattr(version, "generation_id", None)),
249 )
250 )
251 for version in page
252 ],
253 total=total,
254 )
257@activity_router.get("/summary", response_model=Schema.Activity.Summary)
258def activity_summary(
259 since: Optional[datetime] = None,
260 db: Session = Depends(get_db),
261 current_user: User = Depends(get_current_user),
262):
263 """Counts over the same rows the feed lists, for the headline strip.
265 Registered before ``/{version_id}`` so the literal path wins over the
266 parameterised one.
267 """
268 query = _scoped(db, current_user)
269 if since:
270 query = query.filter(ResourceVersion.created_at >= since)
271 rows = query.all()
273 by_type: dict[HistoryEnum.ResourceType, int] = {}
274 counts = {action: 0 for action in HistoryEnum.Action}
275 ai_generated = 0
277 for row in rows:
278 if row.action in counts:
279 counts[row.action] += 1
280 by_type[row.resource_type] = by_type.get(row.resource_type, 0) + 1
281 if getattr(row, "generation_id", None) or _snapshot(row).get("is_ai_generated"):
282 ai_generated += 1
284 return Schema.Activity.Summary(
285 total=len(rows),
286 created=counts[HistoryEnum.Action.created],
287 updated=counts[HistoryEnum.Action.updated],
288 deleted=counts[HistoryEnum.Action.deleted],
289 ai_generated=ai_generated,
290 by_resource_type=[
291 Schema.Activity.TypeCount(resource_type=rtype, count=count)
292 for rtype, count in sorted(
293 by_type.items(), key=lambda item: item[1], reverse=True
294 )
295 ],
296 )
299@activity_router.get("/background", response_model=Schema.Activity.BackgroundEventList)
300def list_background_activity(
301 kind: Optional[list[BackgroundEnum.Kind]] = Query(default=None),
302 since: Optional[datetime] = None,
303 limit: int = 100,
304 offset: int = 0,
305 db: Session = Depends(get_db),
306 current_user: User = Depends(get_current_user),
307):
308 """Work done in the background on what the request's workspace owns,
309 newest first.
311 Scoped by *owner* rather than actor, unlike the change feed above: nobody
312 acted — the scheduler, a board load or a crawl worker did — so the only
313 question the row can answer is whose thing it was done to: a personal
314 board's refresh is Personal's, an organisation's crawl the
315 organisation's, and neither shows in the other.
316 """
317 events, total = background_activity.list_for_owner(
318 db,
319 current_user.id,
320 workspace=request_workspace(db, current_user),
321 kinds=kind,
322 since=since,
323 limit=max(1, min(limit, MAX_LIMIT)),
324 offset=max(0, offset),
325 )
326 return Schema.Activity.BackgroundEventList(
327 events=[Schema.Activity.BackgroundEvent.model_validate(e) for e in events],
328 total=total,
329 retention_days=background_activity.retention_days(),
330 )
333@activity_router.get("/{version_id}", response_model=Schema.Activity.EventDetail)
334def get_activity_event(
335 version_id: UUID,
336 db: Session = Depends(get_db),
337 current_user: User = Depends(get_current_user),
338):
339 """One event, with the snapshot taken at the time and the diff against
340 the version before it.
342 The diff is computed here rather than by the resource's own
343 ``/history/diff`` endpoint because the feed is heterogeneous: a client
344 walking a mixed stream would otherwise need a resource-type-to-URL map
345 and a different request shape per row.
346 """
347 version = db.get(ResourceVersion, version_id)
348 if not version:
349 raise HTTPException(
350 status_code=status.HTTP_404_NOT_FOUND, detail="Activity event not found"
351 )
352 if not current_user.is_superuser and version.actor_user_id != current_user.id:
353 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
355 # The version immediately before this one for the same resource. Ordered
356 # and taken in Python so the comparison is against the true predecessor
357 # even where version numbers have gaps.
358 siblings = (
359 db.query(ResourceVersion)
360 .filter(
361 ResourceVersion.resource_type == version.resource_type,
362 ResourceVersion.resource_id == version.resource_id,
363 )
364 .all()
365 )
366 previous = max(
367 (s for s in siblings if s.version_number < version.version_number),
368 key=lambda s: s.version_number,
369 default=None,
370 )
372 actor = None
373 if version.actor_user_id:
374 actor = db.get(User, version.actor_user_id)
375 generation = None
376 if getattr(version, "generation_id", None):
377 generation = db.get(GenerationRun, version.generation_id)
379 field_diffs = diff_service.compute_diff(
380 previous.snapshot if previous else None, version.snapshot
381 )
382 children_diff = diff_service.compute_children_diff(
383 previous.children_snapshot if previous else None, version.children_snapshot
384 )
386 children_snapshot = (
387 version.children_snapshot
388 if isinstance(version.children_snapshot, dict)
389 else None
390 )
392 return Schema.Activity.EventDetail(
393 **_event_fields(version, actor, generation),
394 snapshot=_snapshot(version),
395 children_snapshot=children_snapshot,
396 diff=Schema.History.DiffResponse(
397 from_version=previous.version_number if previous else None,
398 to_version=version.version_number,
399 fields=[Schema.History.FieldDiff(**fd) for fd in field_diffs],
400 children_diff={
401 key: Schema.History.ChildrenDiffEntry(**entry)
402 for key, entry in children_diff.items()
403 },
404 ),
405 )