Skip to content

Merge test → main#387

Merged
sweetmantech merged 2 commits intomainfrom
test
Apr 1, 2026
Merged

Merge test → main#387
sweetmantech merged 2 commits intomainfrom
test

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented Apr 1, 2026

Sync test to main

Summary by CodeRabbit

Release Notes

  • New Features

    • Added ability to copy messages between chats with optional clearing of existing messages in the destination
    • New API endpoint to retrieve chat messages with proper access validation
  • Backend Improvements

    • Enhanced message persistence operations for better performance and reliability
    • Improved bulk message handling and storage operations

* feat: migrate chat messages get endpoint

* refactor: move chat messages handler from memories to chats

* fix: harden chat access and memories error handling

* fix: move chat error handling to domain handler

* refactor: extract validateGetChatMessagesQuery per project conventions

Move auth + param parsing to standalone validate function.
Handler now calls validateGetChatMessagesQuery then selectMemories.

1670/1670 tests pass.

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

* fix: format validateGetChatMessagesQuery and handler

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

---------

Co-authored-by: Sweets Sweetman <sweetmantech@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 1, 2026

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

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Apr 1, 2026 3:17am

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 1, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e67dc4b0-833c-40c6-9227-3f5456a4cb25

📥 Commits

Reviewing files that changed from the base of the PR and between 08ba312 and da9a25f.

⛔ Files ignored due to path filters (6)
  • lib/chat/__tests__/saveChatCompletion.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chat/__tests__/setupConversation.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chats/__tests__/copyChatMessagesHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chats/__tests__/getChatMessagesHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chats/__tests__/validateCopyChatMessagesBody.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chats/__tests__/validateGetChatMessagesQuery.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (10)
  • app/api/chats/[id]/messages/copy/route.ts
  • app/api/chats/[id]/messages/route.ts
  • lib/chat/saveChatCompletion.ts
  • lib/chat/setupConversation.ts
  • lib/chats/copyChatMessagesHandler.ts
  • lib/chats/getChatMessagesHandler.ts
  • lib/chats/validateCopyChatMessagesBody.ts
  • lib/chats/validateGetChatMessagesQuery.ts
  • lib/supabase/memories/deleteMemories.ts
  • lib/supabase/memories/insertMemories.ts

📝 Walkthrough

Walkthrough

This PR introduces new API endpoints and handler functions to retrieve and copy chat messages between conversations. It includes validation utilities for request parameters and body payloads, updates memory persistence operations to support bulk inserts and deletions, and modifies existing chat completion functions to align with the new bulk-insert pattern.

Changes

Cohort / File(s) Summary
API Routes
app/api/chats/[id]/messages/route.ts, app/api/chats/[id]/messages/copy/route.ts
New Next.js route handlers exposing GET and POST endpoints with CORS preflight support; delegates to corresponding handler functions.
Message Handlers
lib/chats/getChatMessagesHandler.ts, lib/chats/copyChatMessagesHandler.ts
Implements async request handling with validation, memory retrieval/manipulation, and structured JSON responses with error management.
Request Validation
lib/chats/validateGetChatMessagesQuery.ts, lib/chats/validateCopyChatMessagesBody.ts
Zod-based validation schemas for query parameters and request body; enforces constraints (UUID format, source ≠ target chat IDs) and returns early-exit NextResponse on failure.
Supabase Memory Operations
lib/supabase/memories/insertMemories.ts, lib/supabase/memories/deleteMemories.ts
Refactors insertMemories to accept arrays instead of single objects and return counts; adds new deleteMemories utility for bulk deletion by room ID.
Chat Persistence Updates
lib/chat/saveChatCompletion.ts, lib/chat/setupConversation.ts
Adapts existing functions to call insertMemories with array syntax and adds explicit updated_at timestamp construction in response objects.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant GetRoute as GET /api/chats/[id]/messages
    participant GetHandler as getChatMessagesHandler
    participant Validate as validateGetChatMessagesQuery
    participant CacheCheck as validateChatAccess
    participant DB as Supabase (selectMemories)

    Client->>GetRoute: GET /api/chats/[id]/messages
    GetRoute->>GetHandler: POST(request, id)
    GetHandler->>Validate: validateGetChatMessagesQuery(request, id)
    Validate->>CacheCheck: validateChatAccess(request, id)
    CacheCheck-->>Validate: ValidatedChatAccess or NextResponse
    alt Validation Failed
        Validate-->>GetHandler: NextResponse (400/401)
    else Validation Passed
        GetHandler->>DB: selectMemories(room_id, ascending)
        DB-->>GetHandler: memories[] or null
        alt Query Failed
            GetHandler-->>Client: NextResponse (500, error)
        else Query Succeeded
            GetHandler-->>Client: NextResponse (200, { data: memories })
        end
    end
Loading
sequenceDiagram
    actor Client
    participant CopyRoute as POST /api/chats/[id]/messages/copy
    participant CopyHandler as copyChatMessagesHandler
    participant ValidateBody as validateCopyChatMessagesBody
    participant ValidateAccess as validateChatAccess
    participant DB as Supabase (selectMemories,<br/>deleteMemories,<br/>insertMemories)

    Client->>CopyRoute: POST /api/chats/[id]/messages/copy<br/>{ targetChatId, clearExisting }
    CopyRoute->>CopyHandler: copyChatMessagesHandler(request, sourceChatId)
    CopyHandler->>ValidateBody: validateCopyChatMessagesBody(request, sourceChatId)
    alt Body Invalid
        ValidateBody-->>CopyHandler: NextResponse (400)
        CopyHandler-->>Client: NextResponse (400, error)
    else Body Valid
        CopyHandler->>ValidateAccess: validateChatAccess (source & target)
        alt Access Denied
            ValidateAccess-->>CopyHandler: NextResponse (401)
            CopyHandler-->>Client: NextResponse (401, error)
        else Access Granted
            alt clearExisting=true
                CopyHandler->>DB: deleteMemories(targetRoomId)
            end
            CopyHandler->>DB: selectMemories(sourceRoomId)
            DB-->>CopyHandler: sourceMemories[] or null
            alt Source Query Failed
                CopyHandler-->>Client: NextResponse (500, error)
            else Source Query Succeeded
                CopyHandler->>DB: insertMemories([transformed records])
                DB-->>CopyHandler: insertCount
                CopyHandler-->>Client: NextResponse (200, { sourceChatId,<br/>targetChatId, copiedCount,<br/>clearedExisting })
            end
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

📋 Messages copied with care, ✨
Validation stands guard everywhere,
Bulk operations, arrays in flight,
Access controls burning bright,
Clean handlers, responses so right! 🚀

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test

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.

* feat: migrate chat messages copy endpoint

* fix: add handler-level error guard for chat copy

* refactor: move copy chat access checks into handler

* refactor: make copy chat endpoint append-only

* Revert "refactor: make copy chat endpoint append-only"

This reverts commit eb4f4a7.

* refactor: parallelize access checks, rename supabase helpers

Address review:
- Parallelize source/target validateChatAccess with Promise.all
- KISS: deleteMemoriesByRoomId → deleteMemories
- KISS: insertCopiedMemories → insertMemories

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

* fix: use insertMemoriesBatch to avoid overwriting existing insertMemories

An insertMemories.ts already exists on test (single insert). Renamed
batch version to insertMemoriesBatch to avoid collision.

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

* fix: rename to insertMemories, replace existing unused single-insert version

The old insertMemories (single insert) was unused. Replace with
batch version per KISS feedback. Fix formatting.

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

* fix: consolidate insertMemories to single array-based function

One insertMemories that takes an array — updated all callers
(saveChatCompletion, setupConversation, copyChatMessagesHandler)
and their tests. Uses TablesInsert type for proper Supabase compat.

Build passes. All tests pass.

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

---------

Co-authored-by: Sweets Sweetman <sweetmantech@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sweetmantech sweetmantech merged commit fd93602 into main Apr 1, 2026
3 of 6 checks passed
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.

2 participants