Conversation
* fix: handle duplicate room creation race condition Catch 23505 unique constraint error when frontend creates room before backend's selectRoom sees it. Skip notification if room already exists. * fix: keep Promise.all, just wrap in try/catch Simpler fix - keep parallel execution, only catch the 23505 error. * fix: handle duplicate room in createNewRoom.ts This is the actual fix - createNewRoom is called during setupConversation at request START, which is where the 500 error occurs. * fix: revert try/catch bandaid - no longer needed Frontend no longer creates rooms, so no race condition. Backend is single source of truth for room creation. * fix: use upsert instead of insert for room creation - Changed insertRoom to use upsert with ignoreDuplicates: true - Reverted try/catch in createNewRoom.ts and handleChatCompletion.ts - Cleaner solution: duplicates are silently ignored at the DB level * fix: use upsert instead of insert for rooms One-line fix: change insert to upsert in insertRoom.ts. Removes try/catch workarounds since upsert handles duplicates. * refactor: rename insertRoom to upsertRoom to match method Renames the function and file from insertRoom to upsertRoom to align with the actual Supabase method being called (.upsert()). Co-Authored-By: Claude Opus 4.5 <[email protected]> * test: add unit tests for upsertRoom function Adds comprehensive unit tests covering: - Basic upsert operation - Null artist_id handling - Null topic handling - Error handling on upsert failure - Upsert behavior (update on conflict) Co-Authored-By: Claude Opus 4.5 <[email protected]> --------- Co-authored-by: Claude Opus 4.5 <[email protected]>
* perf: optimize bundle and parallelize sequential awaits - Add optimizePackageImports for date-fns, @AI-SDK packages - Parallelize MCP tools and Composio tools fetching with Promise.all - Parallelize Trigger.dev schedule deletion and DB deletion in deleteTask These optimizations improve API response times by parallelizing independent operations. Co-Authored-By: Claude Opus 4.5 <[email protected]> * test: add unit tests for parallel execution optimizations - Add comprehensive tests for deleteTask function including: - Basic functionality (fetch, delete from DB, delete from Trigger.dev) - Error handling (task not found, propagated errors) - Handling tasks without trigger_schedule_id - Parallel execution verification - Add parallel execution tests for setupToolsForRequest: - Verify MCP and Composio tools are fetched concurrently - Verify both operations are called when authToken is provided Co-Authored-By: Claude Opus 4.5 <[email protected]> --------- Co-authored-by: Claude Opus 4.5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughThe pull request migrates room creation from Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client
participant setupToolsForRequest
participant getMcpTools
participant getComposioTools
Client->>setupToolsForRequest: setupToolsForRequest(authToken)
rect rgba(100, 150, 255, 0.5)
par Parallel Execution
setupToolsForRequest->>getMcpTools: getMcpTools(authToken)
setupToolsForRequest->>getComposioTools: getComposioTools()
and
getMcpTools-->>setupToolsForRequest: mcpTools[]
and
getComposioTools-->>setupToolsForRequest: composioTools[]
end
end
setupToolsForRequest->>setupToolsForRequest: aggregate tools
setupToolsForRequest-->>Client: combined tools[]
sequenceDiagram
autonumber
participant Client
participant deleteTask
participant selectScheduledActions
participant deleteSchedule
participant deleteScheduledAction
Client->>deleteTask: deleteTask(id)
deleteTask->>selectScheduledActions: fetch scheduled action by id
selectScheduledActions-->>deleteTask: scheduledAction
rect rgba(100, 150, 255, 0.5)
par Parallel Deletion
alt has trigger_schedule_id
deleteTask->>deleteSchedule: deleteSchedule(trigger_schedule_id)
deleteSchedule-->>deleteTask: resolved
else no trigger_schedule_id
deleteTask->>deleteTask: resolve immediately
end
and
deleteTask->>deleteScheduledAction: deleteScheduledAction(id)
deleteScheduledAction-->>deleteTask: resolved
end
end
deleteTask-->>Client: success
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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 |
Braintrust eval reportCatalog Opportunity Analysis Evaluation (HEAD-1769553070)
Catalog Songs Count Evaluation (HEAD-1769553071)
First Week Album Sales Evaluation (HEAD-1769553070)
Memory & Storage Tools Evaluation (HEAD-1769553071)
Monthly Listeners Tracking Evaluation (HEAD-1769553071)
Search Web Tool Evaluation (HEAD-1769553070)
Social Scraping Evaluation (HEAD-1769553070)
Spotify Followers Evaluation (HEAD-1769553070)
Spotify Tools Evaluation (HEAD-1769553070)
TikTok Analytics Questions Evaluation (HEAD-1769553070)
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
lib/chat/createNewRoom.ts (1)
39-45: Usenull(notundefined) forartist_idin upsert payloadWhen
artistIdis undefined,artistId || undefinedomits the field from the upsert payload. For existing rooms, this meansartist_idwon't be updated or cleared. UseartistId ?? nullto match the pattern inhandleChatCompletionand ensure the field is always included in the upsert payload.✅ Suggested fix
- artist_id: artistId || undefined, + artist_id: artistId ?? null,lib/chats/createChatHandler.ts (1)
63-68: Validate room ownership before upserting whenchatIdis client-provided.The switch from
insertRoomtoupsertRoomwith client-controlledchatIdcreates a security issue: if a client provides an existing room ID,upsertRoomwill silently update that room'saccount_id,artist_id, andtopicwithout verifying ownership. No validation currently enforces that the providedchatIdbelongs to the requesting account. Either add ownership validation before the upsert, or remove client ability to specifychatId.
🤖 Fix all issues with AI agents
In `@next.config.ts`:
- Around line 7-14: The optimizePackageImports array currently lists packages
that aren't actually used: remove 'date-fns' from the optimizePackageImports
configuration (the optimizePackageImports symbol) to avoid optimizing a
non-dependency, and audit the listed AI SDK entries '@ai-sdk/anthropic',
'@ai-sdk/openai', and '@ai-sdk/google' to confirm whether they are directly
imported anywhere or only present for types/indirect use; if they are not
directly imported, either remove them from optimizePackageImports or remove the
unused dependencies from package.json accordingly so the configuration only
contains packages that are truly used.
🧹 Nitpick comments (3)
lib/tasks/__tests__/deleteTask.test.ts (1)
165-172: Misleading test description.The test description says "both operations are called even if they would fail," but neither mock is configured to fail. The test simply verifies both operations are invoked. Consider renaming for clarity.
📝 Suggested rename
- it("both operations are called even if they would fail", async () => { - // This test verifies that both operations are initiated via Promise.all - // by checking both mocks are called, not their order + it("calls both deleteSchedule and deleteScheduledAction", async () => { await deleteTask({ id: mockTaskId }); expect(mockDeleteSchedule).toHaveBeenCalledTimes(1); expect(mockDeleteScheduledAction).toHaveBeenCalledTimes(1); });lib/supabase/rooms/upsertRoom.ts (1)
8-9: Consider specifyingonConflictfor explicit upsert behavior.The Supabase
upsertmethod defaults to using the primary key for conflict resolution. While this likely works correctly withidas the primary key, explicitly specifyingonConflict: 'id'would make the intent clearer and protect against unexpected behavior if the table schema changes.♻️ Suggested improvement
export const upsertRoom = async (params: CreateRoomParams): Promise<Room> => { - const { data, error } = await supabase.from("rooms").upsert(params).select("*").single(); + const { data, error } = await supabase.from("rooms").upsert(params, { onConflict: 'id' }).select("*").single(); if (error) throw error; return data; };lib/supabase/rooms/__tests__/upsertRoom.test.ts (1)
118-142: Test name slightly overpromises actual coverage.The test "updates existing room on conflict (upsert behavior)" only verifies that the upsert call is made with the expected payload and returns the mocked response. It doesn't actually demonstrate conflict resolution behavior since there's no setup showing an existing row.
This is acceptable for a unit test with mocked dependencies, but consider renaming to better reflect what's being tested (e.g., "calls upsert with updated fields").
| experimental: { | ||
| optimizePackageImports: [ | ||
| 'date-fns', | ||
| '@ai-sdk/anthropic', | ||
| '@ai-sdk/openai', | ||
| '@ai-sdk/google', | ||
| ], | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify that these packages are used in the codebase
echo "Checking usage of optimized packages..."
for pkg in "date-fns" "@ai-sdk/anthropic" "@ai-sdk/openai" "@ai-sdk/google"; do
echo "=== $pkg ==="
rg "from ['\"]$pkg" --type ts --type tsx 2>/dev/null | head -10
if [ $? -ne 0 ]; then
echo "No imports found for $pkg"
fi
done
echo ""
echo "Checking package.json for dependencies..."
cat package.json 2>/dev/null | grep -A 50 '"dependencies"' | grep -E "(date-fns|@ai-sdk)" || echo "Could not verify dependencies"Repository: Recoupable-com/Recoup-API
Length of output: 405
Remove unused package from optimizePackageImports configuration.
The optimizePackageImports setting lists packages that should be tree-shaken, but verification shows issues:
date-fnsis included in the configuration but is not a dependency inpackage.json- The AI SDK packages (
@ai-sdk/anthropic,@ai-sdk/openai,@ai-sdk/google) are inpackage.jsonas dependencies but have no direct imports found in the codebase
Optimization settings should only include packages that are actually used. Remove date-fns from the configuration. If the AI SDK packages are unused (e.g., used indirectly or only for type definitions), evaluate whether they should remain or be removed entirely.
🤖 Prompt for AI Agents
In `@next.config.ts` around lines 7 - 14, The optimizePackageImports array
currently lists packages that aren't actually used: remove 'date-fns' from the
optimizePackageImports configuration (the optimizePackageImports symbol) to
avoid optimizing a non-dependency, and audit the listed AI SDK entries
'@ai-sdk/anthropic', '@ai-sdk/openai', and '@ai-sdk/google' to confirm whether
they are directly imported anywhere or only present for types/indirect use; if
they are not directly imported, either remove them from optimizePackageImports
or remove the unused dependencies from package.json accordingly so the
configuration only contains packages that are truly used.
Summary by CodeRabbit
Performance Improvements
Refactor
Tests
✏️ Tip: You can customize this high-level summary in your review settings.