Skip to content

Test - #81

Merged
sweetmantech merged 70 commits into
mainfrom
test
Dec 20, 2025
Merged

Test#81
sweetmantech merged 70 commits into
mainfrom
test

Conversation

@sweetmantech

@sweetmantechsweetmantech commented Dec 20, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

Release Notes

  • New Features

    • Added inbound email handling with automatic replies via integrated email service
    • Implemented conversation memory system to maintain chat history
    • Integrated knowledge base content into AI responses
    • Added image attachment support in chat conversations
    • Enabled conversation notifications
  • Bug Fixes

    • Improved error handling in account retrieval workflow
  • Chores

    • Added email service and AI model client library dependencies

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

…l-hello-world-inbound-email-webhook
Email - hello world inbound email webhook
…l-hard-coded-response
Email - hard-coded response
…l-lookup-account-id-in-supabase-with-selectaccountemails
Sweetmantech/myc 3781 email lookup account id in supabase with selectaccountemails
…l-recoup-chat-response
Sweetmantech/myc 3778 email recoup chat response
…l-pass-input-text-html-to-recoup-agent-call
Sweetmantech/myc 3783 email pass input text html to recoup agent call
…l-save-conversation-in-supabase-memories-table
simple logging
…email-new-emails-saved-to-memory_emails-table
Sweetmantech/myc 3792 api email new emails saved to memory emails table
…email-lookup-referenced-email-in
API - Email - lookup referenced email in content.headers.references t…
…email-agentgenerate-pass-in-full-message-history-for-the
Sweetmantech/myc 3794 api email agentgenerate pass in full message history for the
…email-prevent-duplicate-responses-for-the-same-prompt
API - email - prevent duplicate responses for the same prompt
@vercel

vercelBot commented Dec 20, 2025

Copy link
Copy Markdown
Contributor

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

ProjectDeploymentReviewUpdated (UTC)
recoup-apiReadyReadyPreviewDec 20, 2025 7:56pm

@coderabbitai

coderabbitaiBot commented Dec 20, 2025

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

Walkthrough

This PR introduces a comprehensive email ingestion pipeline with an inbound Resend webhook handler, validates email conversations as memories, generates intelligent responses via a general chat agent, and establishes foundational chat infrastructure for prompt construction, tool orchestration, and request validation.

Changes

Cohort / File(s)Summary
Email Inbound API Route & Handler
app/api/emails/inbound/route.ts, lib/emails/inbound/handleInboundEmail.ts
POST endpoint delegates inbound email requests to handleInboundEmail, which validates the Resend event and routes "email.received" to respondToInboundEmail for threaded reply generation and persistence.
Email Validation & Processing
lib/emails/inbound/validateNewEmailMemory.ts, lib/emails/inbound/respondToInboundEmail.ts, lib/emails/inbound/getEmailContent.ts, lib/emails/inbound/getEmailRoomId.ts, lib/emails/inbound/getEmailRoomMessages.ts, lib/emails/inbound/getFromWithName.ts
Validates inbound emails, resolves or creates conversation rooms, fetches email content and history, generates agent-based replies, and persists responses as conversation memories with duplicate detection.
Email Client & Schema Validation
lib/emails/client.ts, lib/emails/sendEmail.ts, lib/emails/validateInboundEmailEvent.ts, lib/emails/isTestEmail.ts
Wires Resend client initialization, email sending with error handling, inbound event schema validation with Zod, and test email filtering utilities.
General Chat Agent
lib/agents/generalAgent/getGeneralAgent.ts, lib/chat/setupToolsForRequest.ts, lib/chat/types.ts
Constructs a ToolLoopAgent with account context, artist knowledge, system prompts, image handling, and MCP-based tool orchestration; exports RoutingDecision type for agent metadata.
Chat Prompting & Utilities
lib/chat/const.ts, lib/prompts/getSystemPrompt.ts, lib/chat/buildSystemPromptWithImages.ts, lib/chat/generateChatTitle.ts, lib/chat/filterExcludedTools.ts
Defines comprehensive system prompt, augments prompts with user/artist context and images, generates conversation titles, and filters excluded tools from MCP toolset.
Chat Request Handling
lib/chat/validateChatRequest.ts, lib/ai/generateText.ts, lib/const.ts
Validates incoming chat requests with Zod (enforces exactly one of messages/prompt), wraps text generation with model fallback, and adds LIGHTWEIGHT_MODEL constant.
Message Processing Utilities
lib/messages/extractImageUrlsFromMessages.ts, lib/messages/filterMessageContentForMemories.ts, lib/messages/getMessages.ts, lib/messages/validateMessages.ts
Extracts image URLs from messages, filters text content for memory storage, converts strings to UIMessage format, and validates non-empty message arrays.
Supabase Database Layer
lib/supabase/account_emails/selectAccountEmails.ts, lib/supabase/accounts/getAccountWithDetails.ts, lib/supabase/rooms/insertRoom.ts, lib/supabase/memories/insertMemories.ts, lib/supabase/memories/selectMemories.ts, lib/supabase/memory_emails/insertMemoryEmail.ts, lib/supabase/memory_emails/selectMemoryEmails.ts
Extends account email/details queries, adds room creation, memory insertion/retrieval, and memory-email linking with foreign key relations.
Database Schema & Room Creation
types/database.types.ts, lib/chat/createNewRoom.ts
Adds memory_emails table with Row/Insert/Update shapes and foreign key to memories; creates new conversation rooms with title generation and notification dispatch.
Content & Knowledge Utilities
lib/files/getKnowledgeBaseText.ts, lib/uuid/generateUUID.ts, lib/telegram/sendNewConversationNotification.ts
Fetches and formats knowledge base text from URLs, generates UUIDs with fallback, and sends conversation notifications via Telegram (skipping test emails).
Bug Fixes & Dependency Updates
lib/coinbase/getAccount.ts, lib/mcp/tools/youtube/registerGetYouTubeRevenueTool.ts, lib/songs/queueRedisSongs.ts, lib/youtube/queryAnalyticsReports.ts, package.json
Removes debug console logs, improves account get-or-create error handling, adds @ai-sdk/mcp and resend dependencies.

Sequence Diagram

sequenceDiagram
actor Client as Email Sender
participant Resend as Resend Webhook
participant Handler as handleInboundEmail
participant Validator as validateNewEmailMemory
participant Agent as getGeneralAgent
participant DB as Supabase
participant Responder as respondToInboundEmail
participant EmailAPI as Resend Send API
Client->>Resend: Send email to `@mail.recoupable.com`
Resend->>Handler: POST /api/emails/inbound (event)
Handler->>Handler: Parse & validate event
alt Validation Failed
Handler-->>Resend: 400 JSON error
else Event Type = "email.received"
Handler->>Validator: validateNewEmailMemory(event)
Validator->>DB: Lookup account by recipient email
Validator->>Resend: getEmailContent(emailId)
Validator->>DB: selectMemoryEmails (check for existing)
alt Duplicate Detected
Validator-->>Handler: { response: 200 "Already processed" }
else New Email
Validator->>DB: insertRoom (if needed)
Validator->>DB: insertMemories (email as memory)
Validator->>DB: insertMemoryEmail (link email to memory)
Validator-->>Handler: { chatRequestBody, emailText }
Handler->>Responder: respondToInboundEmail(event)
Responder->>Responder: Build reply metadata
Responder->>Responder: Fetch room messages
Responder->>Agent: getGeneralAgent(chatRequestBody)
Agent->>DB: Fetch account details & artist info
Agent->>Agent: Construct system prompt + knowledge
Agent->>Agent: Setup MCP tools
Agent-->>Responder: ToolLoopAgent instance
Responder->>Responder: agent.generate() → reply text
Responder->>EmailAPI: sendEmailWithResend (threaded reply)
EmailAPI-->>Responder: { id, ... }
Responder->>DB: insertMemories (assistant response)
Responder-->>Handler: NextResponse
end
Handler-->>Resend: response payload
else Other Event Type
Handler-->>Resend: {} empty JSON
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Focus areas requiring extra attention:
    • lib/emails/inbound/validateNewEmailMemory.ts — complex multi-step validation with duplicate handling and room creation logic
    • lib/agents/generalAgent/getGeneralAgent.ts — orchestrates account resolution, knowledge loading, tool setup, and agent instantiation
    • lib/chat/validateChatRequest.ts — custom Zod superRefine enforcing mutually exclusive prompt/messages fields
    • Supabase integration points (lib/supabase/memory_emails/*, lib/supabase/rooms/insertRoom.ts) — verify foreign key relationships and error handling
    • Email-memory linking flow across validateNewEmailMemoryrespondToInboundEmail → memory persistence

Possibly related PRs

Poem

🐰 A rabbit hops through emails fast,
Threading replies to the past,
With agents wise and prompts so grand,
Memories stored in memory's land—
From Resend's hooks to database deep,
Conversations now we'll always keep! 📧✨

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35ddfaf and e6f7428.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (44)
  • app/api/emails/inbound/route.ts (1 hunks)
  • lib/agents/generalAgent/getGeneralAgent.ts (1 hunks)
  • lib/ai/generateText.ts (1 hunks)
  • lib/chat/buildSystemPromptWithImages.ts (1 hunks)
  • lib/chat/const.ts (1 hunks)
  • lib/chat/createNewRoom.ts (1 hunks)
  • lib/chat/filterExcludedTools.ts (1 hunks)
  • lib/chat/generateChatTitle.ts (1 hunks)
  • lib/chat/setupToolsForRequest.ts (1 hunks)
  • lib/chat/types.ts (1 hunks)
  • lib/chat/validateChatRequest.ts (1 hunks)
  • lib/coinbase/getAccount.ts (0 hunks)
  • lib/const.ts (1 hunks)
  • lib/emails/client.ts (1 hunks)
  • lib/emails/inbound/getEmailContent.ts (1 hunks)
  • lib/emails/inbound/getEmailRoomId.ts (1 hunks)
  • lib/emails/inbound/getEmailRoomMessages.ts (1 hunks)
  • lib/emails/inbound/getFromWithName.ts (1 hunks)
  • lib/emails/inbound/handleInboundEmail.ts (1 hunks)
  • lib/emails/inbound/respondToInboundEmail.ts (1 hunks)
  • lib/emails/inbound/validateNewEmailMemory.ts (1 hunks)
  • lib/emails/isTestEmail.ts (1 hunks)
  • lib/emails/sendEmail.ts (1 hunks)
  • lib/emails/validateInboundEmailEvent.ts (1 hunks)
  • lib/files/getKnowledgeBaseText.ts (1 hunks)
  • lib/mcp/tools/youtube/registerGetYouTubeRevenueTool.ts (0 hunks)
  • lib/messages/extractImageUrlsFromMessages.ts (1 hunks)
  • lib/messages/filterMessageContentForMemories.ts (1 hunks)
  • lib/messages/getMessages.ts (1 hunks)
  • lib/messages/validateMessages.ts (1 hunks)
  • lib/prompts/getSystemPrompt.ts (1 hunks)
  • lib/songs/queueRedisSongs.ts (0 hunks)
  • lib/supabase/account_emails/selectAccountEmails.ts (1 hunks)
  • lib/supabase/accounts/getAccountWithDetails.ts (2 hunks)
  • lib/supabase/memories/insertMemories.ts (1 hunks)
  • lib/supabase/memories/selectMemories.ts (1 hunks)
  • lib/supabase/memory_emails/insertMemoryEmail.ts (1 hunks)
  • lib/supabase/memory_emails/selectMemoryEmails.ts (1 hunks)
  • lib/supabase/rooms/insertRoom.ts (1 hunks)
  • lib/telegram/sendNewConversationNotification.ts (1 hunks)
  • lib/uuid/generateUUID.ts (1 hunks)
  • lib/youtube/queryAnalyticsReports.ts (0 hunks)
  • package.json (2 hunks)
  • types/database.types.ts (1 hunks)

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.

@sweetmantech
sweetmantech merged commit 269e578 into mainDec 20, 2025
1 of 2 checks passed
Sign up for freeto 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

@sweetmantech