Feat(api) - migrate post chat read#624
Conversation
This commit introduces the handling of a short-lived Privy JWT in the workflow request body as `recoupAccessToken`. The implementation ensures that the token is validated and injected into the sandbox environment, allowing the `recoup-api` skill to authenticate successfully. Key changes include: - Updated schema in `lib/chat/validateChatWorkflow.ts` to accept `recoupAccessToken`. - Enhanced `AgentContext` to include the new token field. - Adjusted `handleChatWorkflowStream` to conditionally spread the token into the context. - Modified `buildRecoupExecEnv` to inject the token into the sandbox environment when present. Tests have been added to verify the new functionality, ensuring that the full suite passes successfully. Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit modifies the response structure for the chat read endpoints to enhance consistency. The return value for successful requests has been changed from `{ status: "ok" }` to `{ success: true }` across the relevant API routes and handler functions.
Key changes include:
- Updated JSDoc comments to reflect the new response format.
- Adjusted the implementation in `markChatReadHandler` and the corresponding test cases to ensure they validate the new response structure.
All tests have been updated accordingly and pass successfully.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughNew POST endpoint at ChangesMark Chat as Read Feature
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
This commit refactors the request creation in the `markChatReadHandler` and `validateMarkChatReadRequest` test files for improved readability. The `makeReq` function has been simplified to return a single line for the `NextRequest` instantiation, enhancing code clarity without altering functionality. All tests remain intact and pass successfully.
…upable/api into feat/migrate-post-chat-read
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
lib/sessions/chats/validateMarkChatReadRequest.ts (1)
44-63: ⚡ Quick winExtract a shared error response helper/constants for repeated literals.
The repeated
{ status: "error", error: ... }+ status/header blocks should be centralized to keep response formatting consistent.As per coding guidelines, "Use constants for repeated values" and "Use configuration objects instead of hardcoded values".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lib/sessions/chats/validateMarkChatReadRequest.ts` around lines 44 - 63, Extract a reusable error response helper and constants to avoid repeating NextResponse.json payloads and headers: create a helper function (e.g., buildErrorResponse(message: string, code: number)) or constant templates (e.g., ERROR_RESPONSE = (msg)=>({ status: "error", error: msg }) and use getCorsHeaders() for headers) and replace the three NextResponse.json calls in validateMarkChatReadRequest (the checks for session, session.account_id !== auth.accountId, and !chat || chat.session_id !== sessionId) to call buildErrorResponse/ERROR_RESPONSE with the appropriate message and HTTP status (404/403) while keeping getCorsHeaders() for headers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@lib/sessions/chats/validateMarkChatReadRequest.ts`:
- Around line 26-30: The validateMarkChatReadRequest function currently uses
sessionId and chatId without schema checks; add a Zod schema (e.g., z.object({
sessionId: z.string().min(1), chatId: z.string().min(1) }) or stricter if UUIDs
are expected) and run schema.parse or safeParse at the top of
validateMarkChatReadRequest to short-circuit invalid input with a NextResponse
400 before any Supabase/database calls, returning the parsed values to continue
processing; update the function signature/return path to use the validated
values from the Zod result and ensure error responses include a clear validation
message.
---
Nitpick comments:
In `@lib/sessions/chats/validateMarkChatReadRequest.ts`:
- Around line 44-63: Extract a reusable error response helper and constants to
avoid repeating NextResponse.json payloads and headers: create a helper function
(e.g., buildErrorResponse(message: string, code: number)) or constant templates
(e.g., ERROR_RESPONSE = (msg)=>({ status: "error", error: msg }) and use
getCorsHeaders() for headers) and replace the three NextResponse.json calls in
validateMarkChatReadRequest (the checks for session, session.account_id !==
auth.accountId, and !chat || chat.session_id !== sessionId) to call
buildErrorResponse/ERROR_RESPONSE with the appropriate message and HTTP status
(404/403) while keeping getCorsHeaders() for headers.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 4d72f826-6548-42bf-a048-d829debd5825
⛔ Files ignored due to path filters (2)
lib/sessions/chats/__tests__/markChatReadHandler.test.tsis excluded by!**/*.test.*,!**/__tests__/**and included bylib/**lib/sessions/chats/__tests__/validateMarkChatReadRequest.test.tsis excluded by!**/*.test.*,!**/__tests__/**and included bylib/**
📒 Files selected for processing (4)
app/api/sessions/[sessionId]/chats/[chatId]/read/route.tslib/sessions/chats/markChatReadHandler.tslib/sessions/chats/validateMarkChatReadRequest.tslib/supabase/chat_reads/upsertChatRead.ts
| export async function validateMarkChatReadRequest( | ||
| request: NextRequest, | ||
| sessionId: string, | ||
| chatId: string, | ||
| ): Promise<NextResponse | ValidatedMarkChatReadRequest> { |
There was a problem hiding this comment.
Add Zod validation for sessionId/chatId before database reads.
sessionId and chatId are consumed without schema validation. Add a validate function (Zod) and short-circuit with a 400 on invalid params before calling Supabase.
Suggested direction
+import { z } from "zod";
+
+const markChatReadParamsSchema = z.object({
+ sessionId: z.string().uuid(),
+ chatId: z.string().uuid(),
+});
...
export async function validateMarkChatReadRequest(
request: NextRequest,
sessionId: string,
chatId: string,
): Promise<NextResponse | ValidatedMarkChatReadRequest> {
+ const parsed = markChatReadParamsSchema.safeParse({ sessionId, chatId });
+ if (!parsed.success) {
+ return NextResponse.json(
+ { status: "error", error: "Invalid route parameters" },
+ { status: 400, headers: getCorsHeaders() },
+ );
+ }As per coding guidelines, "All API endpoints should use a validate function for input parsing using Zod for schema validation".
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export async function validateMarkChatReadRequest( | |
| request: NextRequest, | |
| sessionId: string, | |
| chatId: string, | |
| ): Promise<NextResponse | ValidatedMarkChatReadRequest> { | |
| import { z } from "zod"; | |
| const markChatReadParamsSchema = z.object({ | |
| sessionId: z.string().uuid(), | |
| chatId: z.string().uuid(), | |
| }); | |
| export async function validateMarkChatReadRequest( | |
| request: NextRequest, | |
| sessionId: string, | |
| chatId: string, | |
| ): Promise<NextResponse | ValidatedMarkChatReadRequest> { | |
| const parsed = markChatReadParamsSchema.safeParse({ sessionId, chatId }); | |
| if (!parsed.success) { | |
| return NextResponse.json( | |
| { status: "error", error: "Invalid route parameters" }, | |
| { status: 400, headers: getCorsHeaders() }, | |
| ); | |
| } | |
| // ... rest of function body continues |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lib/sessions/chats/validateMarkChatReadRequest.ts` around lines 26 - 30, The
validateMarkChatReadRequest function currently uses sessionId and chatId without
schema checks; add a Zod schema (e.g., z.object({ sessionId: z.string().min(1),
chatId: z.string().min(1) }) or stricter if UUIDs are expected) and run
schema.parse or safeParse at the top of validateMarkChatReadRequest to
short-circuit invalid input with a NextResponse 400 before any Supabase/database
calls, returning the parsed values to continue processing; update the function
signature/return path to use the validated values from the Zod result and ensure
error responses include a clear validation message.
Manual test results — preview ✅Tested against the preview deployment
DB verification (
|


Summary by cubic
Adds POST /api/sessions/:sessionId/chats/:chatId/read to mark a chat as read for the authenticated account and respond with { success: true }. Auth via Privy bearer token or
x-api-key, validates ownership, and upsertschat_reads.last_read_at.New Features
force-dynamic,force-no-store).upsertChatRead(accountId, chatId).Refactors
Written for commit 048f939. Summary will update on new commits.
Summary by CodeRabbit
Release Notes