Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. 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 timezone-aware calendar availability and user-timezone selection for AI scheduling, updates logger.trace for lazy argument evaluation, uses lazy tracing in rule runner, removes an exported generateDraft helper, adds AI calendar-availability tests, and adds the date-fns-tz dependency. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant AI as aiGetCalendarAvailability
participant DB as Prisma/CalendarConnections
participant Cal as getCalendarAvailability
participant L as Logger
User->>AI: Request scheduling suggestions for thread
AI->>DB: Query calendar connections (select calendarId, timezone, primary)
DB-->>AI: Connections + timezones
AI->>AI: Determine userTimezone (primary → any with tz → UTC)
AI->>L: trace("Determined timezone", () => { userTimezone })
AI->>Cal: getCalendarAvailability({ start,end, timezone: userTimezone })
Cal->>L: trace("TZ-aware request", () => { inputDates, timeMin, timeMax, timezone })
Cal-->>AI: Busy periods (UTC normalized)
AI->>AI: Build prompt with TIMEZONE CONTEXT
AI-->>User: Suggested times (adjusted to userTimezone)
sequenceDiagram
autonumber
participant Code as Caller
participant Log as logger.trace
Code->>Log: trace("message", () => computeExpensiveArgs())
alt Debug disabled
Log-->>Code: Skip evaluation (no args resolved)
else Debug enabled
Log->>Log: Invoke function to resolve args
Log-->>Code: Emit trace with resolved args
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (3)
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.
Additional Comments:
apps/web/tests/ai-process-user-request.test.ts (line 5):
Import path is outdated after the type was moved to a new location, causing a compilation error.
View Details
📝 Patch Details
diff --git a/apps/web/__tests__/ai-process-user-request.test.ts b/apps/web/__tests__/ai-process-user-request.test.ts
index fb643957a..7446e7bc0 100644
--- a/apps/web/__tests__/ai-process-user-request.test.ts
+++ b/apps/web/__tests__/ai-process-user-request.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test, vi } from "vitest";
import stripIndent from "strip-indent";
import { processUserRequest } from "@/utils/ai/assistant/process-user-request";
import type { ParsedMessage, ParsedMessageHeaders } from "@/utils/types";
-import type { RuleWithRelations } from "@/utils/ai/rule/create-prompt-from-rule";
+import type { RuleWithRelations } from "@/utils/rule/types";
import type { Category, GroupItem, Prisma } from "@prisma/client";
import { GroupItemType, LogicalOperator } from "@prisma/client";
import { getEmailAccount } from "@/__tests__/helpers";
Analysis
Outdated import path causes TypeScript compilation error in test file
What fails: The test file apps/web/__tests__/ai-process-user-request.test.ts imports RuleWithRelations from a non-existent module path @/utils/ai/rule/create-prompt-from-rule, causing TypeScript compilation to fail.
How to reproduce:
cd apps/web && npx tsc --noEmit __tests__/ai-process-user-request.test.tsResult:
error TS2307: Cannot find module '@/utils/ai/rule/create-prompt-from-rule' or its corresponding type declarations.
Expected: The import should resolve successfully to the correct location where RuleWithRelations is now defined, matching the pattern used by other files like utils/ai/assistant/process-user-request.ts and utils/rule/rule-history.ts which both import from @/utils/rule/types.
Details: The create-prompt-from-rule.ts file no longer exists in the codebase, and the RuleWithRelations type has been moved to @/utils/rule/types.ts. The test file was missed during the migration and still references the old path.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
apps/web/utils/ai/calendar/availability.ts (2)
134-153: Bug: querying all calendars with each connection’s token (auth errors, duplication).Inside the per‑connection loop you build calendarIds from all connections, then call getCalendarAvailability with those IDs using the current connection’s tokens. This will fail or duplicate work when tokens can’t access other accounts’ calendars.
Apply this diff:
- const promises = calendarConnections.map( - async (calendarConnection) => { - const calendarIds = calendarConnections.flatMap((conn) => - conn.calendars.map((cal) => cal.calendarId), - ); + const promises = calendarConnections.map( + async (calendarConnection) => { + const calendarIds = calendarConnection.calendars.map( + (cal) => cal.calendarId, + ); if (!calendarIds.length) return; try { const availabilityData = await getCalendarAvailability({ accessToken: calendarConnection.accessToken, refreshToken: calendarConnection.refreshToken, expiresAt: calendarConnection.expiresAt?.getTime() || null, emailAccountId: emailAccount.id, calendarIds, startDate, endDate, timezone: userTimezone, }); - logger.trace("Calendar availability data", { - availabilityData, - }); + logger.trace("Calendar availability data", () => ({ + calendars: calendarIds.length, + periods: availabilityData?.length ?? 0, + })); return availabilityData; } catch (error) { logger.error("Error checking calendar availability", { error }); } }, );
130-133: Validate tool input dates before use.Guard against “Invalid Date” to avoid downstream errors.
Suggested change:
- const startDate = new Date(timeMin); - const endDate = new Date(timeMax); + const startDate = new Date(timeMin); + const endDate = new Date(timeMax); + if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) { + logger.warn("Invalid time range for availability tool", { + timeMin, + timeMax, + }); + return { busyPeriods: [] }; + }apps/web/utils/logger.ts (1)
78-85: Axiom trace doesn’t evaluate thunks.Evaluate when a function is provided so underlying logger receives the object.
Apply:
- trace: ( - message: string, - args?: Record<string, unknown> | (() => Record<string, unknown>), - ) => { - if (env.ENABLE_DEBUG_LOGS) { - log.debug(message, { scope, ...fields, ...args }); - } - }, + trace: ( + message: string, + args?: Record<string, unknown> | (() => Record<string, unknown>), + ) => { + if (!env.ENABLE_DEBUG_LOGS) return; + const payload = typeof args === "function" ? args() : args ?? {}; + log.debug(message, { scope, ...fields, ...payload }); + },
🧹 Nitpick comments (4)
apps/web/utils/ai/calendar/availability.ts (1)
183-211: Helper is fine; consider future extension.If you later store a user‑preferred timezone on EmailAccount/User, check it first, then fall back to calendars.
apps/web/utils/calendar/availability.ts (2)
53-55: Trace payload can be large; lazify it.Wrap the busy periods trace in a thunk to avoid serializing when trace is disabled.
Apply:
- logger.trace("Calendar busy periods", { busyPeriods, timeMin, timeMax }); + logger.trace("Calendar busy periods", () => ({ + count: busyPeriods.length, + timeMin, + timeMax, + }));
26-33: Optional: pass timeZone in FreeBusy body.Not required since you send UTC, but specifying timeZone can make responses consistent in downstream logging/formatting. (developers.google.com)
Example:
requestBody: { timeMin, timeMax, + timeZone: "UTC", items: calendarIds.map((id) => ({ id })), },apps/web/__tests__/ai-calendar-availability.test.ts (1)
296-316: Add a test for invalid time range input.Now that we validate dates in the tool, add a case where the LLM passes malformed timeMin/timeMax to ensure we return empty busyPeriods and don’t throw.
Example:
test("gracefully handles invalid timeMin/timeMax", async () => { const messages = getSchedulingMessages(); const emailAccount = getEmailAccount(); // Simulate tool passing bad dates by stubbing the tool execute if you can, // or by passing obviously invalid strings and asserting no throw. // Expect result to be defined (suggest times still possible) and no errors. });
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (7)
apps/web/__tests__/ai-calendar-availability.test.ts(1 hunks)apps/web/package.json(1 hunks)apps/web/utils/ai/calendar/availability.ts(4 hunks)apps/web/utils/ai/choose-rule/run-rules.ts(2 hunks)apps/web/utils/calendar/availability.ts(5 hunks)apps/web/utils/logger.ts(2 hunks)apps/web/utils/reply-tracker/generate-draft.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (17)
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use@/for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
!{.cursor/rules/*.mdc}
📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)
Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/package.jsonapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)
**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport Prisma in the project using
import prisma from "@/utils/prisma";
**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
apps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logic
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
apps/web/utils/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
!pages/_document.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/ai/calendar/availability.tsapps/web/utils/calendar/availability.tsapps/web/package.jsonapps/web/utils/logger.tsapps/web/utils/reply-tracker/generate-draft.ts
apps/web/utils/ai/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
apps/web/utils/ai/**/*.{ts,tsx}: Place main LLM feature implementations under apps/web/utils/ai/
LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)
Keep system prompts and user prompts separate
System prompt should define the LLM's role and task specifications
User prompt should contain the actual data and context
Always define a Zod schema for response validation
Make Zod schemas as specific as possible to guide LLM output
Use descriptive scoped loggers for each feature
Log inputs and outputs with appropriate log levels and include relevant context
Implement early returns for invalid inputs
Use proper error types and logging for failures
Implement fallbacks for AI failures
Add retry logic for transient failures using withRetry
Use XML-like tags to structure data in prompts
Remove excessive whitespace and truncate long inputs in prompts
Format prompt data consistently across similar functions
Use TypeScript types for all parameters and return values in LLM features
Define clear interfaces for complex input/output structures in LLM features
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/utils/ai/calendar/availability.ts
apps/web/utils/{ai,llms}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments
Files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/utils/ai/calendar/availability.ts
**/*.test.{ts,js}
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
Include security tests in your test suites to verify authentication, authorization, and error handling.
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
apps/web/__tests__/**
📄 CodeRabbit inference engine (.cursor/rules/llm-test.mdc)
Place all LLM-related tests under apps/web/tests/
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
apps/web/__tests__/**/*.test.ts
📄 CodeRabbit inference engine (.cursor/rules/llm-test.mdc)
apps/web/__tests__/**/*.test.ts: Guard LLM tests with describe.runIf(process.env.RUN_AI_TESTS === "true") so they only run when RUN_AI_TESTS="true"
Mock the "server-only" module in LLM tests with vi.mock("server-only", () => ({}))
Clear mocks in a beforeEach using vi.clearAllMocks()
Set and use a generous timeout (e.g., const TIMEOUT = 15_000) for LLM tests and pass it to long-running tests/describe
Create helper functions for common test data (e.g., getUser, getTestData(overrides))
Include standard cases: happy path, error handling, edge cases (empty/null), different user configs, and various input formats
Use console.debug to log generated content for inspection
Do not mock the LLM call; invoke the real LLM in these tests
Test both AI and non-AI code paths (e.g., return unchanged when no AI processing is needed)
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
apps/web/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
Place LLM-specific tests under apps/web/tests/
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock theserver-onlymodule withvi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it withvi.mock("@/utils/prisma")and use the mock from@/utils/__mocks__/prisma
Use provided helpers for mocks: import{ getEmail, getEmailAccount, getRule }from@/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g.,vi.clearAllMocks()inbeforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
**/__tests__/**
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
Place AI tests in the
__tests__directory and exclude them from the default test run (they use a real LLM)
Files:
apps/web/__tests__/ai-calendar-availability.test.ts
🧠 Learnings (8)
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.{ts,tsx} : Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments
Applied to files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.tsapps/web/utils/reply-tracker/generate-draft.ts
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI code paths (e.g., return unchanged when no AI processing is needed)
Applied to files:
apps/web/utils/ai/choose-rule/run-rules.tsapps/web/__tests__/ai-calendar-availability.test.ts
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Guard LLM tests with describe.runIf(process.env.RUN_AI_TESTS === "true") so they only run when RUN_AI_TESTS="true"
Applied to files:
apps/web/__tests__/ai-calendar-availability.test.ts
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Mock the "server-only" module in LLM tests with vi.mock("server-only", () => ({}))
Applied to files:
apps/web/__tests__/ai-calendar-availability.test.ts
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Use descriptive scoped loggers for each feature
Applied to files:
apps/web/utils/logger.ts
📚 Learning: 2025-07-18T15:06:47.625Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/logging.mdc:0-0
Timestamp: 2025-07-18T15:06:47.625Z
Learning: Applies to **/*.{ts,tsx} : Use `createScopedLogger` for logging in backend TypeScript files
Applied to files:
apps/web/utils/logger.ts
📚 Learning: 2025-07-20T09:03:06.318Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.318Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Make sure to pass a message value when creating a built-in error.
Applied to files:
apps/web/utils/logger.ts
📚 Learning: 2025-09-20T18:24:34.271Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.271Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`
Applied to files:
apps/web/utils/reply-tracker/generate-draft.ts
🧬 Code graph analysis (4)
apps/web/utils/ai/choose-rule/run-rules.ts (1)
apps/web/utils/index.ts (1)
filterNullProperties(11-17)
apps/web/__tests__/ai-calendar-availability.test.ts (4)
apps/web/utils/types.ts (1)
EmailForLLM(117-131)apps/web/utils/calendar/availability.ts (2)
BusyPeriod(9-12)getCalendarAvailability(62-110)apps/web/__tests__/helpers.ts (1)
getEmailAccount(6-23)apps/web/utils/ai/calendar/availability.ts (1)
aiGetCalendarAvailability(16-181)
apps/web/utils/ai/calendar/availability.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
logger(3-3)
apps/web/utils/logger.ts (1)
apps/web/env.ts (1)
env(16-242)
⏰ 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: Software Component Analysis Js
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Vercel Agent Review
- GitHub Check: Jit Security
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
apps/web/utils/reply-tracker/generate-draft.ts (1)
6-6: LGTM: writing style lookup is now part of the batch.Imported correctly and used in the Promise.all block. No further action.
apps/web/utils/ai/calendar/availability.ts (2)
49-56: Query shape looks good.Selecting calendarId/timezone/primary on enabled calendars is appropriate for TZ inference.
58-62: Timezone inference: sensible fallback chain.Primary → any → UTC is fine. Consider validating IANA names if you see bad data in prod, but ok for now.
apps/web/__tests__/ai-calendar-availability.test.ts (2)
144-186: Test guard, setup, and happy path look good.Suite is properly gated with describe.runIf and uses console.debug per test guidance. Mocks are cleared per test.
430-441: Solid assertions on timezone propagation.Verifying timezone plumbed into getCalendarAvailability is exactly what we need.
Also applies to: 476-485, 526-535, 590-599
apps/web/package.json (1)
98-99: Use @date-fns/tz with date-fns v4; avoid date-fns-tz.The project uses date-fns 4.1.0. v4 ships first‑class time‑zone support via @date-fns/tz (and “in: tz()” options), while date-fns-tz is the pre‑v4 add‑on and can conflict or produce subtle errors. Replace date-fns-tz with @date-fns/tz. (blog.date-fns.org)
Apply this diff:
- "date-fns-tz": "3.2.0", + "@date-fns/tz": "^1.0.2",Run to find any remaining imports:
apps/web/utils/ai/choose-rule/run-rules.ts (1)
23-24: Good use of lazy trace with filtered payload.The thunk + filterNullProperties prevents heavy logs when tracing is off. This aligns with the new logger behavior.
After fixing logger (see separate comment), confirm no runtime type errors by grepping all trace calls that pass thunks:
Also applies to: 73-75
There was a problem hiding this comment.
5 issues found across 9 files
Prompt for AI agents (all 5 issues)
Understand the root cause of the following 5 issues and fix them.
<file name="apps/web/utils/logger.ts">
<violation number="1" location="apps/web/utils/logger.ts:58">
Only the first lazy args function is executed; subsequent functions are ignored. Evaluate all functions or restrict the type to a single lazy callback.</violation>
<violation number="2" location="apps/web/utils/logger.ts:80">
Accepting a lazy args function but not invoking it causes missing log fields. Resolve the function before spreading when debug logs are enabled.</violation>
</file>
<file name="apps/web/utils/ai/calendar/availability.ts">
<violation number="1" location="apps/web/utils/ai/calendar/availability.ts:155">
Logging the full availabilityData can leak sensitive calendar details and add log noise/overhead; prefer logging a summary (e.g., count) instead.</violation>
</file>
<file name="apps/web/utils/calendar/availability.ts">
<violation number="1" location="apps/web/utils/calendar/availability.ts:89">
startOfDay is not timezone-aware; computing "startOfDayInTimezone" without applying the target timezone yields incorrect day boundaries for non-UTC zones.</violation>
<violation number="2" location="apps/web/utils/calendar/availability.ts:90">
endOfDay is not timezone-aware; using it without first converting to the requested timezone causes incorrect end-of-day in that timezone.</violation>
</file>
React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.
Summary by CodeRabbit