Skip to content

Comments

fix: Fix Digest scheduling logic + update tests#584

Merged
elie222 merged 5 commits intoelie222:mainfrom
edulelis:digest-emails-v5
Jul 21, 2025
Merged

fix: Fix Digest scheduling logic + update tests#584
elie222 merged 5 commits intoelie222:mainfrom
edulelis:digest-emails-v5

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Jul 21, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved scheduling logic to ensure the next occurrence is correctly calculated for interval and weekly patterns, including edge cases where the scheduled time matches the current time and when searching for the next occurrence across two weeks.
  • Tests

    • Expanded test coverage for monthly and long-interval scheduling scenarios, including leap years and year boundaries.
    • Enhanced test descriptions and clarified time references for better understanding.
  • API Enhancements

    • Added error handling and request signature verification middleware to the AI digest API endpoint for improved security and reliability.
    • Removed a redundant API route adapter to streamline the digest API.
  • Chores

    • Removed custom headers from the digest enqueue function to simplify request options.

@vercel
Copy link

vercel bot commented Jul 21, 2025

@edulelis is attempting to deploy a commit to the Inbox Zero Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes update scheduling logic to exclude the current date if the slot time matches exactly and extend the weekly search window to 14 days. The test suite was enhanced to be timezone-independent with UTC dates and expanded with comprehensive monthly and long-interval scheduling tests. The AI digest API route was refactored to add middleware for error handling and signature verification, and a redundant simple route wrapper was removed. The digest enqueue function was adjusted to omit custom cron secret headers.

Changes

File(s) Change Summary
apps/web/utils/schedule.ts Changed intervalDays pattern condition to slotDate > fromDate; extended weekly pattern search window from 7 to 14 days.
apps/web/utils/schedule.test.ts Made tests timezone-independent (UTC), clarified comments, renamed test cases, and added extensive monthly and long-interval schedule tests.
apps/web/app/api/ai/digest/route.ts Refactored POST handler to wrap with withError and verifySignatureAppRouter middleware; relocated upsertDigest function unchanged.
apps/web/app/api/ai/digest/simple/route.ts Removed file that wrapped the digest POST handler with error middleware, now redundant due to direct middleware in main route.
apps/web/utils/digest/index.ts Removed custom cron secret headers from publishToQstashQueue call in enqueueDigestItem.

Estimated code review effort

4 (60–120 minutes)

Possibly related PRs

Poem

🐇 Through time’s maze, I bound and leap,

UTC clocks no secrets keep.
Monthly dates and leaps we track,
No missed hops, no turning back.
Digest routes now safe and sound,
Middleware guards all around.
In code’s garden, peace I sow—
A rabbit’s work, swift and thorough! 🥕⏳


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between acc239d and e3e6787.

📒 Files selected for processing (1)
  • apps/web/app/api/ai/digest/route.ts (2 hunks)
✨ 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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

🔭 Outside diff range comments (1)
apps/web/utils/schedule.test.ts (1)

314-333: Critical: Test logic is inconsistent with the scheduling changes.

The test description says "should find next occurrence on same day even if time has passed" but the logic change in schedule.ts (line 166) now uses > instead of >=, which means it will NOT schedule on the same day if the time has passed - it will find the next occurrence.

The test expectation (line 330) expects date 15 (same day) but the pipeline failure shows it gets 22 (next week), which is actually the correct behavior with the new logic.

The test should be updated to match the new logic:

-    it("should find next occurrence on same day even if time has passed", () => {
+    it("should find next occurrence when current time has passed", () => {
       const fromDate = new Date("2024-01-15T12:00:00Z"); // Monday 12 PM
       const timeOfDay = createCanonicalTimeOfDay(10, 0);

       const result = calculateNextScheduleDate(
         {
           intervalDays: null,
           daysOfWeek: DAYS.MONDAY,
           timeOfDay,
           occurrences: null,
         },
         fromDate,
       );

-      // Current time is 12 PM UTC, but 10 AM scheduled time has already passed today, so schedule for same Monday at 10:00 AM
+      // Current time is 12 PM UTC, and 10 AM scheduled time has already passed today, so schedule for next Monday at 10:00 AM
       expect(result).not.toBeNull();
-      expect(result!.getDate()).toBe(15); // Same Monday
+      expect(result!.getDate()).toBe(22); // Next Monday
       expect(result!.getHours()).toBe(10);
       expect(result!.getMinutes()).toBe(0);
     });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1fc3ecf and d4161d1.

📒 Files selected for processing (2)
  • apps/web/utils/schedule.test.ts (15 hunks)
  • apps/web/utils/schedule.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • apps/web/CLAUDE.md
!{.cursor/rules/*.mdc}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/cursor-rules.mdc
**/*.ts

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/form-handling.mdc
**/*.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/logging.mdc
  • .cursor/rules/prisma.mdc
  • .cursor/rules/ultracite.mdc
apps/web/utils/**

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/project-structure.mdc
apps/web/utils/**/*.ts

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/project-structure.mdc
**/*.{js,jsx,ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/ultracite.mdc
!pages/_document.{js,jsx,ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/ultracite.mdc
**/*.test.{ts,js}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/security.mdc
**/*.test.{ts,js,tsx,jsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/testing.mdc
**/*.{test,spec}.{js,jsx,ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/ultracite.mdc
🧠 Learnings (2)
apps/web/utils/schedule.ts (5)

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Make Zod schemas as specific as possible to guide the LLM output.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Include relevant context in log messages for LLM-related code.

apps/web/utils/schedule.test.ts (13)

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.554Z
Learning: Applies to apps/web/tests/**/*.test.ts : Test both AI and non-AI paths in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.554Z
Learning: Applies to apps/web/tests/**/*.test.ts : Include standard test cases: happy path, error handling, edge cases (empty input, null values), different user configurations, and various input formats in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.554Z
Learning: Applies to apps/web/tests/**/*.test.ts : Use descriptive console.debug statements for generated content in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.554Z
Learning: Applies to apps/web/tests/**/*.test.ts : Set appropriate timeouts for LLM calls in tests (e.g., 15,000ms for long-running operations)

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.287Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Make sure the assertion function, like expect, is placed inside an it() function call.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.554Z
Learning: Applies to apps/web/tests/**/*.test.ts : Always create helper functions for common test data in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Document complex AI logic with clear comments in LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.287Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't nest describe() blocks too deeply in test files.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.243Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.287Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't use disabled tests.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/mocks/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.287Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't use export or module.exports in test files.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.287Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't use export or module.exports in test files.

🪛 GitHub Check: test
apps/web/utils/schedule.test.ts

[failure] 330-330: utils/schedule.test.ts > calculateNextScheduleDate > weekly pattern with specific days > should find next occurrence on same day even if time has passed
AssertionError: expected 22 to be 15 // Object.is equality

  • Expected
  • Received
  • 15
  • 22

❯ utils/schedule.test.ts:330:33


[failure] 581-581: utils/schedule.test.ts > calculateNextScheduleDate > real-world scenarios > should handle monthly schedule on the 15th
AssertionError: expected 1 to be +0 // Object.is equality

  • Expected
  • Received
  • 0
  • 1

❯ utils/schedule.test.ts:581:34

🪛 GitHub Actions: Run Tests
apps/web/utils/schedule.test.ts

[error] 330-330: Test failure in calculateNextScheduleDate > weekly pattern with specific days > should find next occurrence on same day even if time has passed: AssertionError - expected 22 to be 15 (Object.is equality).


[error] 581-581: Test failure in calculateNextScheduleDate > real-world scenarios > should handle monthly schedule on the 15th: AssertionError - expected 1 to be 0 (Object.is equality).

⏰ 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: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (5)
apps/web/utils/schedule.ts (2)

166-166: LGTM! Logic change correctly excludes exact time matches.

The change from >= to > prevents scheduling at the exact same time as fromDate, which is the correct behavior for finding the "next" occurrence.


182-183: LGTM! Extended search window improves scheduling flexibility.

Extending the search window from 7 to 14 days allows the function to find weekly occurrences across a two-week period, which is more robust for edge cases.

apps/web/utils/schedule.test.ts (3)

1-1: Import reordering looks good.

The reordering of imports maintains alphabetical order and readability.


694-757: LGTM! Comprehensive test coverage for long intervals.

The new test cases provide excellent coverage for edge cases including:

  • Very long intervals (365 and 1000 days)
  • Multiple occurrences within long intervals
  • Leap year handling
  • Year boundary crossing

These tests validate the robustness of the scheduling algorithm for extreme scenarios.


207-212: Comment improvements enhance test clarity.

The updates to test comments, replacing "local time" with "AM" and improving time descriptions, make the test intentions much clearer and more precise.

Also applies to: 284-289, 307-312, 328-333, 349-354, 369-374, 389-394, 410-415, 432-438, 453-460, 494-499, 517-522, 538-543, 558-563

@elie222 elie222 merged commit f4dcc1d into elie222:main Jul 21, 2025
7 of 10 checks passed
@edulelis edulelis deleted the digest-emails-v5 branch July 24, 2025 18:15
@coderabbitai coderabbitai bot mentioned this pull request Aug 25, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 3, 2025
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