Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded@elie222 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 23 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (5)
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughAdds response-time analytics: DB model and migrations, server-side calculation and API route, provider changes for inbox/sent retrieval, a React analytics UI with charts, tests for calculation logic, and removal of older stats routes. Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant UI as ResponseTimeAnalytics
participant API as /api/user/stats/response-time
participant DB as Database (ResponseTime)
participant Calc as calculateResponseTimes
participant Provider as EmailProvider
Client->>UI: open analytics (date range)
UI->>API: GET with from/to
API->>DB: fetch cached sent messages/meta
DB-->>API: cached entries
API->>DB: fetch sent messages (sentMessageIds)
DB-->>API: sent messages list
API->>Calc: calculateResponseTimes(sentMessages, provider)
Calc->>Provider: get thread messages / histories
Provider-->>Calc: thread messages
Calc->>Calc: pair SENT with previous RECEIVED, compute deltas
Calc-->>API: responseTimeEntries
API->>DB: upsert new ResponseTime entries (cap & dedupe)
DB-->>API: upsert result
API->>API: calculateSummaryStats/distribution/trend
API-->>UI: { summary, distribution, trend, emailsAnalyzed }
UI->>Client: render cards & charts (using formatters)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20–25 minutes
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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.
3 issues found across 1 file
Prompt for AI agents (all 3 issues)
Understand the root cause of the following 3 issues and fix them.
<file name="apps/web/app/api/user/stats/response-time/route.ts">
<violation number="1" location="apps/web/app/api/user/stats/response-time/route.ts:106">
The received filter compares against the recipient address, so the customer's reply is excluded and your own outbound message is treated as inbound; switch to the sender address so we keep actual customer responses.</violation>
<violation number="2" location="apps/web/app/api/user/stats/response-time/route.ts:118">
This filter also checks against the recipient address, so inbound replies are treated as your own outbound messages; use the sender address to capture actual user-sent mail.</violation>
<violation number="3" location="apps/web/app/api/user/stats/response-time/route.ts:255">
Guard the previous-period recursion when `differenceInDays` returns 0 (same-day range); otherwise this calls itself with identical parameters and recurses forever.</violation>
</file>
React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.
Add response time analytics to Stats page and expose GET /api/user/stats/response-time with weekly median trend and distribution bucketing (<1h, 1–4h, 4–24h, 1–3d, 3–7d, >7d)Introduce response-time analytics end to end: a new API computes and caches per-account response times and returns summary, distribution, and weekly trend; the Stats page renders the data with configurable chart formatters; email providers gain inbox and sent lookup methods; schema adds a 📍Where to StartStart with the GET handler Macroscope summarized 1d10e98. |
| // Fetch sent messages in the date range | ||
| const sentMessages = await emailProvider.getMessagesByFields({ | ||
| type: "sent", | ||
| ...(fromDate ? { after: new Date(fromDate) } : {}), |
There was a problem hiding this comment.
Using truthy checks on fromDate/toDate drops valid 0 (Unix epoch). Consider checking for null/undefined instead (e.g., fromDate != null, toDate != null) in the spread filters and the previous-period if so 0 is respected.
🚀 Reply to ask Macroscope to explain or update this suggestion.
👍 Helpful? React to give us feedback.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
apps/web/app/api/user/stats/response-time/route.ts (2)
101-125: Inbound vs outbound filters are inverted (using recipient instead of sender).
receivedMessagesandsentMessagesInThreadboth compareheaders.fromagainstsentMsg.headers.to, which is the recipient address of your original outbound email. This:
- Treats your own outbound messages as “received”.
- Excludes actual customer replies from
receivedMessages.You almost certainly want to distinguish based on the sender (your address) instead:
- “Sent” = messages whose
frommatches the original sender (sentMsg.headers.from).- “Received” = messages whose
fromdoes not match that sender.A minimal fix:
- const receivedMessages = threadMessages - .filter( - (m) => - m.internalDate && - !m.headers.from?.includes(sentMsg.headers.to || ""), - ) + const receivedMessages = threadMessages + .filter( + (m) => + m.internalDate && + !m.headers.from?.includes(sentMsg.headers.from || ""), + ) @@ - const sentMessagesInThread = threadMessages - .filter( - (m) => - m.internalDate && - m.headers.from?.includes(sentMsg.headers.to || ""), - ) + const sentMessagesInThread = threadMessages + .filter( + (m) => + m.internalDate && + m.headers.from?.includes(sentMsg.headers.from || ""), + )This aligns with the previous Cubic comment and ensures response times are computed between actual customer messages and your replies.
245-273: Guard previous‑period recursion to avoid infinite loop for zero‑length ranges.If
differenceInDaysreturns 0 (same‑day or otherwise zero‑day range), the computed previous window is identical (fromDate→fromDate), andgetResponseTimeStatsrecursively calls itself with the same parameters indefinitely.You should skip the previous‑period computation when the day span is ≤ 0:
// Calculate previous period comparison let previousPeriodComparison = null; if (fromDate && toDate) { const currentPeriodDays = differenceInDays( new Date(toDate), new Date(fromDate), ); - const previousFromDate = subDays(new Date(fromDate), currentPeriodDays); - const previousToDate = new Date(fromDate); - - const previousPeriodStats = await getResponseTimeStats({ - fromDate: previousFromDate.getTime(), - toDate: previousToDate.getTime(), - emailProvider, - logger, - }); - - if (previousPeriodStats.summary.medianResponseTime > 0) { - const percentChange = - ((medianResponseTime - previousPeriodStats.summary.medianResponseTime) / - previousPeriodStats.summary.medianResponseTime) * - 100; - - previousPeriodComparison = { - medianResponseTime: previousPeriodStats.summary.medianResponseTime, - percentChange: Math.round(percentChange), - }; - } + if (currentPeriodDays > 0) { + const previousFromDate = subDays(new Date(fromDate), currentPeriodDays); + const previousToDate = new Date(fromDate); + + const previousPeriodStats = await getResponseTimeStats({ + fromDate: previousFromDate.getTime(), + toDate: previousToDate.getTime(), + emailProvider, + logger, + }); + + if (previousPeriodStats.summary.medianResponseTime > 0) { + const percentChange = + ((medianResponseTime - + previousPeriodStats.summary.medianResponseTime) / + previousPeriodStats.summary.medianResponseTime) * + 100; + + previousPeriodComparison = { + medianResponseTime: previousPeriodStats.summary.medianResponseTime, + percentChange: Math.round(percentChange), + }; + } + } }In date-fns v4.1.0, what does `differenceInDays` return when both arguments are the same date, and can it be zero for valid ranges?
🧹 Nitpick comments (3)
apps/web/app/api/user/stats/response-time/route.ts (3)
44-49:periodDateis typed asDatebut serialized to JSON as a string.The
trendtype currently exposesperiodDate: Date, andResponseTimeResponsere‑exports that return type, butNextResponse.jsonwill serialize theDateto an ISO string:trend: Array<{ period: string; periodDate: Date; ... }> ... return { period: format(date, "LLL dd, y"), periodDate: date, // becomes string over the wire ... };On the client, anything using
ResponseTimeResponsewill thinkperiodDateis aDateinstance but actually receive a string.Consider normalizing this to a string (or number) in both type and implementation, e.g.:
- trend: Array<{ - period: string; - periodDate: Date; - medianResponseTime: number; - count: number; - }>; + trend: Array<{ + period: string; + periodDate: string; // ISO string + medianResponseTime: number; + count: number; + }>;and:
- return { - period: format(date, "LLL dd, y"), - periodDate: date, - medianResponseTime: Math.round(median), - count: values.length, - }; + return { + period: format(date, "LLL dd, y"), + periodDate: date.toISOString(), + medianResponseTime: Math.round(median), + count: values.length, + };This keeps the API contract honest and avoids subtle client bugs.
Also applies to: 236-241, 278-288, 291-293
91-153: SequentialgetThreadMessagescalls may be slow for larger datasets.The
for...ofloop awaitsemailProvider.getThreadMessagesone thread at a time. With up to 500 sent messages, this can mean hundreds of sequential network calls and a very slow endpoint.Consider batching with a bounded concurrency pattern, for example:
- Build an array of async tasks per unique
threadId.- Use
Promise.allwith a simple pool/limit (e.g.p-limitor a hand‑rolled queue) to run, say, 5–10 in parallel while keeping rate limits in mind.This should materially improve response times without changing the external behavior.
11-14: Handle query param validation errors with 400 instead of 500.The current code at line 295 uses
responseTimeParams.parse()without error handling. When invalid query params are passed (e.g.,?fromDate=abc),z.coerce.number()will throw a ZodError that bubbles up as a 500 error instead of the expected 400 client error.Switch to
safeParse()and return a 400 JSON error on validation failure:const result = responseTimeParams.safeParse({ fromDate: searchParams.get("fromDate"), toDate: searchParams.get("toDate"), }); if (!result.success) { return NextResponse.json( { error: "Invalid query parameters", details: result.error.flatten() }, { status: 400 } ); } const params = result.data;Also applies to: 295-309
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/web/app/api/user/stats/response-time/route.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/app/api/user/stats/response-time/route.ts (2)
apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/utils/middleware.ts (1)
withEmailProvider(401-414)
⏰ 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). (5)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Jit Security
- GitHub Check: test
- GitHub Check: Review for correctness
- GitHub Check: Analyze (javascript-typescript)
There was a problem hiding this comment.
3 issues found across 1 file
Prompt for AI agents (all 3 issues)
Understand the root cause of the following 3 issues and fix them.
<file name="apps/web/app/api/user/stats/response-time/route.ts">
<violation number="1" location="apps/web/app/api/user/stats/response-time/route.ts:106">
Received/sent classification compares sender headers to the outgoing recipients, so the buckets are inverted and the reported response times track customer replies instead of the user’s responses.</violation>
<violation number="2" location="apps/web/app/api/user/stats/response-time/route.ts:248">
`differenceInDays` can return 0 for same‑day ranges, so the recursive previous‑period call runs with the exact same dates and never terminates, leading to infinite recursion for short queries.</violation>
<violation number="3" location="apps/web/app/api/user/stats/response-time/route.ts:276">
Hardcoding the responseRate to 100% always reports perfect performance even if some processed threads never receive a qualifying reply; derive the percentage from the ratio of threads with measured response times to total processed threads.</violation>
</file>
Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (4)
apps/web/app/api/user/stats/response-time/route.ts (4)
81-82: Guard against dropping valid epoch timestamp (0).The truthy checks
fromDate ? ...andtoDate ? ...will omit the filter when the timestamp is0(Unix epoch). Use explicit nullish checks instead.Apply this diff:
- ...(fromDate ? { after: new Date(fromDate) } : {}), - ...(toDate ? { before: new Date(toDate) } : {}), + ...(fromDate != null ? { after: new Date(fromDate) } : {}), + ...(toDate != null ? { before: new Date(toDate) } : {}),
216-245: Prevent infinite recursion for same-day ranges.When
differenceInDaysreturns 0, the recursive call togetResponseTimeStatsreceives identical date parameters, causing infinite recursion.Apply this diff to guard the recursion:
async function calculatePreviousPeriodComparison( fromDate: number | null | undefined, toDate: number | null | undefined, currentMedian: number, emailProvider: EmailProvider, logger: Logger, ): Promise<SummaryStats["previousPeriodComparison"]> { if (!fromDate || !toDate) return null; const currentDays = differenceInDays(new Date(toDate), new Date(fromDate)); + // Guard against infinite recursion for same-day or invalid ranges + if (currentDays <= 0) return null; + const prevFrom = subDays(new Date(fromDate), currentDays); const prevTo = new Date(fromDate);
271-271: Compute actual response rate instead of hardcoding 100%.Hardcoding
responseRate: 100is misleading. Threads without qualifying received→sent pairs are excluded fromresponseTimes, making the reported rate inaccurate.The actual rate should reflect the ratio of threads with measured responses to total processed threads. However,
processedThreadsis local tocalculateResponseTimesand not accessible here. Consider one of these approaches:Option 1: Return
processedThreads.sizefromcalculateResponseTimesand pass it tocalculateSummaryStats:export async function calculateResponseTimes( sentMessages: any[], emailProvider: EmailProvider, logger: Logger, -): Promise<ResponseTimeEntry[]> { +): Promise<{ responseTimes: ResponseTimeEntry[]; totalThreads: number }> { const responseTimes: ResponseTimeEntry[] = []; const processedThreads = new Set<string>(); // ... existing logic ... - return responseTimes; + return { responseTimes, totalThreads: processedThreads.size }; }Then update
calculateSummaryStats:export async function calculateSummaryStats( responseTimes: ResponseTimeEntry[], + totalThreads: number, fromDate: number | null | undefined, toDate: number | null | undefined, emailProvider: EmailProvider, logger: Logger, ): Promise<SummaryStats> { const values = responseTimes.map((r) => r.responseTimeMinutes); // ... return { medianResponseTime: Math.round(medianResponseTime), averageResponseTime: Math.round(averageResponseTime), - responseRate: 100, + responseRate: totalThreads === 0 ? 0 : Math.round((responseTimes.length / totalThreads) * 100), within1Hour: Math.round(within1Hour), previousPeriodComparison, }; }Option 2: Remove or rename the field until you can accurately track unanswered threads.
223-223: Use nullish check for consistency.Similar to lines 81-82, the truthy check here will reject valid
0timestamps.Apply this diff:
- if (!fromDate || !toDate) return null; + if (fromDate == null || toDate == null) return null;
🧹 Nitpick comments (3)
apps/web/app/api/user/stats/response-time/route.test.ts (3)
11-11: Remove unused import.The import on line 11 is shadowed by line 20 and never used.
Apply this diff:
-import { getMockMessage } from "@/utils/test/helpers"; import type { EmailProvider } from "@/utils/email/types";
197-219: Consider adding test coverage for edge cases.The current test doesn't verify:
- The
responseRatefield (currently hardcoded to 100%)- The
previousPeriodComparisonlogic (requires non-nullfromDate/toDate)- Edge cases like empty arrays or single-value arrays
Consider adding tests like:
it("should handle empty response times", async () => { const result = await calculateSummaryStats( [], null, null, mockProvider, mockLogger, ); expect(result.averageResponseTime).toBe(0); expect(result.medianResponseTime).toBe(0); expect(result.within1Hour).toBe(0); }); it("should calculate previous period comparison when dates provided", async () => { // Test with fromDate/toDate to verify previousPeriodComparison // Note: This would require mocking getResponseTimeStats });
221-238: Consider testing bucket boundaries.The current test verifies basic bucketing but doesn't test boundary values that might be off-by-one errors.
Consider adding a test for exact boundaries:
it("should handle bucket boundaries correctly", () => { const responseTimes = [ { responseTimeMinutes: 59 }, // < 1h (edge) { responseTimeMinutes: 60 }, // 1-4h (boundary) { responseTimeMinutes: 239 }, // 1-4h (edge) { responseTimeMinutes: 240 }, // 4-24h (boundary) { responseTimeMinutes: 1440 }, // 1-3d (boundary) ] as any[]; const result = calculateDistribution(responseTimes); expect(result.lessThan1Hour).toBe(1); expect(result.oneToFourHours).toBe(2); expect(result.fourTo24Hours).toBe(1); expect(result.oneToThreeDays).toBe(1); });
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/app/api/user/stats/response-time/route.test.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
apps/web/app/api/user/stats/response-time/route.test.ts (2)
apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/app/api/user/stats/response-time/route.ts (3)
calculateResponseTimes(119-193)calculateSummaryStats(247-275)calculateDistribution(277-289)
apps/web/app/api/user/stats/response-time/route.ts (2)
apps/web/utils/middleware.ts (1)
withEmailProvider(401-414)apps/web/utils/logger.ts (1)
Logger(5-5)
⏰ 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). (5)
- GitHub Check: Static Code Analysis Js
- GitHub Check: Jit Security
- GitHub Check: cubic · AI code reviewer
- GitHub Check: test
- GitHub Check: Review for correctness
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (5)
apps/web/app/api/user/stats/response-time/route.ts (5)
122-131: Sent/received detection is Gmail-specific; prefer provider-aware helperClassification currently relies on the hardcoded
"SENT"label and a fallback membership in the initialsentMessageslist. That’s fine for Gmail but will misclassify messages for other providers (e.g. Outlook) that don’t share the same label semantics.If your
EmailProviderexposes something likeemailProvider.isSentMessage(message), prefer delegating the classification to that helper so each provider can encode its own rules. This also centralizes any future tweaks in one place.Also applies to: 155-165
12-16: Invalid timestamps becomeNaNand can bubble into Date logic / 500s; tighten schema or treat as bad request
z.coerce.number().nullish()will happily coerce invalid query strings (e.g.?fromDate=abcor empty) toNaN, which then flows intonew Date(fromDate)/differenceInDaysand can cause unpredictable behavior or 500s rather than a clean 400. Consider refining to finite numbers and/or usingsafeParseto return a 400 for bad params, e.g.:const timestamp = z .preprocess((value) => { if (value == null) return undefined; const n = Number(value); return Number.isFinite(n) ? n : undefined; }, z.number().optional()); const responseTimeSchema = z.object({ fromDate: timestamp, toDate: timestamp, });and handle
safeParsefailure in the handler as a 400 instead of throwing.Also applies to: 52-57
83-86: Truthiness checks onfromDate/toDatedrop valid0(Unix epoch) and conflate “absent” with “0”Both the
getMessagesByFieldsfilters andcalculatePreviousPeriodComparisonuse truthy checks (fromDate ? …/if (!fromDate || !toDate)) so a valid0timestamp is treated as missing, andnull/undefined/0are all folded together. If0is meant to be valid, prefer explicit nullish checks:// Fetch ...(fromDate != null ? { after: new Date(fromDate) } : {}), ...(toDate != null ? { before: new Date(toDate) } : {}), // Previous-period guard if (fromDate == null || toDate == null) return null;This also pairs better with a refined schema that rejects
NaN.Also applies to: 217-225
68-87: Previous-period calculation causes unbounded recursion (and same-range loops when day-diff ≤ 0)
calculateSummaryStatsalways callscalculatePreviousPeriodComparison, which callsgetResponseTimeStatsagain with another window; that inner call again computes a previous period, and so on without a base case. WhendifferenceInDaysreturns0(same-day range) you even recurse with identical dates. This will eventually stack overflow for any request withfromDate/toDate.You need both (a) a guard on the day span and (b) a way to disable previous-period recursion for the recursive call, e.g.:
type GetResponseTimeStatsOptions = { includePreviousPeriod?: boolean }; async function getResponseTimeStats( { fromDate, toDate, emailProvider, logger }: ResponseTimeParams & { emailProvider: EmailProvider; logger: Logger }, { includePreviousPeriod = true }: GetResponseTimeStatsOptions = {}, ) { // ... const summary = await calculateSummaryStats( responseTimes, includePreviousPeriod ? fromDate : null, includePreviousPeriod ? toDate : null, emailProvider, logger, ); } async function calculatePreviousPeriodComparison(/* … */) { if (fromDate == null || toDate == null) return null; const currentDays = differenceInDays(new Date(toDate), new Date(fromDate)); if (!Number.isFinite(currentDays) || currentDays <= 0) return null; const prevStats = await getResponseTimeStats( { fromDate: subDays(new Date(fromDate), currentDays).getTime(), toDate: new Date(fromDate).getTime(), emailProvider, logger, }, { includePreviousPeriod: false }, ); // ... }Without something along these lines, this endpoint is not safe to deploy.
Also applies to: 217-246, 261-267
248-276:responseRatehardcoded to 100% makes the metric incorrect / misleading
calculateSummaryStatsalways returnsresponseRate: 100, whilegetEmptyStatsuses0. SinceresponseTimesonly includes threads with a valid received→sent pair, unanswered threads are invisible and this 100% figure does not reflect reality.Either compute an actual rate (e.g. thread-level responses / total processed threads, possibly by returning
processedThreads.sizefromcalculateResponseTimes) or drop/rename the field until you have enough data to compute it meaningfully. At minimum, avoid returning a hardcoded 100%.Also applies to: 333-341
🧹 Nitpick comments (3)
apps/web/app/api/user/stats/response-time/route.ts (3)
211-215: Align “within 1 hour” metric with< 1 hourbucket semantics
calculateWithin1Hourtreats<= 60minutes as “within 1 hour”, whilecalculateDistributionuses< 60for thelessThan1Hourbucket. A 60‑minute response is counted as “within 1 hour” but ends up in theoneToFourHoursbucket, which may be confusing when comparing metrics.Either change the metric to
< 60to match the bucket, or rename the bucket to something likeupTo1Hourand adjust the threshold, so names and thresholds stay consistent.Also applies to: 278-299
81-87: Sampling only the first 100 sent messages can skew stats for heavy users
getMessagesByFieldsis capped atmaxResults: 100, andcalculateResponseTimesprocesses only threads corresponding to those messages. For users with high volume, this may bias summary/distribution/trend toward the most recent or arbitrary slice of activity.If feasible, consider:
- Paging through more messages for the selected window, or
- Making the cap configurable / clearly documenting that this is a sampled view.
This is not a correctness bug but worth being explicit about.
Also applies to: 122-191
18-23: API response serializesDatefields to strings; ensure consumer types reflect that
ResponseTimeEntry.receivedDate/sentDateandTrendEntry.periodDateare typed asDate, butNextResponse.jsonwill serialize them as ISO strings over the wire. If these interfaces (or a derivedResponseTimeResponsetype) are reused on the client, the runtime shape will actually be{ periodDate: string, receivedDate: string, … }.Consider defining explicit API response types that use
stringfor date fields (and keepDatefor internal/server-only structs), or consistently parse them back toDateon the client while reflecting that in types.Also applies to: 45-50, 304-331, 333-352
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/web/app/api/user/stats/response-time/route.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/app/api/user/stats/response-time/route.ts (3)
apps/web/utils/middleware.ts (1)
withEmailProvider(401-414)apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/utils/types.ts (1)
ParsedMessage(51-73)
⏰ 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)
- GitHub Check: cubic · AI code reviewer
There was a problem hiding this comment.
2 issues found across 2 files (reviewed changes from recent commits).
Prompt for AI agents (all 2 issues)
Understand the root cause of the following 2 issues and fix them.
<file name="apps/web/app/api/user/stats/response-time/route.ts">
<violation number="1" location="apps/web/app/api/user/stats/response-time/route.ts:167">
Response-time metrics ignore the requested date range: once a thread is selected, every historical reply in that thread is counted, so a 7‑day query still includes months-old responses.</violation>
<violation number="2" location="apps/web/app/api/user/stats/response-time/route.ts:272">
Response rate is always reported as 100%, because it is hard-coded instead of being derived from the share of sent conversations that received a reply.</violation>
</file>
Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR
There was a problem hiding this comment.
2 issues found across 2 files
Prompt for AI agents (all 2 issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="apps/web/app/api/user/stats/response-time/route.ts">
<violation number="1" location="apps/web/app/api/user/stats/response-time/route.ts:94">
P1: The date range filters are ignored after fetching threads, so response-time stats for a period include every historical reply in any matching thread, inflating the requested window’s metrics.</violation>
<violation number="2" location="apps/web/app/api/user/stats/response-time/route.ts:226">
P2: `differenceInDays` truncates to zero for sub‑day ranges, so previous-period comparisons never move backward—they recurse with the exact same window and can’t produce a meaningful change for “today”/hourly queries.</violation>
</file>
Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR
There was a problem hiding this comment.
4 issues found across 7 files (changes from recent commits).
Prompt for AI agents (all 4 issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="apps/web/prisma/migrations/20251207172822_response_time/migration.sql">
<violation number="1" location="apps/web/prisma/migrations/20251207172822_response_time/migration.sql:8">
P1: `responseTimeMs` is created as BIGINT even though the Prisma model declares it as Int, causing Prisma schema/DB drift and failing future migrations.</violation>
</file>
<file name="apps/web/prisma/schema.prisma">
<violation number="1" location="apps/web/prisma/schema.prisma:715">
P2: `responseTimeMs` uses a 32-bit Int, so any response taking more than ~24 days (2,147,483,647 ms) will overflow and fail to persist. Use a BigInt to safely store millisecond durations that can span weeks or months.</violation>
</file>
<file name="apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx">
<violation number="1" location="apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx:81">
P3: User-facing text misspells “Response” as “Respone”, leaving a typo in the analytics UI.</violation>
<violation number="2" location="apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx:212">
P2: `formatTime` can output impossible durations (e.g., `1h 60m`, `1d 24h`) because rounded remainders are never carried into the next unit, leading to incorrect analytics readouts.</violation>
</file>
Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR
apps/web/prisma/migrations/20251207172822_response_time/migration.sql
Outdated
Show resolved
Hide resolved
apps/web/prisma/schema.prisma
Outdated
| threadId String | ||
| sentMessageId String | ||
| receivedMessageId String | ||
| responseTimeMs Int // Denormalized: sentAt - receivedAt |
There was a problem hiding this comment.
P2: responseTimeMs uses a 32-bit Int, so any response taking more than ~24 days (2,147,483,647 ms) will overflow and fail to persist. Use a BigInt to safely store millisecond durations that can span weeks or months.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/prisma/schema.prisma, line 715:
<comment>`responseTimeMs` uses a 32-bit Int, so any response taking more than ~24 days (2,147,483,647 ms) will overflow and fail to persist. Use a BigInt to safely store millisecond durations that can span weeks or months.</comment>
<file context>
@@ -705,6 +706,23 @@ model EmailMessage {
+ threadId String
+ sentMessageId String
+ receivedMessageId String
+ responseTimeMs Int // Denormalized: sentAt - receivedAt
+ receivedAt DateTime
+ sentAt DateTime
</file context>
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
Outdated
Show resolved
Hide resolved
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
apps/web/app/api/user/stats/response-time/route.test.ts (1)
1-4: Solid test coverage; consider tightening imports and typesTests cover the key response-time scenarios well and validate summary/distribution logic. A few polish points you may want to address:
- Prefer importing helpers via the alias (
@/__tests__/helpers) instead of the deep relative path to match existing test patterns.- The comment block around Lines 12–17 is meta/documentation about helpers’ location; it can be removed to keep the test file focused.
mockEmailProvider: anyand theas any[]casts forresponseTimesweaken type safety vs the repo-wide “noany” rule. Consider either:
- Exporting a minimal
ResponseTimeEntrytype from the route and using it in tests, or- Using
as unknown as ResponseTimeEntry[]in one place with a comment, rather thananyin multiple spots.None of these block merging but they’ll keep tests more in line with the TS guidelines.
Also applies to: 12-18, 27-35, 195-204, 216-221
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (1)
31-36: Minor UX and type-safety tweaks in ResponseTimeAnalyticsFunctionality looks good and matches the route shape; a few small refinements would help:
- Line 81: text typo —
"Respone time data..."→"Response time data...".- Lines 33–35:
new URLSearchParams(params as Record<string, string>)relies on a cast even thoughResponseTimeParamscontains numbers/nullish values. Consider normalizing to strings and dropping nulls instead of casting, e.g. building aRecord<string, string>fromObject.entries(params).filter(([_, v]) => v != null)before passing it toURLSearchParams.- Lines 86–103:
className="grid gap-2 sm:gap-4 grid-cols-3"forces three columns on mobile; using a mobile‑first layout likegrid-cols-1 sm:grid-cols-3will keep cards readable on small screens while preserving the desktop layout.These are small but will improve robustness and mobile UX.
Also applies to: 38-61, 71-85, 86-103
apps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx (1)
14-25: Chart extensions are backward‑compatible; mind tooltip value typing for future usesThe added
yAxisFormatter,tooltipLabelFormatter, andtooltipValueFormatterprops cleanly extend theBarChartwithout breaking existing callers, and the new tooltip label logic correctly falls back when the x‑value isn’t a date.One minor forward‑compatibility note:
tooltipValueFormatteris typed/used as(value: number) => stringwithentry.value as number. If you later reuse this chart with non‑numeric series, you may want to widen that to(value: number | string) => stringand avoid the cast. For the current numeric analytics use cases this is fine.Also applies to: 33-36, 110-115, 116-121, 123-146, 166-170
apps/web/prisma/schema.prisma (1)
167-168: ResponseTime model and relation look good; double‑checkresponseTimeMstype vs migrationThe new
responseTimesrelation onEmailAccountand theResponseTimemodel (ids, timestamps, thread/message IDs,@@unique([emailAccountId, sentMessageId]), and@@index([emailAccountId, sentAt])) fit the analytics use case and are correctly scoped byemailAccountId.Given the migration creates
responseTimeMsasBIGINT, confirm whether you want this field to be a 32‑bitInt(and adjust the migration) or a 64‑bitBigInt(and adjust the Prisma field toBigInt/Int @db.BigInt). Keeping these aligned will make Prisma Client behavior predictable.Also applies to: 709-724
apps/web/app/api/user/stats/response-time/route.ts (2)
12-17: Tighten query param handling and date‑range guardsOverall route structure, scoping by
emailAccountId, and use of Prismaselectall look solid. A few improvements around query params and date handling:
- Lines 12–17:
z.coerce.number().nullish()will accept invalid strings asNaN. Later,new Date(fromDate)/new Date(toDate)and numeric comparisons run against these values, which can lead toInvalid Dateor unexpected filtering. Consider refining to finite numbers or mapping invalid/NaN toundefinedbefore use (e.g..transform(v => Number.isFinite(v) ? v : undefined)or a.refine(Number.isFinite)and catching 400s at the middleware layer).- Lines 95–101 & 171–176: using truthy checks (
fromDate ? {...} : {},if (fromDate && sentTime < fromDate)) drops legitimate0and is also slightly misleading. Prefer explicit nullability checks (fromDate != null) so all numeric values are honored and behavior is clearer.- With those changes, the route will be more robust against bad query strings and edge ranges while keeping the current behavior for normal usage.
Functionally the analytics look correct; these are hardening tweaks around inputs.
Also applies to: 61-76, 95-101, 171-176
197-275: Thread walking and response‑pair detection behave as intended; consider future provider‑aware refinement
calculateResponseTimescorrectly:
- Processes each thread once via
processedThreadsto avoid duplicates.- Sorts by
internalDateand tracks a single outstanding received message to pair with the next sent message, matching the test scenarios (simple replies and alternating receive/send).- Classifies sent messages using Gmail’s
"SENT"label and falls back to membership in the initialsentMessagesset, which keeps the logic working even if some providers don’t set that label.Two minor notes you may consider later:
- The comment
// we capped it at 100is now stale vsMAX_SENT_MESSAGES = 50; updating it will avoid confusion.- There’s an
awaitinside thefor ... ofloop (per‑threadgetThreadMessages). With the current cap of 50 this is fine, but if you ever raise the cap significantly you might want to batch these calls viaPromise.allSettledwith some concurrency control.Given current limits and tests, this logic is acceptable as‑is.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
apps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx(4 hunks)apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx(1 hunks)apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx(2 hunks)apps/web/app/api/user/stats/response-time/route.test.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/prisma/migrations/20251207172822_response_time/migration.sql(1 hunks)apps/web/prisma/schema.prisma(2 hunks)
🧰 Additional context used
📓 Path-based instructions (24)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Follow NextJS app router structure with (app) directory
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks over class components
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Use LoadingContent component for async data with loading and error states
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/(app)/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)
apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put inpage.tsx, or in theapps/web/app/(app)/PAGE_NAMEfolder
If we're in a deeply nested component we will useswrto fetch via API
If you need to useonClickin a component, that component is a client component and file must start withuse client
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.tsx: Use theLoadingContentcomponent to handle loading states instead of manual loading state management
For text areas, use theInputcomponent withtype='text',autosizeTextareaprop set to true, andregisterPropsfor form integration
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include atitleelement for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
AssigntabIndexto non-interactive HTML elements witharia-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
Don't use the return value of React.render
Make sure all dependencies are correctly specified in React hooks
Make sure all React hooks are called from the top level of component functions
Don't forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use bothchildrenanddangerouslySetInnerHTMLprops on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use<>...</>instead of<Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't usetarget="_blank"withoutrel="noopener"
Don't use<img>elements in Next.js projects
Don't use<head>elements in Next.js projects
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/prisma/schema.prismaapps/web/app/api/user/stats/response-time/route.test.tsapps/web/prisma/migrations/20251207172822_response_time/migration.sql
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/(app)/[emailAccountId]/stats/Stats.tsxapps/web/app/(app)/[emailAccountId]/stats/BarChart.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/api/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/*.ts: Wrap GET API routes withwithAuthorwithEmailAccountmiddleware for authentication
Export response types from GET API routes usingAwaited<ReturnType<>>pattern for type-safe client usage
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
apps/web/app/api/**/route.ts: Create GET API routes usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/app/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)
**/app/**/route.ts: Always wrap GET API route handlers withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, as the middleware handles error handling
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/**/[!.]*/route.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Use kebab-case for route directories in Next.js App Router (e.g.,
api/hello-world/route)
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,tsx}: API routes must usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/app/api/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/prisma/schema.prisma
📄 CodeRabbit inference engine (.cursor/rules/prisma.mdc)
Use PostgreSQL as the database system with Prisma
Files:
apps/web/prisma/schema.prisma
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Usevitestfor testing the application
Tests should be colocated next to the tested file with.test.tsor.test.tsxextension (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and import the mock from@/utils/__mocks__/prisma
Usevi.clearAllMocks()inbeforeEachto clean up mocks between tests
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Do not mock the Logger
Avoid testing implementation details
Use test helpersgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor mocking emails, accounts, and rules
Files:
apps/web/app/api/user/stats/response-time/route.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests
Files:
apps/web/app/api/user/stats/response-time/route.test.ts
🧠 Learnings (25)
📓 Common learnings
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Create GET API routes using `withAuth` or `withEmailAccount` middleware in `apps/web/app/api/*/route.ts`, export response types as `GetExampleResponse` type alias for client-side type safety
📚 Learning: 2025-11-25T14:42:11.919Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-11-25T14:42:11.919Z
Learning: Applies to utils/**/*.{js,ts,jsx,tsx} : The `utils` folder contains core app logic such as Next.js Server Actions and Gmail API requests
Applied to files:
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
📚 Learning: 2025-11-25T14:42:16.602Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-11-25T14:42:16.602Z
Learning: The `utils` folder contains core app logic such as Next.js Server Actions and Gmail API requests
Applied to files:
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/**/*.tsx : Use LoadingContent component for async data with loading and error states
Applied to files:
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/{pages,routes,components}/**/*.{ts,tsx} : Never call Gmail API directly from routes or components - always use wrapper functions from the utils folder
Applied to files:
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Create GET API routes using `withAuth` or `withEmailAccount` middleware in `apps/web/app/api/*/route.ts`, export response types as `GetExampleResponse` type alias for client-side type safety
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Wrap GET API routes with `withAuth` or `withEmailAccount` middleware for authentication
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use Date.now() to get milliseconds since the Unix Epoch
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Don't compare against -0
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use isNaN() when checking for NaN
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Design Gmail wrapper functions to be provider-agnostic to support future email providers like Outlook and ProtonMail
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Set timeout constant `const TIMEOUT = 15_000;` for LLM tests
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
🧬 Code graph analysis (2)
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx (1)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (1)
ResponseTimeAnalytics(27-154)
apps/web/app/api/user/stats/response-time/route.ts (3)
apps/web/utils/middleware.ts (1)
withEmailProvider(426-439)apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/utils/types.ts (1)
ParsedMessage(51-73)
⏰ 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). (3)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: test
- GitHub Check: Review for correctness
🔇 Additional comments (5)
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx (1)
12-12: ResponseTimeAnalytics integration looks correct and consistentNew component is wired with the same
dateRange/refreshIntervalpattern as existing analytics and is placed sensibly in the stats grid; no issues from this change.Also applies to: 126-129
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (1)
156-205: Summary cards and time formatting logic look sound
SummaryCard,formatTime, andformatTimeShorthandle the expected comparison object shape and convert minute values into readable strings with sensible boundaries (minutes, hours, days). The conditional comparison styling and icons are also wired correctly.Also applies to: 207-230
apps/web/app/api/user/stats/response-time/route.ts (3)
109-132: Response‑time caching and range filtering logic are soundThe cache layer (
findManybyemailAccountIdandsentMessageId), calculation only for uncached messages,createManywithskipDuplicates, and final filtering ofcombinedEntriesbysentAtwithin[fromDate, toDate]all look correct and respect ownership and the requested window. ClampingresponseTimeMstoMAX_RESPONSE_TIME_MSis also a reasonable safety boundary.Also applies to: 135-162, 170-195
277-345: Summary/distribution/trend computations are correct and match the UI expectations
calculateSummaryStatscorrectly converts ms→minutes, computes median/average, and derives the “within 1 hour” percentage, rounding for display and leavingpreviousPeriodComparisonnull (avoiding the earlier recursion issues).calculateDistributionbuckets minute values into<1h,1–4h,4–24h,1–3d,3–7d, and>7dranges, aligning with the UI labels.calculateTrendgroups bystartOfWeek(sentAt), computes a median per week, and sorts byperiodDate, which fits the “Weekly Response Time Trend” chart.These helpers line up with the data shapes expected by
ResponseTimeAnalytics.tsx.
376-395: Empty‑state helper is consistent with API and UI consumers
getEmptyStatsreturns zeros andpreviousPeriodComparison: nullwithemailsAnalyzed: 0and the samemaxEmailsCapconstant. This matches what the UI expects for empty periods and keeps the response shape stable.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (1)
208-219: Fix rounding logic to prevent impossible durations.The current implementation can output invalid values like "1h 60m" or "1d 24h" when the remainder rounds up to the next unit boundary.
Example:
formatTime(119.5)produces:
hours = Math.floor(119.5 / 60) = 1mins = Math.round(119.5 % 60) = Math.round(59.5) = 60- Result:
"1h 60m"❌Apply this diff to fix the rounding logic:
function formatTime(minutes: number): string { if (minutes === 0) return "0m"; - if (minutes < 60) return `${Math.round(minutes)}m`; + const totalMinutes = Math.round(minutes); + if (totalMinutes < 60) return `${totalMinutes}m`; if (minutes < 1440) { - const hours = Math.floor(minutes / 60); - const mins = Math.round(minutes % 60); + const hours = Math.floor(totalMinutes / 60); + const mins = totalMinutes % 60; return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`; } - const days = Math.floor(minutes / 1440); - const hours = Math.round((minutes % 1440) / 60); + const totalHours = Math.floor(totalMinutes / 60); + const days = Math.floor(totalHours / 24); + const hours = totalHours % 24; return hours > 0 ? `${days}d ${hours}h` : `${days}d`; }apps/web/app/api/user/stats/response-time/route.ts (1)
207-241: Use provider-agnostic sent-message detection.The hardcoded
"SENT"label is Gmail-specific and won't work correctly for Outlook. The fallback tosentMessageIdsis a workaround, but the proper solution is to use the provider'sisSentMessagemethod.Apply this diff to use provider-agnostic detection:
- const sentLabelId = "SENT"; - for (const sentMsg of sentMessages) { if (!sentMsg.threadId || processedThreads.has(sentMsg.threadId)) continue; processedThreads.add(sentMsg.threadId); try { const threadMessages = await emailProvider.getThreadMessages( sentMsg.threadId, ); // Sort by date ascending const sortedMessages = threadMessages.sort((a, b) => { const dateA = a.internalDate ? new Date(a.internalDate).getTime() : 0; const dateB = b.internalDate ? new Date(b.internalDate).getTime() : 0; return dateA - dateB; }); let lastReceivedMessage: { id: string; date: Date } | null = null; for (const message of sortedMessages) { if (!message.internalDate) continue; const messageDate = new Date(message.internalDate); - // Determine if message is sent or received - let isSent = false; - if (message.labelIds?.includes(sentLabelId)) { - isSent = true; - } - - // If we still haven't matched, fallback to checking if this specific message is in our known sent list - // (Only efficient if sentMessages is small, but we capped it at 100) - if (!isSent && sentMessageIds.has(message.id)) { - isSent = true; - } + // Use provider-agnostic sent message detection + const isSent = emailProvider.isSentMessage(message); if (isSent) {Based on learnings: Design email wrapper functions to be provider-agnostic to support multiple email providers.
🧹 Nitpick comments (1)
apps/web/app/api/user/stats/response-time/route.ts (1)
299-317: Summary statistics correctly computed.The calculations for median, average, and within-1-hour percentage are mathematically sound. The
previousPeriodComparisonis currently set tonullwith a TODO comment, which is an acceptable interim state until a non-recursive implementation is added.Consider implementing the previous period comparison in a future iteration to provide trend insights to users.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx(1 hunks)apps/web/app/api/user/stats/response-time/route.test.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/utils/email/google.ts(1 hunks)apps/web/utils/email/microsoft.ts(2 hunks)apps/web/utils/email/types.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (23)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include atitleelement for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
AssigntabIndexto non-interactive HTML elements witharia-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/utils/email/types.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Follow NextJS app router structure with (app) directory
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/api/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/*.ts: Wrap GET API routes withwithAuthorwithEmailAccountmiddleware for authentication
Export response types from GET API routes usingAwaited<ReturnType<>>pattern for type-safe client usage
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
apps/web/app/api/**/route.ts: Create GET API routes usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/app/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)
**/app/**/route.ts: Always wrap GET API route handlers withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, as the middleware handles error handling
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Use kebab-case for route directories in Next.js App Router (e.g.,
api/hello-world/route)
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,tsx}: API routes must usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
**/app/api/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
apps/web/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks over class components
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Use LoadingContent component for async data with loading and error states
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
apps/web/app/(app)/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)
apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put inpage.tsx, or in theapps/web/app/(app)/PAGE_NAMEfolder
If we're in a deeply nested component we will useswrto fetch via API
If you need to useonClickin a component, that component is a client component and file must start withuse client
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.tsx: Use theLoadingContentcomponent to handle loading states instead of manual loading state management
For text areas, use theInputcomponent withtype='text',autosizeTextareaprop set to true, andregisterPropsfor form integration
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
Don't use the return value of React.render
Make sure all dependencies are correctly specified in React hooks
Make sure all React hooks are called from the top level of component functions
Don't forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use bothchildrenanddangerouslySetInnerHTMLprops on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use<>...</>instead of<Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't usetarget="_blank"withoutrel="noopener"
Don't use<img>elements in Next.js projects
Don't use<head>elements in Next.js projects
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Usevitestfor testing the application
Tests should be colocated next to the tested file with.test.tsor.test.tsxextension (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and import the mock from@/utils/__mocks__/prisma
Usevi.clearAllMocks()inbeforeEachto clean up mocks between tests
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Do not mock the Logger
Avoid testing implementation details
Use test helpersgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor mocking emails, accounts, and rules
Files:
apps/web/app/api/user/stats/response-time/route.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests
Files:
apps/web/app/api/user/stats/response-time/route.test.ts
🧠 Learnings (25)
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/utils/email/types.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/utils/email/types.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls
Applied to files:
apps/web/utils/email/google.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/utils/email/google.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Keep Gmail provider-specific implementation details isolated within the apps/web/utils/gmail/ directory
Applied to files:
apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Create GET API routes using `withAuth` or `withEmailAccount` middleware in `apps/web/app/api/*/route.ts`, export response types as `GetExampleResponse` type alias for client-side type safety
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : User prompts must contain the actual data and context, and should be kept separate from system prompts
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use Date.now() to get milliseconds since the Unix Epoch
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Don't compare against -0
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use isNaN() when checking for NaN
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Design Gmail wrapper functions to be provider-agnostic to support future email providers like Outlook and ProtonMail
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Set timeout constant `const TIMEOUT = 15_000;` for LLM tests
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.test.ts : Include security tests in test suites to verify: authentication is required, IDOR protection works (other users cannot access resources), parameter validation rejects invalid inputs, and error messages don't leak information
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use vitest imports (`describe`, `expect`, `test`, `vi`, `beforeEach`) in LLM test files
Applied to files:
apps/web/app/api/user/stats/response-time/route.test.ts
🧬 Code graph analysis (5)
apps/web/utils/email/google.ts (2)
apps/web/utils/gmail/label.ts (1)
GmailLabel(20-34)apps/web/utils/gmail/message.ts (1)
getMessages(257-286)
apps/web/app/api/user/stats/response-time/route.ts (3)
apps/web/utils/middleware.ts (1)
withEmailProvider(426-439)apps/web/utils/email/types.ts (1)
EmailProvider(45-255)apps/web/utils/logger.ts (1)
Logger(5-5)
apps/web/utils/email/microsoft.ts (1)
apps/web/utils/outlook/retry.ts (1)
withOutlookRetry(19-80)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (7)
apps/web/app/api/user/stats/response-time/route.ts (2)
ResponseTimeParams(15-15)GetResponseTimeResponse(56-58)apps/web/hooks/useOrgSWR.ts (1)
useOrgSWR(10-45)apps/web/utils/types.ts (1)
isDefined(12-14)apps/web/components/ui/chart.tsx (1)
ChartConfig(11-19)apps/web/utils/colors.ts (1)
COLORS(25-37)apps/web/utils/string.ts (1)
pluralize(40-46)apps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx (1)
BarChart(27-192)
apps/web/app/api/user/stats/response-time/route.test.ts (1)
apps/web/app/api/user/stats/response-time/route.ts (3)
calculateResponseTimes(195-273)calculateSummaryStats(299-317)calculateDistribution(319-343)
⏰ 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). (3)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: test
- GitHub Check: Review for correctness
🔇 Additional comments (8)
apps/web/utils/email/types.ts (1)
74-78: LGTM!The new
getSentMessageIdsmethod signature is well-defined and aligns with both Gmail and Outlook provider implementations. The lightweight approach of returning onlyidandthreadIdis efficient for analytics use cases.apps/web/utils/email/google.ts (1)
187-209: LGTM!The implementation correctly constructs a Gmail search query with
label:SENTand optional date boundaries. The epoch-second conversion with boundary adjustments (±1 second) ensures inclusive date ranges, and the response filtering/mapping is clean.apps/web/app/api/user/stats/response-time/route.test.ts (1)
1-218: Excellent test coverage!The test suite thoroughly covers:
- Simple response-time calculation
- Multi-step conversation sequences
- Edge case handling (multiple sent messages, missing labels)
- Fallback to ID-based detection
- Summary and distribution calculations
The use of
getMockMessageHelperand proper mock setup demonstrates good testing practices.Based on learnings: Test structure follows the recommended patterns from
@/__tests__/helpersand uses vitest correctly.apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (1)
28-155: Well-structured component with proper data handling.The component correctly:
- Uses
useOrgSWRfor authenticated data fetching- Applies
useMemoto transform API data- Handles loading/error states with
LoadingContent- Filters undefined values with
isDefined- Renders empty state when no data is available
The integration with BarChart and proper use of formatters demonstrates good component design.
apps/web/app/api/user/stats/response-time/route.ts (4)
60-75: LGTM! Proper authentication and input validation.The route correctly:
- Uses
withEmailProvidermiddleware for authentication- Validates query parameters with Zod schema
- Scopes operations to the authenticated
emailAccountId- Returns responses using
NextResponse.json()As per coding guidelines: API routes must use appropriate middleware and validate all input parameters.
108-160: Well-implemented database caching strategy.The implementation efficiently:
- Checks for cached response times before computation
- Only processes uncached messages
- Uses
createManywithskipDuplicatesfor bulk inserts- Caps
responseTimeMsto prevent integer overflow- Properly scopes all queries to
emailAccountIdAs per coding guidelines: All database queries are correctly scoped to the authenticated user.
169-174: Date range filtering correctly applied.The implementation properly filters response times to the requested date range by checking
sentAtagainst the boundaries. The additional filtering after combining cached and new entries ensures accuracy when cached data may span a broader time range.
56-58: LGTM! Response type correctly exported.The response type is properly inferred using the
Awaited<ReturnType<typeof getResponseTimeStats>>pattern, ensuring type safety between the API route and client consumption.Based on learnings: Always export response types from GET routes using the
Awaited<ReturnType<>>pattern for type-safe client usage.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (3)
apps/web/app/api/user/stats/response-time/route.ts (1)
203-205: Use provider-awareemailProvider.isSentMessageinstead of hardcoded"SENT"labelSent/received detection is currently tied to a
"SENT"label and a fallback tosentMessageIds. That assumes Gmail-style labels and can misclassify messages for other providers or future implementations, even though theEmailProviderinterface already exposes anisSentMessagehook.You can simplify and make this logic provider-agnostic:
- const responseTimes: ResponseTimeEntry[] = []; - const processedThreads = new Set<string>(); - const sentMessageIds = new Set(sentMessages.map((m) => m.id)); - - const sentLabelId = "SENT"; + const responseTimes: ResponseTimeEntry[] = []; + const processedThreads = new Set<string>(); @@ - let lastReceivedMessage: { id: string; date: Date } | null = null; - - for (const message of sortedMessages) { - if (!message.internalDate) continue; - const messageDate = new Date(message.internalDate); - - // Determine if message is sent or received - let isSent = false; - if (message.labelIds?.includes(sentLabelId)) { - isSent = true; - } - - // If we still haven't matched, fallback to checking if this specific message is in our known sent list - // (Only efficient if sentMessages is small, but we capped it at 100) - if (!isSent && sentMessageIds.has(message.id)) { - isSent = true; - } - - if (isSent) { + let lastReceivedMessage: { id: string; date: Date } | null = null; + + for (const message of sortedMessages) { + if (!message.internalDate) continue; + const messageDate = new Date(message.internalDate); + + const isSent = emailProvider.isSentMessage(message); + + if (isSent) { // Message is SENT if (lastReceivedMessage) { @@ - } else { - // Message is RECEIVED - lastReceivedMessage = { id: message.id, date: messageDate }; - } + } else { + // Message is RECEIVED + lastReceivedMessage = { id: message.id, date: messageDate }; + }This centralizes provider-specific logic in the provider implementations and makes the analytics route robust across Gmail, Outlook, and future providers.
Also applies to: 207-241, 245-261
apps/web/utils/email/microsoft.ts (1)
239-276: Fix Sent Items scoping:parentFolderId eq 'sentitems'will not match any messages
parentFolderIdholds the folder GUID, so filtering with the literal'sentitems'will typically return no results. You’re already using the well‑known Sent Items endpoint elsewhere; this helper should do the same and keep only thesentDateTimefilters.Consider refactoring like this:
- const filters: string[] = ["parentFolderId eq 'sentitems'"]; - if (after) { - filters.push(`sentDateTime ge ${after.toISOString()}`); - } - if (before) { - filters.push(`sentDateTime le ${before.toISOString()}`); - } - - const response = await withOutlookRetry(() => - this.client - .getClient() - .api("/me/messages") - .select("id,conversationId") - .filter(filters.join(" and ")) - .top(maxResults) - .orderby("sentDateTime desc") - .get(), - ); + const filters: string[] = []; + if (after) { + filters.push(`sentDateTime ge ${after.toISOString()}`); + } + if (before) { + filters.push(`sentDateTime le ${before.toISOString()}`); + } + + const response = await withOutlookRetry(() => { + let request = this.client + .getClient() + .api("/me/mailFolders('sentitems')/messages") + .select("id,conversationId") + .top(maxResults) + .orderby("sentDateTime desc"); + + if (filters.length > 0) { + request = request.filter(filters.join(" and ")); + } + + return request.get(); + });This aligns with how you scope Sent Items in
getSentThreadsExcludingand ensures Outlook sent message IDs are actually returned.apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (1)
81-84: Include the actual email count in the “Response time data based on last …” sentence
pluralizeonly returns the word form, so the current text drops the numeric count (“based on last email/emails”). You likely want to show both the count and the correct plural.- <p className="text-muted-foreground text-sm"> - Response time data based on last{" "} - {pluralize(data.emailsAnalyzed, "email")} - </p> + <p className="text-muted-foreground text-sm"> + Response time data based on last{" "} + {data.emailsAnalyzed}{" "} + {pluralize(data.emailsAnalyzed, "email")} + </p>
🧹 Nitpick comments (4)
apps/web/prisma/schema.prisma (1)
167-167: ResponseTime model and relation look consistent with route usageThe
ResponseTimeschema andEmailAccount.responseTimesrelation align with how the API queries and stores response times (byemailAccountId + sentMessageIdandsentAt). The explicit Int32 cap in the route avoids overflow at the Prisma/Postgres layer.If you ever care about tracking very long‑running conversations (responses > ~24 days), consider switching
responseTimeMstoBigIntso you don’t have to clamp values in application code, but this isn’t strictly required for the current feature set.Also applies to: 709-724
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (2)
32-37: Avoid unsafe cast when building query string for SWR key
ResponseTimeParamscan containnumber | null | undefined, but you cast it directly toRecord<string, string>forURLSearchParams. It works at runtime, but it’s type-unsafe and doesn’t explicitly drop nullish values.A small refactor makes the types and behavior clearer:
- const params: ResponseTimeParams = getDateRangeParams(dateRange); - - const { data, isLoading, error } = useOrgSWR<GetResponseTimeResponse>( - `/api/user/stats/response-time?${new URLSearchParams(params as Record<string, string>)}`, - { refreshInterval }, - ); + const params: ResponseTimeParams = getDateRangeParams(dateRange); + const searchParams = new URLSearchParams(); + if (params.fromDate != null) { + searchParams.set("fromDate", String(params.fromDate)); + } + if (params.toDate != null) { + searchParams.set("toDate", String(params.toDate)); + } + + const { data, isLoading, error } = useOrgSWR<GetResponseTimeResponse>( + `/api/user/stats/response-time?${searchParams.toString()}`, + { refreshInterval }, + );
87-104: Make summary cards grid responsive for small screens
grid-cols-3at all breakpoints will squeeze three cards side‑by‑side on mobile. Tailwind’s mobile‑first pattern would typically start at 1 column and fan out on larger screens.- <div className="grid gap-2 sm:gap-4 grid-cols-3"> + <div className="grid grid-cols-1 gap-2 sm:gap-4 md:grid-cols-3">This keeps the layout readable on narrow viewports while preserving the 3‑column layout on desktop.
apps/web/app/api/user/stats/response-time/route.ts (1)
49-54: AlignTrendEntry.periodDatetype with JSON-serialized value
TrendEntry.periodDateis typed asDate, andcalculateTrendreturns an actualDateobject, butNextResponse.jsonwill serialize that to a string. On the client,GetResponseTimeResponse["trend"][i].periodDatewill therefore be a string at runtime despite being typed asDate, which can lead to subtle bugs if it’s ever used.Two low-friction options:
- Change the type to
stringand serialize explicitly (e.g.periodDate: format(date, "yyyy-MM-dd")ordate.toISOString()), or- Drop
periodDatefrom the API response and keep it as an internal helper for sorting.Right now the client only uses
period, so adjusting the type/shape here should be safe and will make the contract more accurate.Also applies to: 345-370
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/prisma/migrations/20251207172822_response_time/migration.sql(1 hunks)apps/web/prisma/schema.prisma(2 hunks)apps/web/utils/email/microsoft.ts(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/prisma/migrations/20251207172822_response_time/migration.sql
🧰 Additional context used
📓 Path-based instructions (22)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
apps/web/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Follow NextJS app router structure with (app) directory
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.ts
apps/web/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks over class components
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Use LoadingContent component for async data with loading and error states
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
apps/web/app/(app)/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)
apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put inpage.tsx, or in theapps/web/app/(app)/PAGE_NAMEfolder
If we're in a deeply nested component we will useswrto fetch via API
If you need to useonClickin a component, that component is a client component and file must start withuse client
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.tsx: Use theLoadingContentcomponent to handle loading states instead of manual loading state management
For text areas, use theInputcomponent withtype='text',autosizeTextareaprop set to true, andregisterPropsfor form integration
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include atitleelement for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
AssigntabIndexto non-interactive HTML elements witharia-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
Don't use the return value of React.render
Make sure all dependencies are correctly specified in React hooks
Make sure all React hooks are called from the top level of component functions
Don't forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use bothchildrenanddangerouslySetInnerHTMLprops on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use<>...</>instead of<Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't usetarget="_blank"withoutrel="noopener"
Don't use<img>elements in Next.js projects
Don't use<head>elements in Next.js projects
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.tsapps/web/prisma/schema.prisma
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsxapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
apps/web/app/api/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/*.ts: Wrap GET API routes withwithAuthorwithEmailAccountmiddleware for authentication
Export response types from GET API routes usingAwaited<ReturnType<>>pattern for type-safe client usage
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
apps/web/app/api/**/route.ts: Create GET API routes usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/app/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)
**/app/**/route.ts: Always wrap GET API route handlers withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, as the middleware handles error handling
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
apps/web/app/**/[!.]*/route.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Use kebab-case for route directories in Next.js App Router (e.g.,
api/hello-world/route)
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,tsx}: API routes must usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/app/api/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/prisma/schema.prisma
📄 CodeRabbit inference engine (.cursor/rules/prisma.mdc)
Use PostgreSQL as the database system with Prisma
Files:
apps/web/prisma/schema.prisma
🧠 Learnings (21)
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : User prompts must contain the actual data and context, and should be kept separate from system prompts
Applied to files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use static Response methods instead of new Response() constructor when possible
Applied to files:
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Create GET API routes using `withAuth` or `withEmailAccount` middleware in `apps/web/app/api/*/route.ts`, export response types as `GetExampleResponse` type alias for client-side type safety
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : Use Zod schemas for request body validation in API routes
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Wrap GET API routes with `withAuth` or `withEmailAccount` middleware for authentication
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use Date.now() to get milliseconds since the Unix Epoch
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Don't compare against -0
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use isNaN() when checking for NaN
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Design Gmail wrapper functions to be provider-agnostic to support future email providers like Outlook and ProtonMail
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls
Applied to files:
apps/web/utils/email/microsoft.ts
🧬 Code graph analysis (1)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx (7)
apps/web/app/api/user/stats/response-time/route.ts (2)
ResponseTimeParams(15-15)GetResponseTimeResponse(56-58)apps/web/hooks/useOrgSWR.ts (1)
useOrgSWR(10-45)apps/web/utils/types.ts (1)
isDefined(12-14)apps/web/components/ui/chart.tsx (1)
ChartConfig(11-19)apps/web/utils/colors.ts (1)
COLORS(25-37)apps/web/utils/string.ts (1)
pluralize(40-46)apps/web/app/(app)/[emailAccountId]/stats/BarChart.tsx (1)
BarChart(27-192)
⏰ 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)
- GitHub Check: Review for correctness
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/web/utils/ai/report/fetch.ts (1)
57-62: LGTM! Cleaner sent message retrieval.The simplified approach using
getSentMessagesdirectly is more maintainable than the previousgetMessagesByFields-based logic.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx(1 hunks)apps/web/app/api/user/stats/day/route.ts(0 hunks)apps/web/app/api/user/stats/response-time/calculate.test.ts(1 hunks)apps/web/app/api/user/stats/response-time/calculate.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/app/api/user/stats/route.ts(0 hunks)apps/web/utils/__mocks__/email-provider.ts(1 hunks)apps/web/utils/ai/choose-rule/bulk-process-emails.ts(1 hunks)apps/web/utils/ai/report/fetch.ts(1 hunks)apps/web/utils/email/google.ts(2 hunks)apps/web/utils/email/microsoft.ts(4 hunks)apps/web/utils/email/types.ts(1 hunks)apps/web/utils/outlook/client.ts(1 hunks)
💤 Files with no reviewable changes (2)
- apps/web/app/api/user/stats/route.ts
- apps/web/app/api/user/stats/day/route.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/app/(app)/[emailAccountId]/stats/ResponseTimeAnalytics.tsx
🧰 Additional context used
📓 Path-based instructions (21)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include atitleelement for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
AssigntabIndexto non-interactive HTML elements witharia-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/outlook/client.tsapps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
apps/web/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Follow NextJS app router structure with (app) directory
Files:
apps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/*.ts: Wrap GET API routes withwithAuthorwithEmailAccountmiddleware for authentication
Export response types from GET API routes usingAwaited<ReturnType<>>pattern for type-safe client usage
Files:
apps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,tsx}: API routes must usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Files:
apps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.ts
**/app/api/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Files:
apps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Usevitestfor testing the application
Tests should be colocated next to the tested file with.test.tsor.test.tsxextension (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and import the mock from@/utils/__mocks__/prisma
Usevi.clearAllMocks()inbeforeEachto clean up mocks between tests
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Do not mock the Logger
Avoid testing implementation details
Use test helpersgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor mocking emails, accounts, and rules
Files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests
Files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
LLM-related code must be organized in specific directories:
apps/web/utils/ai/for main implementations,apps/web/utils/llms/for core utilities and configurations, andapps/web/__tests__/for LLM-specific tests
Files:
apps/web/utils/ai/report/fetch.tsapps/web/utils/ai/choose-rule/bulk-process-emails.ts
apps/web/utils/ai/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
apps/web/utils/ai/**/*.ts: LLM feature functions must import fromzodfor schema validation, usecreateScopedLoggerfrom@/utils/logger,chatCompletionObjectandcreateGenerateObjectfrom@/utils/llms, and importEmailAccountWithAItype from@/utils/llms/types
LLM feature functions must follow a standard structure: accept options withinputDataandemailAccountparameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and usecreateGenerateObjectto execute the LLM call
System prompts must define the LLM's role and task specifications
User prompts must contain the actual data and context, and should be kept separate from system prompts
Always define a Zod schema for LLM response validation and make schemas as specific as possible to guide the LLM output
Use descriptive scoped loggers for each LLM feature, log inputs and outputs with appropriate log levels, and include relevant context in log messages
Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures usingwithRetry
Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Use TypeScript types for all LLM function parameters and return values, and define clear interfaces for complex input/output structures
Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments
Files:
apps/web/utils/ai/report/fetch.tsapps/web/utils/ai/choose-rule/bulk-process-emails.ts
apps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
apps/web/app/api/**/route.ts: Create GET API routes usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/app/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)
**/app/**/route.ts: Always wrap GET API route handlers withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, as the middleware handles error handling
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Use kebab-case for route directories in Next.js App Router (e.g.,
api/hello-world/route)
Files:
apps/web/app/api/user/stats/response-time/route.ts
🧠 Learnings (31)
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : System prompts must define the LLM's role and task specifications
Applied to files:
apps/web/utils/outlook/client.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers
Applied to files:
apps/web/utils/__mocks__/email-provider.tsapps/web/app/api/user/stats/response-time/calculate.test.tsapps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Mock 'server-only' module with empty object in LLM test files: `vi.mock("server-only", () => ({}))`
Applied to files:
apps/web/utils/__mocks__/email-provider.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Mock `server-only` using `vi.mock("server-only", () => ({}))`
Applied to files:
apps/web/utils/__mocks__/email-provider.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Mock Prisma using `vi.mock("@/utils/prisma")` and import the mock from `@/utils/__mocks__/prisma`
Applied to files:
apps/web/utils/__mocks__/email-provider.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use `vi.clearAllMocks()` in `beforeEach` to clean up mocks between tests
Applied to files:
apps/web/utils/__mocks__/email-provider.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Set timeout constant `const TIMEOUT = 15_000;` for LLM tests
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use vitest imports (`describe`, `expect`, `test`, `vi`, `beforeEach`) in LLM test files
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.test.ts : Include security tests in test suites to verify: authentication is required, IDOR protection works (other users cannot access resources), parameter validation rejects invalid inputs, and error messages don't leak information
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use descriptive test names
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls
Applied to files:
apps/web/utils/ai/report/fetch.tsapps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Keep Gmail provider-specific implementation details isolated within the apps/web/utils/gmail/ directory
Applied to files:
apps/web/utils/email/types.tsapps/web/utils/email/google.tsapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Create GET API routes using `withAuth` or `withEmailAccount` middleware in `apps/web/app/api/*/route.ts`, export response types as `GetExampleResponse` type alias for client-side type safety
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Wrap GET API routes with `withAuth` or `withEmailAccount` middleware for authentication
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use Date.now() to get milliseconds since the Unix Epoch
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Don't compare against -0
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use isNaN() when checking for NaN
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Design Gmail wrapper functions to be provider-agnostic to support future email providers like Outlook and ProtonMail
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/utils/email/microsoft.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
🧬 Code graph analysis (5)
apps/web/utils/ai/report/fetch.ts (1)
apps/web/utils/email/types.ts (1)
EmailProvider(45-253)
apps/web/utils/email/types.ts (1)
apps/web/utils/types.ts (1)
ParsedMessage(51-73)
apps/web/utils/email/google.ts (4)
apps/web/utils/types.ts (1)
ParsedMessage(51-73)apps/web/utils/gmail/message.ts (2)
queryBatchMessages(294-326)getMessages(257-286)apps/web/utils/gmail/label.ts (1)
GmailLabel(20-34)apps/web/utils/email/microsoft.ts (1)
getMessages(187-220)
apps/web/app/api/user/stats/response-time/calculate.ts (2)
apps/web/utils/email/types.ts (1)
EmailProvider(45-253)apps/web/utils/logger.ts (1)
Logger(5-5)
apps/web/app/api/user/stats/response-time/route.ts (4)
apps/web/utils/middleware.ts (1)
withEmailProvider(426-439)apps/web/utils/email/types.ts (1)
EmailProvider(45-253)apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/app/api/user/stats/response-time/calculate.ts (4)
SummaryStats(15-23)DistributionStats(25-32)ResponseTimeEntry(5-13)calculateResponseTimes(58-136)
⏰ 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: test
- GitHub Check: Review for correctness
🔇 Additional comments (20)
apps/web/utils/outlook/client.ts (1)
237-237: Good addition for explicit account selection.Adding
prompt: "select_account"ensures users explicitly choose which Microsoft account to link, preventing accidental linking of the wrong account when users have multiple accounts signed in.apps/web/utils/email/types.ts (1)
71-76: LGTM! Well-designed API additions.The new
getInboxMessagesandgetSentMessageIdsmethods provide a clean interface for fetching inbox messages and lightweight sent message identifiers. The distinction between full message retrieval and ID-only retrieval is a good performance optimization.apps/web/utils/email/google.ts (2)
188-194: LGTM! Clean implementation using existing utilities.The
getInboxMessagesmethod correctly usesqueryBatchMessageswith the appropriate inbox query.
196-218: LGTM! Efficient implementation with proper date filtering.The
getSentMessageIdsmethod:
- Builds a proper Gmail query with the SENT label
- Correctly converts dates to Unix timestamps with inclusive boundaries
- Uses
getMessages(notqueryBatchMessages) for efficiency since only IDs are needed- Filters out incomplete results
apps/web/app/api/user/stats/response-time/calculate.ts (3)
34-56: LGTM! Well-implemented helper functions.The
msToMinutes,calculateMedian,calculateAverage, andcalculateWithin1Hourfunctions are correctly implemented with proper edge case handling (empty arrays return 0).
138-156: LGTM! Proper statistical calculations with placeholder for future work.The
calculateSummaryStatsfunction correctly computes median, average, and within-1-hour percentage. The TODO note for previous-period comparison is appropriately documented.
158-182: LGTM! Clear time bucketing logic.The
calculateDistributionfunction properly buckets response times into well-defined ranges with clear thresholds (60 min, 240 min, 1440 min, etc.).apps/web/utils/__mocks__/email-provider.ts (1)
72-72: LGTM! Consistent mock implementation.The
getInboxMessagesmock follows the same pattern as other message-fetching mocks and provides a sensible default empty array.apps/web/utils/ai/choose-rule/bulk-process-emails.ts (1)
32-41: LGTM! Correct adaptation to new API.The change from
getMessagesByFieldstogetInboxMessagescorrectly updates the destructuring pattern from[{ messages }, rules]to[messages, rules]to match the new return type.apps/web/app/api/user/stats/response-time/calculate.test.ts (2)
14-181: LGTM! Comprehensive test coverage.The test suite covers key scenarios:
- Simple received → sent reply pairs
- Multi-message sequences with correct pairing logic
- Handling of multiple consecutive sent messages
- Fallback when SENT label is missing
- Clear test names and inline documentation
Well-structured and thorough testing.
183-217: LGTM! Statistics and distribution tests.The tests for
calculateSummaryStatsandcalculateDistributionverify correct median, average, percentage, and bucketing calculations with representative data.apps/web/app/api/user/stats/response-time/route.ts (4)
39-54: LGTM! Proper middleware usage and parameter parsing.The route correctly uses
withEmailProvidermiddleware for authentication and email account scoping. The Zod schema parsing ensures type safety for query parameters.
87-139: LGTM! Efficient caching strategy.The implementation:
- Checks for cached entries before computing
- Filters to uncached messages only
- Stores new calculations with
skipDuplicates- Caps response times to prevent integer overflow
This provides good performance optimization for repeated queries.
177-202: LGTM! Clear trend calculation by week.The
calculateTrendfunction properly groups response times by week, calculates median per week, and returns sorted results with formatted dates.
204-224: LGTM! Sensible empty state.The
getEmptyStatshelper returns properly structured zero values when no data is available, ensuring consistent response shape.apps/web/utils/email/microsoft.ts (5)
68-68: LGTM!The import of
withOutlookRetryis appropriate for adding resilience to Graph API calls.
225-238: LGTM!The refactored
getSentMessagescorrectly usessentDateTimefor ordering sent items and wraps the call with retry logic.
240-256: LGTM!The new
getInboxMessagesmethod correctly usesreceivedDateTimefor ordering inbox messages and follows the same resilient pattern asgetSentMessages.
258-297: LGTM! Past issues resolved.The implementation correctly uses
sentDateTimefor filtering and ordering sent items, and properly uses the/me/mailFolders('sentitems')/messagesendpoint. The past review concerns about usingreceivedDateTimeandparentFolderIdfiltering have been addressed.
335-335: LGTM!Correctly uses
sentDateTimefor ordering sent items, consistent with other sent items queries in this file.
| ...(fromDate ? { after: new Date(fromDate) } : {}), | ||
| ...(toDate ? { before: new Date(toDate) } : {}), |
There was a problem hiding this comment.
Handle Unix epoch (0) correctly in date filters.
Using truthy checks (fromDate ?) will incorrectly skip 0 (Unix epoch), treating it as missing rather than a valid timestamp. This affects both the API call here and the filtering on lines 150-151.
Apply this diff:
const sentMessages = await emailProvider.getSentMessageIds({
maxResults: MAX_SENT_MESSAGES,
- ...(fromDate ? { after: new Date(fromDate) } : {}),
- ...(toDate ? { before: new Date(toDate) } : {}),
+ ...(fromDate != null ? { after: new Date(fromDate) } : {}),
+ ...(toDate != null ? { before: new Date(toDate) } : {}),
});Also update the filtering logic:
const allEntries = combinedEntries.filter((entry) => {
const sentTime = entry.sentAt.getTime();
- if (fromDate && sentTime < fromDate) return false;
- if (toDate && sentTime > toDate) return false;
+ if (fromDate != null && sentTime < fromDate) return false;
+ if (toDate != null && sentTime > toDate) return false;
return true;
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ...(fromDate ? { after: new Date(fromDate) } : {}), | |
| ...(toDate ? { before: new Date(toDate) } : {}), | |
| ...(fromDate != null ? { after: new Date(fromDate) } : {}), | |
| ...(toDate != null ? { before: new Date(toDate) } : {}), |
| count: number; | ||
| } | ||
|
|
||
| export type GetResponseTimeResponse = Awaited< |
There was a problem hiding this comment.
GetResponseTimeResponse exposes trend[].periodDate as Date, but NextResponse.json(...) serializes it to a string. This leaks an incorrect contract to clients. Consider updating the exported API type to use string for periodDate (or stringify before returning) to keep types and payload aligned.
| export type GetResponseTimeResponse = Awaited< | |
| export type GetResponseTimeResponse = { | |
| summary: SummaryStats; | |
| distribution: DistributionStats; | |
| trend: Array<Omit<TrendEntry, "periodDate"> & { periodDate: string }>; | |
| emailsAnalyzed: number; | |
| maxEmailsCap: number; | |
| }; |
🚀 Reply to ask Macroscope to explain or update this suggestion.
👍 Helpful? React to give us feedback.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
apps/web/app/api/user/stats/response-time/route.ts (1)
19-22: Harden date query parsing and avoid truthy checks forfromDate/toDate
z.coerce.number().nullish()will happily produceNaNfor bad query strings, and the downstream truthy checks (fromDate ? ...) both (a) ignore a valid Unix epoch0and (b) letNaNslip through as “no filter”, while still being passed intonew Date(fromDate).To make this robust and respect
0:
- Normalize/validate the parsed numbers so invalid values become
null(or cause a 400), and- Replace truthy checks with explicit null checks where you build
after/beforeand where you filterallEntries.For example:
-const responseTimeSchema = z.object({ - fromDate: z.coerce.number().nullish(), - toDate: z.coerce.number().nullish(), -}); +const responseTimeSchema = z.object({ + fromDate: z + .coerce.number() + .transform((v) => (Number.isNaN(v) ? null : v)) + .nullable(), + toDate: z + .coerce.number() + .transform((v) => (Number.isNaN(v) ? null : v)) + .nullable(), +}); @@ const sentMessages = await emailProvider.getSentMessageIds({ maxResults: MAX_SENT_MESSAGES, - ...(fromDate ? { after: new Date(fromDate) } : {}), - ...(toDate ? { before: new Date(toDate) } : {}), + ...(fromDate != null ? { after: new Date(fromDate) } : {}), + ...(toDate != null ? { before: new Date(toDate) } : {}), }); @@ const allEntries = combinedEntries.filter((entry) => { const sentTime = entry.sentAt.getTime(); - if (fromDate && sentTime < fromDate) return false; - if (toDate && sentTime > toDate) return false; + if (fromDate != null && sentTime < fromDate) return false; + if (toDate != null && sentTime > toDate) return false; return true; });This prevents
Invalid Dateflows from bad params and ensures0is treated as a valid timestamp rather than “missing”.Also applies to: 73-77, 144-148
apps/web/app/api/user/stats/response-time/calculate.ts (1)
55-66: Use provider-agnosticemailProvider.isSentMessageinstead of hardcoded"SENT"Sent/received detection is currently tied to the Gmail
"SENT"label with an ID fallback:
- This fails for providers that don’t use Gmail-style labels and can misclassify older sent messages as received, corrupting response-time pairing.
- The
EmailProviderinterface already exposesisSentMessage(message), intended to encapsulate provider-specific logic.Switch to
emailProvider.isSentMessageas the primary check and keep thesentMessageIdsset only as a safety net for messages we know came from the sent-list. For example:- const sentLabelId = "SENT"; - for (const sentMsg of sentMessages) { @@ - for (const message of sortedMessages) { + for (const message of sortedMessages) { @@ - // Determine if message is sent or received - let isSent = false; - if (message.labelIds?.includes(sentLabelId)) { - isSent = true; - } - - // If we still haven't matched, fallback to checking if this specific message is in our known sent list - // (Only efficient if sentMessages is small, but we capped it at 100) - if (!isSent && sentMessageIds.has(message.id)) { - isSent = true; - } + // Determine if message is sent or received in a provider-agnostic way + const isSent = + emailProvider.isSentMessage(message) || sentMessageIds.has(message.id);You’ll also want to extend the tests’
mockEmailProviderto provide anisSentMessageimplementation that mirrors the desired behavior.Also applies to: 67-102
🧹 Nitpick comments (2)
apps/web/app/api/user/stats/response-time/calculate.test.ts (1)
16-23: Tighten email provider mock typing and prepare forisSentMessageusage
mockEmailProvideris typed asanyand only stubsgetThreadMessages; as we rely more onEmailProvider(e.g.,isSentMessage), this will silently break tests instead of failing at compile time. Consider typing the mock toPartial<EmailProvider>and adding anisSentMessagestub to lock tests to the provider contract and keep them valid if detection logic changes.Also applies to: 25-64
apps/web/app/api/user/stats/response-time/calculate.ts (1)
69-77: Avoidawaitin the per-thread loop to reduce latency
getThreadMessagesis awaited inside afor ... ofloop, so up to 50 thread fetches run strictly sequentially. That increases latency and conflicts with the project guideline to avoidawaitin loops.Consider batching thread fetches with controlled concurrency, e.g.:
const threadsToProcess = sentMessages .filter((m) => m.threadId && !processedThreads.has(m.threadId)); const results = await Promise.all( threadsToProcess.map(async (sentMsg) => { processedThreads.add(sentMsg.threadId!); try { const threadMessages = await emailProvider.getThreadMessages(sentMsg.threadId!); // existing sorting + pairing logic return { ok: true }; } catch (error) { logger.error(`Failed to process thread ${sentMsg.threadId}`, { error }); return { ok: false }; } }), );This keeps behavior the same while allowing parallelism (you can also introduce a concurrency limiter if needed).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
apps/web/app/api/user/stats/response-time/calculate.test.ts(1 hunks)apps/web/app/api/user/stats/response-time/calculate.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/prisma/migrations/20251209071346_response_time_mins/migration.sql(1 hunks)apps/web/prisma/schema.prisma(2 hunks)apps/web/utils/internal-api.ts(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- apps/web/prisma/migrations/20251209071346_response_time_mins/migration.sql
🧰 Additional context used
📓 Path-based instructions (20)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include atitleelement for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
AssigntabIndexto non-interactive HTML elements witharia-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/prisma/schema.prismaapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/internal-api.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
apps/web/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Follow NextJS app router structure with (app) directory
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
apps/web/app/api/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/*.ts: Wrap GET API routes withwithAuthorwithEmailAccountmiddleware for authentication
Export response types from GET API routes usingAwaited<ReturnType<>>pattern for type-safe client usage
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
apps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
apps/web/app/api/**/route.ts: Create GET API routes usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
Files:
apps/web/app/api/user/stats/response-time/route.ts
**/app/**/route.ts
📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)
**/app/**/route.ts: Always wrap GET API route handlers withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, as the middleware handles error handling
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Use kebab-case for route directories in Next.js App Router (e.g.,
api/hello-world/route)
Files:
apps/web/app/api/user/stats/response-time/route.ts
apps/web/app/api/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,tsx}: API routes must usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/app/api/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.tsapps/web/app/api/user/stats/response-time/calculate.test.ts
**/prisma/schema.prisma
📄 CodeRabbit inference engine (.cursor/rules/prisma.mdc)
Use PostgreSQL as the database system with Prisma
Files:
apps/web/prisma/schema.prisma
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Usevitestfor testing the application
Tests should be colocated next to the tested file with.test.tsor.test.tsxextension (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and import the mock from@/utils/__mocks__/prisma
Usevi.clearAllMocks()inbeforeEachto clean up mocks between tests
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Do not mock the Logger
Avoid testing implementation details
Use test helpersgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor mocking emails, accounts, and rules
Files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests
Files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
🧠 Learnings (24)
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Create GET API routes using `withAuth` or `withEmailAccount` middleware in `apps/web/app/api/*/route.ts`, export response types as `GetExampleResponse` type alias for client-side type safety
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/app/api/**/*.ts : Wrap GET API routes with `withAuth` or `withEmailAccount` middleware for authentication
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use Date.now() to get milliseconds since the Unix Epoch
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Don't compare against -0
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use isNaN() when checking for NaN
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Design Gmail wrapper functions to be provider-agnostic to support future email providers like Outlook and ProtonMail
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/calculate.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Set timeout constant `const TIMEOUT = 15_000;` for LLM tests
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use vitest imports (`describe`, `expect`, `test`, `vi`, `beforeEach`) in LLM test files
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use descriptive test names
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.test.ts : Include security tests in test suites to verify: authentication is required, IDOR protection works (other users cannot access resources), parameter validation rejects invalid inputs, and error messages don't leak information
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/app/api/user/stats/response-time/calculate.test.ts
🧬 Code graph analysis (4)
apps/web/utils/internal-api.ts (1)
apps/web/env.ts (1)
env(17-247)
apps/web/app/api/user/stats/response-time/route.ts (4)
apps/web/utils/middleware.ts (1)
withEmailProvider(426-439)apps/web/utils/email/types.ts (1)
EmailProvider(45-253)apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/app/api/user/stats/response-time/calculate.ts (7)
SummaryStats(15-23)DistributionStats(25-32)ResponseTimeEntry(5-13)calculateResponseTimes(55-133)calculateSummaryStats(135-153)calculateDistribution(155-179)calculateMedian(181-181)
apps/web/app/api/user/stats/response-time/calculate.ts (2)
apps/web/utils/email/types.ts (1)
EmailProvider(45-253)apps/web/utils/logger.ts (1)
Logger(5-5)
apps/web/app/api/user/stats/response-time/calculate.test.ts (1)
apps/web/app/api/user/stats/response-time/calculate.ts (3)
calculateResponseTimes(55-133)calculateSummaryStats(135-153)calculateDistribution(155-179)
⏰ 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). (3)
- GitHub Check: test
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Review for correctness
🔇 Additional comments (2)
apps/web/utils/internal-api.ts (1)
6-8: No action required—the fallback chain correctly excludesWEBHOOK_URL.The removal is already applied and correct.
WEBHOOK_URLis used for external webhook functionality inoutlook/watch.ts, not internal API calls. The current fallback chain (INTERNAL_API_URL→NEXT_PUBLIC_BASE_URL) properly separates concerns and has no impact on deployments.apps/web/prisma/schema.prisma (1)
167-167: ResponseTime model and relation look consistent with usageThe
ResponseTimemodel shape (minutes-based duration, timestamps, and IDs) plus theresponseTimesrelation onEmailAccount, unique(emailAccountId, sentMessageId)constraint, andemailAccountId,sentAtindex align well with the read/write patterns in the new API route and should scale reasonably for date-scoped queries.Also applies to: 709-724
| }): Promise<{ id: string; threadId: string }[]> { | ||
| const { maxResults, after, before } = options; | ||
|
|
||
| let query = `label:${GmailLabel.SENT}`; |
There was a problem hiding this comment.
The search query uses label:${GmailLabel.SENT} (API label ID) instead of Gmail search syntax. This can return no results. Consider using in:sent (or label:sent) to reliably match sent mail.
| let query = `label:${GmailLabel.SENT}`; | |
| let query = `in:sent`; |
🚀 Reply to ask Macroscope to explain or update this suggestion.
👍 Helpful? React to give us feedback.
Summary by CodeRabbit
New Features
Database
Improvements
Tests
Chores
✏️ Tip: You can customize this high-level summary in your review settings.