Skip to content

Test#168

Merged
sidneyswift merged 2 commits intomainfrom
test
Jan 27, 2026
Merged

Test#168
sidneyswift merged 2 commits intomainfrom
test

Conversation

@sidneyswift
Copy link
Contributor

@sidneyswift sidneyswift commented Jan 27, 2026

Summary by CodeRabbit

  • Performance Improvements

    • Parallelized tool fetching and task deletion operations for improved responsiveness.
    • Enabled package import optimization in build configuration for faster app loading.
  • Refactor

    • Updated room creation operations to support upsert functionality for more efficient data management.
  • Tests

    • Added comprehensive test coverage for room upsert and task deletion functionality.

✏️ Tip: You can customize this high-level summary in your review settings.

sidneyswift and others added 2 commits January 27, 2026 16:18
* 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]>
@vercel
Copy link
Contributor

vercel bot commented Jan 27, 2026

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

Project Deployment Review Updated (UTC)
recoup-api Ready Ready Preview Jan 27, 2026 10:31pm

@coderabbitai
Copy link

coderabbitai bot commented Jan 27, 2026

📝 Walkthrough

Walkthrough

The pull request migrates room creation from insertRoom to upsertRoom across multiple modules, parallelizes tool fetching in setupToolsForRequest, parallelizes deletion operations in deleteTask, and adds comprehensive test coverage for new functionality including upsert and delete operations. Additionally, Next.js configuration is updated to optimize package imports.

Changes

Cohort / File(s) Summary
Room Upsert Migration
lib/supabase/rooms/upsertRoom.ts, lib/supabase/rooms/__tests__/upsertRoom.test.ts
Replaces Supabase insert() operation with upsert(). New test file validates upsert behavior including conflict handling, null value management, and error propagation.
Chat Module Updates
lib/chat/createNewRoom.ts, lib/chat/handleChatCompletion.ts, lib/chat/__tests__/handleChatCompletion.test.ts
Updates imports and function calls from insertRoom to upsertRoom; adds id field to upsert payload in createNewRoom.ts. All test mocks and assertions updated accordingly.
Chat Integration Tests
lib/chat/__tests__/integration/chatEndToEnd.test.ts
Updates all mock paths and assertions to reference upsertRoom instead of insertRoom. No control flow changes.
Tool Fetching Parallelization
lib/chat/setupToolsForRequest.ts, lib/chat/__tests__/setupToolsForRequest.test.ts
Replaces sequential conditional fetching with Promise.all() to fetch MCP and Composio tools concurrently. New parallel execution test suite validates that both tools are fetched simultaneously when authToken is present.
Chats Module Updates
lib/chats/createChatHandler.ts, lib/chats/__tests__/createChatHandler.test.ts
Migrates from insertRoom to upsertRoom and introduces topic parameter derived from firstMessage. Test mocks and expectations updated to use upsertRoom.
Room Operations
lib/rooms/copyRoom.ts, lib/rooms/__tests__/copyRoom.test.ts
Replaces insertRoom with upsertRoom in copy logic. Mock variable renamed from mockInsertRoom to mockUpsertRoom; test assertions updated.
Task Deletion Parallelization
lib/tasks/deleteTask.ts, lib/tasks/__tests__/deleteTask.test.ts
Parallelizes schedule deletion and scheduled action deletion using Promise.all(). New comprehensive test suite covers normal cases, edge cases (null/undefined trigger_schedule_id), concurrent execution semantics, and error handling.
Build Configuration
next.config.ts
Adds experimental.optimizePackageImports configuration targeting date-fns, @ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google.

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[]
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • sweetmantech

🐰 Upserts bloom where inserts grew,
Tools fetch faster, side by side—
Deletions dance in parallel stride,
The warren speeds through refactor dew,

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The pull request title 'Test' is vague and generic, providing no meaningful information about the substantial changes in the changeset. Replace with a descriptive title that summarizes the main changes, such as 'Replace insertRoom with upsertRoom and parallelize tool fetching' or 'Refactor room operations to use upsert and optimize async operations'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

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 and usage tips.

@github-actions
Copy link

github-actions bot commented Jan 27, 2026

Braintrust eval report

Catalog Opportunity Analysis Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
Catalog_availability 10.2% (+6pp) 3 🟢 1 🔴
Llm_calls 0 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 43.26s (+1.74s) 1 🟢 4 🔴

Catalog Songs Count Evaluation (HEAD-1769553071)

Score Average Improvements Regressions
AnswerCorrectness 19.4% (0pp) 1 🟢 2 🔴
Factuality 66.7% (+33pp) 1 🟢 -
Llm_calls 4 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 16.87s (+3.12s) 1 🟢 2 🔴

First Week Album Sales Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
Factuality 0% (-60pp) - 1 🔴
Llm_calls 1 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 13.61s (-3.64s) 4 🟢 -

Memory & Storage Tools Evaluation (HEAD-1769553071)

Score Average Improvements Regressions
Tools_called 0% (+0pp) - -
Llm_calls 0 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 18.35s (+5.16s) - 1 🔴

Monthly Listeners Tracking Evaluation (HEAD-1769553071)

Score Average Improvements Regressions
AnswerSimilarity 78.4% (+2pp) 3 🟢 2 🔴
Llm_calls 2 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 12.61s (+0.44s) 2 🟢 3 🔴

Search Web Tool Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
AnswerCorrectness 26.8% (-3pp) 4 🟢 5 🔴
Llm_calls 3 (+0) - -
Tool_calls 0 (+0) - -
Errors 0.09 (+0.09) - 1 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 24.42s (-2.28s) 9 🟢 2 🔴

Social Scraping Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
Tools_called 0% (+0pp) - -
Llm_calls 0 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 24.31s (+2.74s) 3 🟢 3 🔴

Spotify Followers Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
AnswerCorrectness 20.3% (0pp) 1 🟢 2 🔴
Llm_calls 3 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 13.93s (-0.9s) 3 🟢 2 🔴

Spotify Tools Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
Tools_called 0% (+0pp) - -
Llm_calls 0 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 18.42s (-6.72s) - 1 🔴

TikTok Analytics Questions Evaluation (HEAD-1769553070)

Score Average Improvements Regressions
Question_answered 0% (-5pp) - 1 🔴
Llm_calls 0 (+0) - -
Tool_calls 0 (+0) - -
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 0tok (+0tok) - -
Prompt_cached_tokens 0tok (+0tok) - -
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 0tok (+0tok) - -
Completion_reasoning_tokens 0tok (+0tok) - -
Total_tokens 0tok (+0tok) - -
Duration 15.47s (-0.28s) 1 🟢 1 🔴

@sidneyswift sidneyswift merged commit ee7c647 into main Jan 27, 2026
5 of 6 checks passed
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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: Use null (not undefined) for artist_id in upsert payload

When artistId is undefined, artistId || undefined omits the field from the upsert payload. For existing rooms, this means artist_id won't be updated or cleared. Use artistId ?? null to match the pattern in handleChatCompletion and 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 when chatId is client-provided.

The switch from insertRoom to upsertRoom with client-controlled chatId creates a security issue: if a client provides an existing room ID, upsertRoom will silently update that room's account_id, artist_id, and topic without verifying ownership. No validation currently enforces that the provided chatId belongs to the requesting account. Either add ownership validation before the upsert, or remove client ability to specify chatId.

🤖 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 specifying onConflict for explicit upsert behavior.

The Supabase upsert method defaults to using the primary key for conflict resolution. While this likely works correctly with id as the primary key, explicitly specifying onConflict: '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").

Comment on lines +7 to +14
experimental: {
optimizePackageImports: [
'date-fns',
'@ai-sdk/anthropic',
'@ai-sdk/openai',
'@ai-sdk/google',
],
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 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-fns is included in the configuration but is not a dependency in package.json
  • The AI SDK packages (@ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google) are in package.json as 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.

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

Comments