Skip to content

feat(api): Stamp a session's trigger origin, add liveness filters and last message - #5767

Open
ardaerzin wants to merge 1 commit into
feat/mobile-parity-and-consolidationfrom
api/session-trigger-stamp
Open

feat(api): Stamp a session's trigger origin, add liveness filters and last message#5767
ardaerzin wants to merge 1 commit into
feat/mobile-parity-and-consolidationfrom
api/session-trigger-stamp

Conversation

@ardaerzin

Copy link
Copy Markdown
Contributor

Context

The sessions UX rework needs three things the sessions API did not provide: knowing which sessions an automation started (so the list can hide them by default and show them as a mode), filtering the list by liveness or an explicit id set (for the "waiting" pushdown), and a per-session last message for previews.

Changes

  • Sessions created by a dispatched trigger are stamped with origin: "trigger" and a reference to the trigger that started them. Queue-dispatched triggers stamp the same way.
  • The session list accepts an origin filter (used to exclude automation runs by default), a liveness filter, and an explicit id set.
  • A session can report its last message, so list rows render a preview without loading the transcript.

Tests / notes

  • New unit tests: test_session_trigger_stamp, test_session_last_message, test_query_sessions_filters; updated root-service, search and references tests.
  • Based on feat/mobile-parity-and-consolidation, not main: the changes build on that branch's session liveness and records work, and the patch does not apply on main (two of the test files do not exist there).

…expose its last message

Sessions started by an automation carry origin and trigger references, and the list hides them by default (origin filter). The list also filters by liveness and an explicit id set, and each session can report its last message for previews.
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Aug 6, 2026
@vercel

vercel Bot commented Aug 6, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agenta-documentation Ready Ready Preview Aug 6, 2026 7:58am

Request Review

@dosubot dosubot Bot added Backend Feature Request New feature or request labels Aug 6, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added advanced session filtering by IDs, origin, tags, stream status, archived/ended state, and exclusions.
    • Session listings can now include the latest message preview and an optional total matching count.
    • Trigger-created sessions are linked to their originating trigger and delivery.
  • Bug Fixes
    • Improved handling of empty, deleted, or unavailable messages so session listings remain reliable.
  • Tests
    • Expanded coverage for filtering, counts, message previews, and trigger metadata.

Walkthrough

The PR expands session queries with filtering and total counts, adds batched latest-message previews, and links trigger deliveries to session IDs and origin metadata. It also wires the required services and adds unit coverage for these paths.

Changes

Session infrastructure

Layer / File(s) Summary
Session query contracts
api/oss/src/apis/fastapi/sessions/models.py, api/oss/src/core/sessions/dtos.py, api/oss/src/core/sessions/streams/...
Session requests and queries support flags, tags, origins, explicit session ID inclusion and exclusion, and optional totals. Stream interfaces expose matching query and count operations.
Latest message previews
api/oss/src/core/sessions/records/..., api/oss/src/dbs/postgres/sessions/records/dao.py, api/oss/tests/pytest/unit/sessions/test_session_last_message.py
Records services and DAOs provide batched newest-message previews. Session list items include optional preview data.
Filtered session listing and counts
api/oss/src/core/sessions/service.py, api/oss/src/core/sessions/streams/service.py, api/oss/src/dbs/postgres/sessions/streams/dao.py, api/oss/src/apis/fastapi/sessions/router.py, api/oss/tests/pytest/unit/sessions/test_query_sessions_*.py, api/oss/tests/pytest/unit/sessions/test_sessions_root_service.py
Session listing resolves reference and explicit ID restrictions, applies shared predicates, enriches results, and supports matching count queries.
Trigger session attribution
api/oss/src/tasks/asyncio/triggers/dispatcher.py, api/oss/src/core/triggers/dtos.py, api/entrypoints/worker_queues.py, api/entrypoints/routers.py, api/oss/tests/pytest/unit/sessions/test_session_trigger_stamp.py
Trigger dispatch creates and propagates session IDs, then best-effort stamps origin and trigger metadata through SessionStreamsService.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

Session query flow

sequenceDiagram
  participant Client
  participant SessionsRootRouter
  participant SessionsService
  participant SessionStreamsService
  participant RecordsService
  Client->>SessionsRootRouter: Submit session query
  SessionsRootRouter->>SessionsService: Build and execute SessionQuery
  SessionsService->>SessionStreamsService: Query filtered streams
  SessionsService->>RecordsService: Fetch latest message previews
  SessionsRootRouter-->>Client: Return sessions and optional total
Loading

Trigger session attribution

sequenceDiagram
  participant TriggerBroker
  participant TriggersDispatcher
  participant Workflow
  participant SessionStreamsService
  TriggerBroker->>TriggersDispatcher: Dispatch trigger
  TriggersDispatcher->>TriggersDispatcher: Generate session ID
  TriggersDispatcher->>Workflow: Send session ID in request
  TriggersDispatcher->>SessionStreamsService: Stamp trigger origin
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.00% which is insufficient. The required threshold is 60.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: trigger-origin stamping, liveness filters, and last-message previews.
Description check ✅ Passed The description directly explains the session origin, filtering, last-message, and test changes in the pull request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch api/session-trigger-stamp

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Railway Preview Environment

Preview URL https://gateway-pr-5767.up.railway.app/w
Project agenta-oss-clone-spike
Image tag pr-5767-8cef37f
Status Deployed
Railway logs Open logs
Workflow logs View workflow run
Updated at 2026-08-06T08:04:49.934Z

@ardaerzin

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
api/oss/tests/pytest/unit/sessions/test_session_trigger_stamp.py (1)

68-139: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a dispatcher-level attribution test.

These tests call SessionStreamsService.set_origin directly. They do not test the new dispatcher contract.

Add a test that invokes TriggersDispatcher._run and verifies that one generated session_id is present in both TriggerDeliveryData and WorkflowServiceRequest. Also verify the stamped trigger ID, name, and subscription or schedule kind.

api/oss/tests/pytest/unit/sessions/test_query_sessions_filters.py (1)

83-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add origin tag filter coverage.

These tests do not verify tags or exclude_tags. Add one test for tag containment and one test that asserts excluded tags generate the tags IS NULL OR NOT tags @> ... predicate. This protects the required behavior for historic sessions with NULL tags.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f4e5037d-cada-4a8a-ab44-a9f5f2828d5a

📥 Commits

Reviewing files that changed from the base of the PR and between 1185ee2 and bbed383.

📒 Files selected for processing (22)
  • api/entrypoints/routers.py
  • api/entrypoints/worker_queues.py
  • api/oss/src/apis/fastapi/sessions/models.py
  • api/oss/src/apis/fastapi/sessions/router.py
  • api/oss/src/core/sessions/dtos.py
  • api/oss/src/core/sessions/records/dtos.py
  • api/oss/src/core/sessions/records/interfaces.py
  • api/oss/src/core/sessions/records/service.py
  • api/oss/src/core/sessions/service.py
  • api/oss/src/core/sessions/streams/dtos.py
  • api/oss/src/core/sessions/streams/interfaces.py
  • api/oss/src/core/sessions/streams/service.py
  • api/oss/src/core/triggers/dtos.py
  • api/oss/src/dbs/postgres/sessions/records/dao.py
  • api/oss/src/dbs/postgres/sessions/streams/dao.py
  • api/oss/src/tasks/asyncio/triggers/dispatcher.py
  • api/oss/tests/pytest/unit/sessions/test_query_sessions_filters.py
  • api/oss/tests/pytest/unit/sessions/test_query_sessions_references.py
  • api/oss/tests/pytest/unit/sessions/test_query_sessions_search.py
  • api/oss/tests/pytest/unit/sessions/test_session_last_message.py
  • api/oss/tests/pytest/unit/sessions/test_session_trigger_stamp.py
  • api/oss/tests/pytest/unit/sessions/test_sessions_root_service.py

Comment thread api/oss/src/apis/fastapi/sessions/models.py
Comment thread api/oss/src/apis/fastapi/sessions/router.py
Comment on lines +53 to +66
async def latest_message_per_session(
self,
*,
project_id: UUID,
session_ids: List[str],
) -> Dict[str, SessionMessagePreview]:
"""One batched lookup for a whole page — never one call per row."""
if not session_ids:
return {}

return await self.records_dao.latest_message_per_session(
project_id=project_id,
session_ids=session_ids,
)

@coderabbitai coderabbitai Bot Aug 6, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Return a named DTO from latest_message_per_session.

RecordsService.latest_message_per_session returns a raw Dict. Add a Pydantic container DTO in api/oss/src/core/sessions/records/dtos.py, return that DTO from this method, and update SessionsService to consume it.

As per coding guidelines, service methods must return typed DTOs and must not return raw dicts.

Source: Coding guidelines

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return is already fully typed: Dict[str, SessionMessagePreview], where SessionMessagePreview is a Pydantic DTO from records/dtos.py. A container DTO wrapping a keyed map adds a layer without adding type safety.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ardaerzin, SessionMessagePreview provides type safety for each map value. However, latest_message_per_session still returns a raw Python dict as its service result.

The coding guideline applies to the service return container, not only to its values. A small Pydantic DTO that contains the keyed previews would satisfy that contract. I will keep this finding open.

You are interacting with an AI system.

Comment thread api/oss/src/tasks/asyncio/triggers/dispatcher.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Backend Feature Request New feature or request size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant