Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds filtering to skip system/DRAFT label removals, refines thread-status prompt/rules and AI rule-matching to merge AI reasons, adds related tests (including duplicated determine-thread-status tests), and bumps version to v2.17.15. Changes
Sequence Diagram(s)Label removal flow (early filter + skip when only system/DRAFT labels removed): sequenceDiagram
participant Gmail as Gmail webhook
participant Handler as process-label-removed-event
participant Provider as mailProvider.getMessage
participant DB as prisma.upsert
Gmail->>Handler: labelRemovedEvent(allRemovedLabelIds, messageId, threadId)
Handler->>Handler: filter out system labels -> removedLabelIds
alt removedLabelIds is empty
Handler-->>Gmail: log trace "no non-system labels" (labelCount=0)
Note over Handler: return early (skip processing)
else removedLabelIds present
Handler->>Provider: getMessage(messageId)
alt message not found
Handler-->>Handler: log warning (deleted/trashed) with allRemovedLabelIds & nonSystemLabels
Handler-->>Gmail: return
else message found
Handler->>DB: upsert coldEmail / continue processing (use removedLabelIds)
Handler-->>Gmail: finished
end
end
AI rule matching (merge AI-selected reasons into existing matches): sequenceDiagram
participant Matcher as findMatchingRulesWithReasons
participant AI as AI evaluator
participant Rules as existingMatches
Matcher->>AI: request rule suggestions (includes calendar cases)
AI-->>Matcher: aiRuleIds + aiReasons
Matcher->>Rules: map existingMatches
alt aiRuleIds overlap existingMatches
Matcher->>Matcher: append ConditionType.AI reason to overlapping matches
else
Matcher->>Matcher: add AI-only matches (with aiReasons)
end
Matcher-->>Caller: combined matches with merged reasons
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
💤 Files with no reviewable changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
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 |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
apps/web/__tests__/determine-thread-status.test.ts (1)
581-612: Clarify test comment terminology.The test name and comment (Line 606) use "auto-converts" which suggests there's explicit code logic that converts FYI to ACTIONED. However, the actual mechanism is that the AI follows the prompt guidance: "FYI is ONLY for emails the user RECEIVED. If the user SENT the last email, it cannot be FYI" (Line 54 in determine-thread-status.ts).
Consider updating the comment to reflect that this is prompt-guided behavior rather than code-level auto-conversion:
- // Even if AI determines FYI, it should auto-convert to ACTIONED - // because user sent the last email + // AI should determine ACTIONED (not FYI) because user sent the last email + // Per prompt guidance: "FYI is ONLY for emails the user RECEIVED"
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
apps/web/__tests__/determine-thread-status.test.ts(1 hunks)apps/web/app/api/google/webhook/process-label-removed-event.test.ts(1 hunks)apps/web/app/api/google/webhook/process-label-removed-event.ts(1 hunks)apps/web/utils/ai/reply/determine-thread-status.ts(1 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (18)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use@/for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX
Files:
apps/web/utils/ai/reply/determine-thread-status.tsapps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/app/api/google/webhook/process-label-removed-event.tsapps/web/__tests__/determine-thread-status.test.ts
!{.cursor/rules/*.mdc}
📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)
Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location
Files:
apps/web/utils/ai/reply/determine-thread-status.tsapps/web/app/api/google/webhook/process-label-removed-event.test.tsversion.txtapps/web/app/api/google/webhook/process-label-removed-event.tsapps/web/__tests__/determine-thread-status.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)
**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod
Files:
apps/web/utils/ai/reply/determine-thread-status.tsapps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/app/api/google/webhook/process-label-removed-event.tsapps/web/__tests__/determine-thread-status.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport Prisma in the project using
import prisma from "@/utils/prisma";
**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.
Files:
apps/web/utils/ai/reply/determine-thread-status.tsapps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/app/api/google/webhook/process-label-removed-event.tsapps/web/__tests__/determine-thread-status.test.ts
apps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logic
Files:
apps/web/utils/ai/reply/determine-thread-status.ts
apps/web/utils/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size
Files:
apps/web/utils/ai/reply/determine-thread-status.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...
Files:
apps/web/utils/ai/reply/determine-thread-status.tsapps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/app/api/google/webhook/process-label-removed-event.tsapps/web/__tests__/determine-thread-status.test.ts
!pages/_document.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.
Files:
apps/web/utils/ai/reply/determine-thread-status.tsapps/web/app/api/google/webhook/process-label-removed-event.test.tsversion.txtapps/web/app/api/google/webhook/process-label-removed-event.tsapps/web/__tests__/determine-thread-status.test.ts
apps/web/utils/ai/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
apps/web/utils/ai/**/*.{ts,tsx}: Place main LLM feature implementations under apps/web/utils/ai/
LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)
Keep system prompts and user prompts separate
System prompt should define the LLM's role and task specifications
User prompt should contain the actual data and context
Always define a Zod schema for response validation
Make Zod schemas as specific as possible to guide LLM output
Use descriptive scoped loggers for each feature
Log inputs and outputs with appropriate log levels and include relevant context
Implement early returns for invalid inputs
Use proper error types and logging for failures
Implement fallbacks for AI failures
Add retry logic for transient failures using withRetry
Use XML-like tags to structure data in prompts
Remove excessive whitespace and truncate long inputs in prompts
Format prompt data consistently across similar functions
Use TypeScript types for all parameters and return values in LLM features
Define clear interfaces for complex input/output structures in LLM features
Files:
apps/web/utils/ai/reply/determine-thread-status.ts
apps/web/utils/{ai,llms}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments
Files:
apps/web/utils/ai/reply/determine-thread-status.ts
apps/web/app/**
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
NextJS app router structure with (app) directory
Files:
apps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/app/api/google/webhook/process-label-removed-event.ts
**/*.test.{ts,js}
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
Include security tests in your test suites to verify authentication, authorization, and error handling.
Files:
apps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/__tests__/determine-thread-status.test.ts
apps/web/app/api/**/*.{ts,js}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.
Files:
apps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/app/api/google/webhook/process-label-removed-event.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.
Files:
apps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/__tests__/determine-thread-status.test.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock theserver-onlymodule withvi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it withvi.mock("@/utils/prisma")and use the mock from@/utils/__mocks__/prisma
Use provided helpers for mocks: import{ getEmail, getEmailAccount, getRule }from@/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g.,vi.clearAllMocks()inbeforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger
Files:
apps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/__tests__/determine-thread-status.test.ts
apps/web/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
Place LLM-specific tests under apps/web/tests/
Files:
apps/web/__tests__/determine-thread-status.test.ts
**/__tests__/**
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
Place AI tests in the
__tests__directory and exclude them from the default test run (they use a real LLM)
Files:
apps/web/__tests__/determine-thread-status.test.ts
apps/web/__tests__/**/*.test.ts
📄 CodeRabbit inference engine (.cursor/rules/llm-test.mdc)
apps/web/__tests__/**/*.test.ts: Place all LLM-related tests under apps/web/tests/
Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"
Mock the Next.js server runtime marker by adding vi.mock("server-only", () => ({})) in LLM tests
Gate LLM tests behind RUN_AI_TESTS using describe.runIf(process.env.RUN_AI_TESTS === "true")
Call vi.clearAllMocks() in a beforeEach for LLM tests
Set a TIMEOUT of 15_000ms for LLM-related tests and pass it to long-running tests/describe blocks
Create helper functions for common test data (e.g., getUser, getTestData) to reduce duplication
Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats
Use console.debug to log generated LLM content for inspection (e.g., console.debug("Generated content:\n", result.content))
Do not mock the actual LLM call in these tests; exercise real LLM integrations
Test both AI and non-AI paths, including cases where no AI processing is required
Prefer existing helpers from @/tests/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers
Files:
apps/web/__tests__/determine-thread-status.test.ts
🧠 Learnings (9)
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.{ts,tsx} : Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments
Applied to files:
apps/web/utils/ai/reply/determine-thread-status.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : System prompt should define the LLM's role and task specifications
Applied to files:
apps/web/utils/ai/reply/determine-thread-status.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)
Applied to files:
apps/web/utils/ai/reply/determine-thread-status.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI paths, including cases where no AI processing is required
Applied to files:
apps/web/app/api/google/webhook/process-label-removed-event.test.tsapps/web/__tests__/determine-thread-status.test.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Implement early returns for invalid inputs
Applied to files:
apps/web/app/api/google/webhook/process-label-removed-event.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Gate LLM tests behind RUN_AI_TESTS using describe.runIf(process.env.RUN_AI_TESTS === "true")
Applied to files:
apps/web/__tests__/determine-thread-status.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats
Applied to files:
apps/web/__tests__/determine-thread-status.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer existing helpers from @/__tests__/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers
Applied to files:
apps/web/__tests__/determine-thread-status.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Run AI tests using: pnpm test-ai <feature>
Applied to files:
apps/web/__tests__/determine-thread-status.test.ts
🧬 Code graph analysis (3)
apps/web/app/api/google/webhook/process-label-removed-event.test.ts (1)
apps/web/app/api/google/webhook/process-label-removed-event.ts (1)
handleLabelRemovedEvent(27-149)
apps/web/app/api/google/webhook/process-label-removed-event.ts (1)
apps/web/utils/gmail/label.ts (1)
GmailLabel(20-34)
apps/web/__tests__/determine-thread-status.test.ts (2)
apps/web/__tests__/helpers.ts (2)
getEmailAccount(6-24)getEmail(45-64)apps/web/utils/ai/reply/determine-thread-status.ts (1)
aiDetermineThreadStatus(10-119)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Jit Security
🔇 Additional comments (4)
apps/web/app/api/google/webhook/process-label-removed-event.test.ts (1)
176-187: LGTM! Test correctly validates DRAFT label skip behavior.The test properly verifies that when a DRAFT label is removed (which happens when a draft is sent), the handler returns early without attempting to fetch the message or update the database. This prevents 404 errors when trying to access the draft message ID that no longer exists.
apps/web/app/api/google/webhook/process-label-removed-event.ts (1)
52-60: LGTM! Guard clause correctly prevents processing draft label removals.The early return is appropriately placed after validation but before the
getMessagecall that would fail with a 404 error. The comment clearly explains that when a draft is sent, Gmail removes the DRAFT label and the draft message ID no longer exists (it becomes a new sent message with a new ID).apps/web/utils/ai/reply/determine-thread-status.ts (1)
36-74: LGTM! Comprehensive prompt refinements improve status determination accuracy.The updated criteria provide clearer guidance for:
- Tracking user-specific commitments in multi-person threads
- Distinguishing between user's promises (TO_REPLY) vs others' promises (AWAITING_REPLY)
- Request fulfillment scenarios (no longer awaiting when request is fulfilled)
- Critical distinction that FYI is only for received emails (not sent)
- User-sent informational content should be ACTIONED (not AWAITING_REPLY)
The expanded critical rules section addresses edge cases systematically and provides specific guidance the AI can reference.
apps/web/__tests__/determine-thread-status.test.ts (1)
552-579: LGTM! Test correctly validates ACTIONED status for user-sent informational emails.The test properly verifies that when the user sends informational content (recommendations, links, advice) without asking questions or expecting specific actions, the status should be ACTIONED (not AWAITING_REPLY). This aligns with the updated prompt guidance on Line 61-62 and Rule 7 (Lines 72-73) in determine-thread-status.ts.
Summary by CodeRabbit
Bug Fixes
Improvements
Tests
Version