Skip to content

feat(ai): GET /api/ai/chat/active-streams — DB-backed bootstrap endpoint#1163

Merged
2witstudios merged 3 commits into
masterfrom
pu/task7-active-streams
Apr 30, 2026
Merged

feat(ai): GET /api/ai/chat/active-streams — DB-backed bootstrap endpoint#1163
2witstudios merged 3 commits into
masterfrom
pu/task7-active-streams

Conversation

@2witstudios

@2witstudios 2witstudios commented Apr 30, 2026

Copy link
Copy Markdown
Owner

Summary

  • Adds GET /api/ai/chat/active-streams?channelId=<value> so any client can deterministically bootstrap multiplayer stream state on mount.
  • Queries aiStreamSessions for rows with status='streaming' started in the last 10 minutes; returns { streams: [{ messageId, conversationId, triggeredBy: { userId, displayName, tabId } }] }.
  • Auth: session-only, requireCSRF: false (read-only). Permissions: user:X:global channels require X === userId; otherwise canUserViewPage(userId, channelId).
  • Registers the missing @pagespace/db/schema/ai-streams subpath export so the route resolves.

Test plan

  • pnpm --filter web typecheck passes
  • 401 when unauthenticated
  • 400 when channelId is missing
  • 403 when user:X:global and X !== userId
  • 403 when pageId channel and user has no view permission
  • { streams: [] } when no rows in the 10-minute window
  • Returns full payload shape with active rows

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • New endpoint available to retrieve active AI chat stream sessions with real-time information about ongoing conversations, participants, and stream status for monitoring purposes.

New endpoint queries aiStreamSessions for streaming rows in the last 10 minutes
so any client can deterministically bootstrap multiplayer stream state on mount.
Adds the @pagespace/db/schema/ai-streams subpath export so the route resolves.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@2witstudios has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 41 minutes and 49 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 90e7187c-de35-4731-b2d6-c825c79aafb6

📥 Commits

Reviewing files that changed from the base of the PR and between b1ee428 and 08695cb.

📒 Files selected for processing (1)
  • apps/web/src/app/api/ai/chat/active-streams/route.ts
📝 Walkthrough

Walkthrough

Introduces a new API endpoint for retrieving active AI stream sessions with request authentication, channel authorization checks, and database queries for sessions started within the last 10 minutes. Also exports a new database schema entry point.

Changes

Cohort / File(s) Summary
Active Streams API Endpoint
apps/web/src/app/api/ai/chat/active-streams/route.ts
New GET endpoint that authenticates requests, validates channelId query parameter, performs authorization checks (special handling for user:(.+):global pattern and canUserViewPage), queries aiStreamSessions table for active streaming sessions within 10 minutes, and returns structured stream metadata with error handling.
Database Schema Export
packages/db/package.json
Added new export entry ./schema/ai-streams mapping to type definitions and JavaScript runtime files for @pagespace/db package.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API as GET /api/ai/chat/active-streams
    participant Auth as Authentication
    participant AuthZ as Authorization
    participant DB as aiStreamSessions
    participant Response

    Client->>API: Request with channelId query param
    API->>Auth: authenticateRequestWithOptions
    alt Auth Fails
        Auth-->>Response: Return auth error (4xx)
    else Auth Success
        API->>API: Validate channelId exists
        alt Missing channelId
            API-->>Response: Return 400 error
        else channelId Present
            API->>AuthZ: Check authorization
            alt user:(.+):global pattern & userId mismatch
                AuthZ-->>Response: Return 403 error
            else Other channelId or userId match
                AuthZ->>AuthZ: canUserViewPage check
                alt Access Denied
                    AuthZ-->>Response: Return 403 error
                else Access Granted
                    API->>DB: Query active streams<br/>(status=streaming, startedAt >= 10min ago)
                    DB-->>API: Return session rows
                    API->>Response: Return 200 with streams JSON
                end
            end
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A stream of sessions now flows free,
With auth checks standing guard with glee,
From database whispers, fresh and bright,
Ten minutes captured in the light,
The channels speak—who may see? ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(ai): GET /api/ai/chat/active-streams — DB-backed bootstrap endpoint' directly and specifically summarizes the main change: adding a new API endpoint with database backing for bootstrapping stream state.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pu/task7-active-streams

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
Review rate limit: 0/1 reviews remaining, refill in 41 minutes and 49 seconds.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web/src/app/api/ai/chat/active-streams/route.ts`:
- Around line 39-54: The query building the streams array is nondeterministic
because it lacks an ORDER BY; update the db query that selects from
aiStreamSessions (the streams query in route.ts) to add an explicit orderBy
(e.g., order by aiStreamSessions.startedAt DESC and a stable tie-breaker such as
aiStreamSessions.messageId ASC) so results are returned in a deterministic,
repeatable order for the bootstrap payload.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8c0a22ee-e911-493e-a40c-30c4042c6b08

📥 Commits

Reviewing files that changed from the base of the PR and between 617fa83 and b1ee428.

📒 Files selected for processing (2)
  • apps/web/src/app/api/ai/chat/active-streams/route.ts
  • packages/db/package.json

Comment thread apps/web/src/app/api/ai/chat/active-streams/route.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b1ee428344

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/web/src/app/api/ai/chat/active-streams/route.ts
2witstudios and others added 2 commits April 29, 2026 20:24
…ic payloads

Without ORDER BY, Postgres can return rows in varying order across requests,
producing unstable bootstrap payloads. Sort ascending by startedAt with
messageId as a stable tiebreaker.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…lures

Adds auditRequest calls on the three early-return paths (auth failure,
global-channel user mismatch, page view denial) so SIEM can detect probing
of the active-streams endpoint. Required by the security-audit-coverage
gate; mirrors the pattern in apps/web/src/app/api/ai/abort/route.ts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@2witstudios 2witstudios merged commit fce7b66 into master Apr 30, 2026
10 checks passed
@2witstudios 2witstudios deleted the pu/task7-active-streams branch April 30, 2026 02:30
2witstudios added a commit that referenced this pull request May 15, 2026
…int (#1163)

* feat(ai): GET /api/ai/chat/active-streams — DB-backed bootstrap endpoint

New endpoint queries aiStreamSessions for streaming rows in the last 10 minutes
so any client can deterministically bootstrap multiplayer stream state on mount.
Adds the @pagespace/db/schema/ai-streams subpath export so the route resolves.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): order active-streams by startedAt, messageId for deterministic payloads

Without ORDER BY, Postgres can return rows in varying order across requests,
producing unstable bootstrap payloads. Sort ascending by startedAt with
messageId as a stable tiebreaker.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): emit authz.access.denied audit events on auth/permission failures

Adds auditRequest calls on the three early-return paths (auth failure,
global-channel user mismatch, page view denial) so SIEM can detect probing
of the active-streams endpoint. Required by the security-audit-coverage
gate; mirrors the pattern in apps/web/src/app/api/ai/abort/route.ts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant