Skip to content

Comments

Fix outlook error#839

Merged
elie222 merged 3 commits intomainfrom
fix/outlook-bug
Oct 8, 2025
Merged

Fix outlook error#839
elie222 merged 3 commits intomainfrom
fix/outlook-bug

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Oct 8, 2025

Summary by CodeRabbit

  • New Features

    • Improved Outlook message querying with flexible multi-criteria filters (including date constraints) and better handling of special-character searches; enhanced thread retrieval and label operations.
  • Tests

    • Introduced RUN_E2E_TESTS gating for E2E/integration suites (Outlook and Gmail). Expanded Outlook E2E coverage for threads, senders, labels, searches and webhooks with clearer logging and structure.
  • Chores

    • Added unified E2E test script and updated usage instructions; removed the Outlook-specific test script.
  • Version

    • Bumped release to v2.15.5.

@vercel
Copy link

vercel bot commented Oct 8, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Oct 8, 2025 1:16pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 8, 2025

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit 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.

Walkthrough

Replaces Gmail/Outlook test gating to use RUN_E2E_TESTS and adds a test-e2e script; expands and reorganizes Outlook E2E tests; adds queryMessagesWithFilters to Outlook utilities and refactors Microsoft getMessagesFromSender to use filter-based queries; bumps version to v2.15.5.

Changes

Cohort / File(s) Summary of Changes
E2E test gating & suites
apps/web/__tests__/gmail-operations.test.ts, apps/web/__tests__/outlook-operations.test.ts
Switch test gating from per-service env vars to RUN_E2E_TESTS; reorganize and expand Outlook tests (thread, sender queries, label ops, messages, search, webhooks); add conditional DB load, logging, and improved test scaffolding.
Outlook message utilities
apps/web/utils/outlook/message.ts
Add queryMessagesWithFilters — builds OData filters (sender/date/folder), handles paging via skipToken, fetches and maps messages, returns nextPageToken.
Microsoft email wrapper
apps/web/utils/email/microsoft.ts
Refactor getMessagesFromSender to build filters and dateFilters and call queryMessagesWithFilters instead of the previous single-sender pagination path.
Package scripts
apps/web/package.json
Remove test-outlook script; add test-e2e script: cross-env RUN_E2E_TESTS=true vitest --run.
Versioning
version.txt
Bump version from v2.15.4 to v2.15.5.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor TestRunner as Test Runner
  participant Env as Environment
  participant Vitest as Vitest
  participant Suites as Test Suites

  TestRunner->>Env: Run `test-e2e` (RUN_E2E_TESTS=true)
  Env-->>Vitest: Expose RUN_E2E_TESTS
  Vitest->>Suites: Load Gmail & Outlook test files
  alt RUN_E2E_TESTS truthy
    Suites->>Suites: Execute E2E/integration blocks
  else RUN_E2E_TESTS falsy
    Suites->>Suites: Skip E2E/integration blocks
  end
Loading
sequenceDiagram
  autonumber
  participant Caller as Microsoft.getMessagesFromSender
  participant Filters as Filter Builder
  participant Outlook as queryMessagesWithFilters
  participant Graph as MS Graph API

  Caller->>Filters: Build `filters` (from/address eq "<sender>")
  Caller->>Filters: Build optional `dateFilters` (receivedDateTime gt/lt)
  Caller->>Outlook: queryMessagesWithFilters({ filters, dateFilters, maxResults, pageToken })
  Outlook->>Graph: GET /messages?$filter=...&$top=...&$skiptoken=...
  Graph-->>Outlook: Messages + @odata.nextLink
  Outlook-->>Caller: { messages, nextPageToken }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Fix outlook error #839 — Adds RUN_E2E_TESTS, test-e2e script, expands Outlook tests and introduces filter-based querying (high overlap with these changes).
  • Refactor email provider imports #702 — Changes Outlook message query paths and utilities; intersects with queryMessagesWithFilters and getMessagesFromSender refactor.
  • Fix outlook webhook #836 — Modifies Outlook integration/webhook tests and gating; closely related to test reorganizations here.

Suggested reviewers

  • anakarentorosserrano-star

Poem

I twitch my whiskers at filters bright,
Hop through threads by morning light.
E2E flags set, I bound and cheer,
New queries fetch the threads I hear.
Version up — a happy hop, hooray! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The title "Fix outlook error" is overly vague and only addresses a perceived Outlook issue, but the changeset introduces a new RUN_E2E_TESTS gating mechanism, updates both Gmail and Outlook test suites, adds an end-to-end test script, implements a new queryMessagesWithFilters function, and bumps the package version. This title does not accurately or comprehensively summarize the scope or primary purpose of the pull request. Please update the title to clearly reflect the main changes, for example: “Introduce RUN_E2E_TESTS gating for end-to-end tests and update Outlook/Gmail operations tests and utilities.”
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b22902 and 60fc8d9.

📒 Files selected for processing (2)
  • apps/web/__tests__/outlook-operations.test.ts (3 hunks)
  • apps/web/utils/outlook/message.ts (1 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
apps/web/__tests__/gmail-operations.test.ts (2)

22-22: Make RUN_E2E_TESTS a strict boolean

Avoid accidental runs when RUN_E2E_TESTS="false".

Apply this diff:

-const RUN_E2E_TESTS = process.env.RUN_E2E_TESTS;
+const RUN_E2E_TESTS = process.env.RUN_E2E_TESTS === "true";

Based on learnings


51-51: Use strict gating check

With the change above, skipIf remains correct. If not changing the const, use explicit comparison here.

Alternative diff (if you keep RUN_E2E_TESTS as a string):

-describe.skipIf(!RUN_E2E_TESTS)("Gmail Webhook Payload", () => {
+describe.skipIf(process.env.RUN_E2E_TESTS !== "true")("Gmail Webhook Payload", () => {

Based on learnings

apps/web/__tests__/outlook-operations.test.ts (2)

25-25: Make RUN_E2E_TESTS a strict boolean

Prevent accidental execution when RUN_E2E_TESTS="false".

Apply this diff:

-const RUN_E2E_TESTS = process.env.RUN_E2E_TESTS;
+const RUN_E2E_TESTS = process.env.RUN_E2E_TESTS === "true";

Based on learnings


41-41: Use strict gating check

Pairing with the boolean const above keeps this correct. If not changing const, compare to "true" here.

Alternative diff:

-describe.skipIf(!RUN_E2E_TESTS)("Outlook Operations Integration Tests", () => {
+describe.skipIf(process.env.RUN_E2E_TESTS !== "true")("Outlook Operations Integration Tests", () => {

Based on learnings

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0534445 and 5b22902.

📒 Files selected for processing (6)
  • apps/web/__tests__/gmail-operations.test.ts (3 hunks)
  • apps/web/__tests__/outlook-operations.test.ts (3 hunks)
  • apps/web/package.json (1 hunks)
  • apps/web/utils/email/microsoft.ts (2 hunks)
  • apps/web/utils/outlook/message.ts (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (14)
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/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/outlook/message.ts
  • apps/web/package.json
  • version.txt
  • apps/web/utils/email/microsoft.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import 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/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.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/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements 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/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/outlook/message.ts
  • apps/web/package.json
  • version.txt
  • apps/web/utils/email/microsoft.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.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__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.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__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.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__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.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 the server-only module with vi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it with vi.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() in beforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger

Files:

  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.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__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
apps/web/__tests__/**/*.test.ts

📄 CodeRabbit inference engine (.cursor/rules/llm-test.mdc)

apps/web/__tests__/**/*.test.ts: Place all LLM-related tests under apps/web/tests/
Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"
Mock the Next.js server runtime marker by adding vi.mock("server-only", () => ({})) in LLM tests
Gate LLM tests behind RUN_AI_TESTS using describe.runIf(process.env.RUN_AI_TESTS === "true")
Call vi.clearAllMocks() in a beforeEach for LLM tests
Set a TIMEOUT of 15_000ms for LLM-related tests and pass it to long-running tests/describe blocks
Create helper functions for common test data (e.g., getUser, getTestData) to reduce duplication
Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats
Use console.debug to log generated LLM content for inspection (e.g., console.debug("Generated content:\n", result.content))
Do not mock the actual LLM call in these tests; exercise real LLM integrations
Test both AI and non-AI paths, including cases where no AI processing is required
Prefer existing helpers from @/tests/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Files:

  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
🧠 Learnings (2)
📚 Learning: 2025-10-02T23:23:48.053Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.053Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer existing helpers from @/__tests__/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Applied to files:

  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/__tests__/gmail-operations.test.ts
📚 Learning: 2025-10-02T23:23:48.053Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.053Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Gate LLM tests behind RUN_AI_TESTS using describe.runIf(process.env.RUN_AI_TESTS === "true")

Applied to files:

  • apps/web/__tests__/gmail-operations.test.ts
🧬 Code graph analysis (3)
apps/web/utils/outlook/message.ts (2)
apps/web/utils/outlook/client.ts (1)
  • OutlookClient (19-63)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (13-20)
apps/web/utils/email/microsoft.ts (2)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (13-20)
apps/web/utils/outlook/message.ts (1)
  • queryMessagesWithFilters (318-372)
apps/web/__tests__/outlook-operations.test.ts (2)
apps/web/utils/email/microsoft.ts (1)
  • OutlookProvider (66-1241)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-29)
⏰ 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: Software Component Analysis Js
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Jit Security
🔇 Additional comments (4)
version.txt (1)

1-1: Version bump looks good

No issues.

apps/web/package.json (1)

12-12: Add E2E script: LGTM

Script aligns with new RUN_E2E_TESTS gating.

apps/web/utils/email/microsoft.ts (1)

678-695: Refactor to filter-based query: LGTM

Escaping is correct; date filters are well-formed; integrates with new utility.

apps/web/__tests__/gmail-operations.test.ts (1)

9-11: Usage docs updated: LGTM

Matches new test-e2e script.

Comment on lines 318 to 372
export async function queryMessagesWithFilters(
client: OutlookClient,
options: {
filters?: string[]; // OData filter expressions to AND together
dateFilters?: string[]; // additional date filters like receivedDateTime gt/lt
maxResults?: number;
pageToken?: string;
folderId?: string; // if omitted, defaults to inbox OR archive
},
) {
const { filters = [], dateFilters = [], pageToken, folderId } = options;

const MAX_RESULTS = 20;
const maxResults = Math.min(options.maxResults || MAX_RESULTS, MAX_RESULTS);

const folderIds = await getFolderIds(client);
const inboxFolderId = folderIds.inbox;
const archiveFolderId = folderIds.archive;

// Build base request
let request = client
.getClient()
.api("/me/messages")
.select(
"id,conversationId,conversationIndex,subject,bodyPreview,from,sender,toRecipients,receivedDateTime,isDraft,isRead,body,categories,parentFolderId",
)
.top(maxResults);

// Build folder filter
const folderFilter = folderId
? `parentFolderId eq '${escapeODataString(folderId)}'`
: `(parentFolderId eq '${escapeODataString(inboxFolderId)}' or parentFolderId eq '${escapeODataString(archiveFolderId)}')`;

const combinedFilters = [folderFilter, ...dateFilters, ...filters].filter(
Boolean,
);
const combinedFilter = combinedFilters.join(" and ");

request = request.filter(combinedFilter);

if (pageToken) {
request = request.skipToken(pageToken);
}

const response: { value: Message[]; "@odata.nextLink"?: string } =
await request.get();

const messages = await convertMessages(response.value, folderIds);
const nextPageToken = response["@odata.nextLink"]
? new URL(response["@odata.nextLink"]).searchParams.get("$skiptoken") ||
undefined
: undefined;

return { messages, nextPageToken };
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fix folder filter when inbox/archive IDs are missing and add stable ordering

  • If archive/inbox IDs aren’t available, the current filter can degrade to parentFolderId eq '', returning no results or errors.
  • Add orderby for deterministic results (mirrors queryBatchMessages behavior).

Apply this diff within the function:

@@
-  // Build folder filter
-  const folderFilter = folderId
-    ? `parentFolderId eq '${escapeODataString(folderId)}'`
-    : `(parentFolderId eq '${escapeODataString(inboxFolderId)}' or parentFolderId eq '${escapeODataString(archiveFolderId)}')`;
-
-  const combinedFilters = [folderFilter, ...dateFilters, ...filters].filter(
-    Boolean,
-  );
-  const combinedFilter = combinedFilters.join(" and ");
-
-  request = request.filter(combinedFilter);
+  // Build folder filter (robust to missing folder IDs)
+  const folderIdFilters: string[] = [];
+  if (folderId) {
+    folderIdFilters.push(
+      `parentFolderId eq '${escapeODataString(folderId)}'`,
+    );
+  } else {
+    if (inboxFolderId) {
+      folderIdFilters.push(
+        `parentFolderId eq '${escapeODataString(inboxFolderId)}'`,
+      );
+    }
+    if (archiveFolderId) {
+      folderIdFilters.push(
+        `parentFolderId eq '${escapeODataString(archiveFolderId)}'`,
+      );
+    }
+  }
+  const folderFilter =
+    folderIdFilters.length === 0
+      ? undefined
+      : folderIdFilters.length === 1
+        ? folderIdFilters[0]
+        : `(${folderIdFilters.join(" or ")})`;
+
+  const combinedFilters = [folderFilter, ...dateFilters, ...filters].filter(
+    Boolean,
+  );
+  if (combinedFilters.length > 0) {
+    const combinedFilter = combinedFilters.join(" and ");
+    request = request.filter(combinedFilter);
+  }
@@
-  if (pageToken) {
-    request = request.skipToken(pageToken);
-  }
+  if (pageToken) {
+    request = request.skipToken(pageToken);
+  } else {
+    // Keep ordering only for non-paginated requests to avoid complexity errors
+    request = request.orderby("receivedDateTime DESC");
+  }

Optional: also warn if maxResults > 20 to match queryBatchMessages.

📝 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.

Suggested change
export async function queryMessagesWithFilters(
client: OutlookClient,
options: {
filters?: string[]; // OData filter expressions to AND together
dateFilters?: string[]; // additional date filters like receivedDateTime gt/lt
maxResults?: number;
pageToken?: string;
folderId?: string; // if omitted, defaults to inbox OR archive
},
) {
const { filters = [], dateFilters = [], pageToken, folderId } = options;
const MAX_RESULTS = 20;
const maxResults = Math.min(options.maxResults || MAX_RESULTS, MAX_RESULTS);
const folderIds = await getFolderIds(client);
const inboxFolderId = folderIds.inbox;
const archiveFolderId = folderIds.archive;
// Build base request
let request = client
.getClient()
.api("/me/messages")
.select(
"id,conversationId,conversationIndex,subject,bodyPreview,from,sender,toRecipients,receivedDateTime,isDraft,isRead,body,categories,parentFolderId",
)
.top(maxResults);
// Build folder filter
const folderFilter = folderId
? `parentFolderId eq '${escapeODataString(folderId)}'`
: `(parentFolderId eq '${escapeODataString(inboxFolderId)}' or parentFolderId eq '${escapeODataString(archiveFolderId)}')`;
const combinedFilters = [folderFilter, ...dateFilters, ...filters].filter(
Boolean,
);
const combinedFilter = combinedFilters.join(" and ");
request = request.filter(combinedFilter);
if (pageToken) {
request = request.skipToken(pageToken);
}
const response: { value: Message[]; "@odata.nextLink"?: string } =
await request.get();
const messages = await convertMessages(response.value, folderIds);
const nextPageToken = response["@odata.nextLink"]
? new URL(response["@odata.nextLink"]).searchParams.get("$skiptoken") ||
undefined
: undefined;
return { messages, nextPageToken };
}
export async function queryMessagesWithFilters(
client: OutlookClient,
options: {
filters?: string[]; // OData filter expressions to AND together
dateFilters?: string[]; // additional date filters like receivedDateTime gt/lt
maxResults?: number;
pageToken?: string;
folderId?: string; // if omitted, defaults to inbox OR archive
},
) {
const { filters = [], dateFilters = [], pageToken, folderId } = options;
const MAX_RESULTS = 20;
const maxResults = Math.min(options.maxResults || MAX_RESULTS, MAX_RESULTS);
const folderIds = await getFolderIds(client);
const inboxFolderId = folderIds.inbox;
const archiveFolderId = folderIds.archive;
// Build base request
let request = client
.getClient()
.api("/me/messages")
.select(
"id,conversationId,conversationIndex,subject,bodyPreview,from,sender,toRecipients,receivedDateTime,isDraft,isRead,body,categories,parentFolderId",
)
.top(maxResults);
// Build folder filter (robust to missing folder IDs)
const folderIdFilters: string[] = [];
if (folderId) {
folderIdFilters.push(
`parentFolderId eq '${escapeODataString(folderId)}'`,
);
} else {
if (inboxFolderId) {
folderIdFilters.push(
`parentFolderId eq '${escapeODataString(inboxFolderId)}'`,
);
}
if (archiveFolderId) {
folderIdFilters.push(
`parentFolderId eq '${escapeODataString(archiveFolderId)}'`,
);
}
}
const folderFilter =
folderIdFilters.length === 0
? undefined
: folderIdFilters.length === 1
? folderIdFilters[0]
: `(${folderIdFilters.join(" or ")})`;
const combinedFilters = [folderFilter, ...dateFilters, ...filters].filter(
Boolean,
);
if (combinedFilters.length > 0) {
const combinedFilter = combinedFilters.join(" and ");
request = request.filter(combinedFilter);
}
if (pageToken) {
request = request.skipToken(pageToken);
} else {
// Keep ordering only for non-paginated requests to avoid complexity errors
request = request.orderby("receivedDateTime DESC");
}
const response: { value: Message[]; "@odata.nextLink"?: string } =
await request.get();
const messages = await convertMessages(response.value, folderIds);
const nextPageToken = response["@odata.nextLink"]
? new URL(response["@odata.nextLink"]).searchParams.get("$skiptoken") ||
undefined
: undefined;
return { messages, nextPageToken };
}
🤖 Prompt for AI Agents
In apps/web/utils/outlook/message.ts around lines 318–372, the folder filter
currently interpolates possibly-empty inbox/archive IDs which can produce
filters like "parentFolderId eq ''" and return no results; update the logic to
only include parentFolderId clauses when the corresponding inbox/archive IDs are
present (if a folderId option is provided use it, otherwise build an OR clause
from any non-empty inbox/archive IDs and if none exist omit the parentFolderId
filter entirely), then append the other date/filters as before; also add a
stable ordering by calling orderby("receivedDateTime desc") on the request (to
mirror queryBatchMessages) and optionally log or cap if options.maxResults > 20
to match MAX_RESULTS behavior.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 issues found across 6 files

Prompt for AI agents (all 4 issues)

Understand the root cause of the following 4 issues and fix them.


<file name="apps/web/__tests__/outlook-operations.test.ts">

<violation number="1" location="apps/web/__tests__/outlook-operations.test.ts:41">
This suite now runs even when TEST_OUTLOOK_EMAIL is missing, so `beforeAll` returns without initializing `provider` and the subsequent tests crash when they call `provider.*`. Please keep the suite skipped unless both RUN_E2E_TESTS and TEST_OUTLOOK_EMAIL are set.</violation>

<violation number="2" location="apps/web/__tests__/outlook-operations.test.ts:298">
With this guard the webhook suite executes even when TEST_OUTLOOK_EMAIL is undefined, causing the Prisma lookup to throw. Please continue skipping unless both RUN_E2E_TESTS and TEST_OUTLOOK_EMAIL are provided.</violation>
</file>

<file name="apps/web/__tests__/gmail-operations.test.ts">

<violation number="1" location="apps/web/__tests__/gmail-operations.test.ts:51">
Dropping the TEST_GMAIL_EMAIL guard means the e2e suite now runs even when that env var is missing, so Prisma receives email: undefined and the test crashes. Please keep the skip condition checking both RUN_E2E_TESTS and TEST_GMAIL_EMAIL.</violation>
</file>

<file name="apps/web/utils/outlook/message.ts">

<violation number="1" location="apps/web/utils/outlook/message.ts:349">
If inboxFolderId or archiveFolderId is missing we filter against an empty string, so the query returns zero messages even though mail exists. Please only include known folder IDs (or skip the filter) when getFolderIds cannot supply them.</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

// Build folder filter
const folderFilter = folderId
? `parentFolderId eq '${escapeODataString(folderId)}'`
: `(parentFolderId eq '${escapeODataString(inboxFolderId)}' or parentFolderId eq '${escapeODataString(archiveFolderId)}')`;
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Oct 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If inboxFolderId or archiveFolderId is missing we filter against an empty string, so the query returns zero messages even though mail exists. Please only include known folder IDs (or skip the filter) when getFolderIds cannot supply them.

Prompt for AI agents
Address the following comment on apps/web/utils/outlook/message.ts at line 349:

<comment>If inboxFolderId or archiveFolderId is missing we filter against an empty string, so the query returns zero messages even though mail exists. Please only include known folder IDs (or skip the filter) when getFolderIds cannot supply them.</comment>

<file context>
@@ -315,6 +315,62 @@ export async function queryBatchMessages(
+  // Build folder filter
+  const folderFilter = folderId
+    ? `parentFolderId eq &#39;${escapeODataString(folderId)}&#39;`
+    : `(parentFolderId eq &#39;${escapeODataString(inboxFolderId)}&#39; or parentFolderId eq &#39;${escapeODataString(archiveFolderId)}&#39;)`;
+
+  const combinedFilters = [folderFilter, ...dateFilters, ...filters].filter(
</file context>

✅ Addressed in 60fc8d9

@elie222 elie222 merged commit 115c390 into main Oct 8, 2025
5 of 6 checks passed
@elie222 elie222 deleted the fix/outlook-bug branch October 8, 2025 13:08
@coderabbitai coderabbitai bot mentioned this pull request Nov 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant