Skip to content

Comments

Use economy model for persona#800

Merged
elie222 merged 1 commit intomainfrom
chore/economy-model-persona
Sep 18, 2025
Merged

Use economy model for persona#800
elie222 merged 1 commit intomainfrom
chore/economy-model-persona

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 18, 2025

Summary by CodeRabbit

  • New Features
    • Onboarding now supports “move to folder” and “move to folder (delayed)” rule actions, enabling related cold email and reply tracking steps for these cases.
  • Refactor
    • Switched sender categorization to a more efficient AI model to reduce cost/latency without changing behavior.
  • Chores
    • Version updated to v2.9.46.

@vercel
Copy link

vercel bot commented Sep 18, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 18, 2025 0:08am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 18, 2025

Walkthrough

Expanded rule onboarding guard to include move_folder actions and updated AI sender categorization to use the “economy” model; bumped version to v2.9.46.

Changes

Cohort / File(s) Change Summary
Rules Onboarding Guard
apps/web/utils/actions/rule.ts
Broadened isSet type guard in createRulesOnboardingAction to treat "move_folder" and "move_folder_delayed" as set, enabling onboarding branches for these actions.
AI Model Selection
apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
Switched model selection from getModel(..., "chat") to getModel(..., "economy"); no other logic changes.
Version Bump
version.txt
Updated version from v2.9.45 to v2.9.46.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant R as createRulesOnboardingAction
  participant CE as ColdEmail Blocker
  participant RT as Reply Tracker

  U->>R: Create/Update Rule (categoryAction = move_folder|move_folder_delayed)
  R->>R: isSet(categoryAction) check (now includes move_folder*)
  alt isSet == true
    R->>CE: Run cold-email onboarding branch
    R->>RT: Run reply-tracker onboarding branch
    CE-->>R: Results
    RT-->>R: Results
    R-->>U: Onboarding branches executed
  else
    R-->>U: No onboarding branches
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • Move folder action improvements #683 — Adjusts rule handling for move_folder actions, touching the same rule onboarding logic.
  • Fixes #657 — Refactors categorize-sender to use generateObject/getModel; overlaps with the model selection change here.

Poem

A rabbit taps keys with a gentle cheer,
“Move the folders? I hear, I hear!”
The inbox hums in economy mode,
Onboarding paths now share the road.
Version hops to forty-six—how neat!
Thump-thump, shipped changes at rabbit-feet. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Use economy model for persona" accurately and concisely reflects the primary change in this PR — switching the AI model used (aiCategorizeSenders) from "chat" to "economy". It is specific enough for a reviewer to understand the main intent; the other edits (rule type-guard expansion and version bump) are minor and need not be included in the title.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/economy-model-persona

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts (1)

58-61: Escape XML-like prompt fields to prevent structure breakage.

Subjects/snippets can contain <, >, &, which will corrupt the tag structure and harm parsing/accuracy.

Apply escaping when interpolating:

-              <subject>${s.subject}</subject>
-              <snippet>${s.snippet}</snippet>
+              <subject>${escapeXml(s.subject)}</subject>
+              <snippet>${escapeXml(s.snippet)}</snippet>

Add a local helper (or use an existing util if present):

+function escapeXml(input: string): string {
+  return input
+    .replace(/&/g, "&amp;")
+    .replace(/</g, "&lt;")
+    .replace(/>/g, "&gt;");
+}
apps/web/utils/actions/rule.ts (1)

96-115: Keep LABEL when adding MOVE_FOLDER — don't overwrite actions

apps/web/utils/actions/rule.ts: lines 96–115 — getActionsFromCategoryAction replaces the actions array for move_folder, dropping the initial LABEL the prompt promises. Push MOVE_FOLDER instead of reassigning:

-      actions = [
-        {
-          type: ActionType.MOVE_FOLDER,
-          folderId,
-          folderName: rule.name,
-          delayInMinutes:
-            categoryAction === "move_folder_delayed"
-              ? ONE_WEEK_MINUTES
-              : undefined,
-        },
-      ];
+      actions.push({
+        type: ActionType.MOVE_FOLDER,
+        folderId,
+        folderName: rule.name,
+        delayInMinutes:
+          categoryAction === "move_folder_delayed"
+            ? ONE_WEEK_MINUTES
+            : undefined,
+      });

If this was intentional, update the generated prompt text to remove “Label …” for move_folder variants.

🧹 Nitpick comments (1)
apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts (1)

48-67: Trim/truncate long inputs to control token bloat.

Bound subject/snippet length to reduce costs and improve determinism.

-              <subject>${s.subject}</subject>
-              <snippet>${s.snippet}</snippet>
+              <subject>${escapeXml(s.subject.slice(0, 200))}</subject>
+              <snippet>${escapeXml(s.snippet.slice(0, 500))}</snippet>
📜 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 1e7e5e1 and 1f92ae9.

📒 Files selected for processing (3)
  • apps/web/utils/actions/rule.ts (1 hunks)
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
!{.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:

  • version.txt
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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:

  • version.txt
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.ts
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/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/actions/rule.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/categorize-sender/ai-categorize-senders.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/categorize-sender/ai-categorize-senders.ts
apps/web/utils/actions/**/*.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/rule.ts
apps/web/utils/actions/*.ts

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

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
Use actionClient when both authenticated user context and a specific emailAccountId are needed. The emailAccountId must be bound when calling the action from the client.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/rule.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
version.txt (1)

1-1: Version bump looks fine; don’t forget release hygiene.

Ensure the changelog/release notes and tag v2.9.46 are created alongside this bump.

apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts (1)

89-89: Switching to "economy" model — confirm provider mapping, availability, and quotas.

  • Repo search shows many call sites already use getModel(..., "economy") and tests assert getModel(userAi, "economy") -> Provider.OPENROUTER, modelName "google/gemini-2.5-flash-preview-05-20" (see apps/web/utils/llms/model.test.ts).
  • Action: verify the getModel implementation actually maps "economy" to the intended provider/model, ensure required provider API key(s) are present in env/config, confirm the model is available and its current rate limits, and validate downstream quotas/latency budgets for impacted flows (categorize, reports, knowledge extraction).
  • Quick locations to check: apps/web/utils/llms/model.test.ts and callers such as apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts:89 (many other report/knowledge modules also use "economy").

Comment on lines 588 to 596
const isSet = (
value: string | undefined | null,
): value is "label" | "label_archive" | "label_archive_delayed" =>
value !== "none" && value !== undefined;
): value is
| "label"
| "label_archive"
| "label_archive_delayed"
| "move_folder"
| "move_folder_delayed" => value !== "none" && value !== undefined;

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

Type guard bug: null and arbitrary strings pass as “set”.

value !== "none" && value !== undefined erroneously returns true for null and any non-"none" string, while the predicate narrows to specific literals. This can enable invalid actions to flow through.

Use exact membership + include null check; also narrow the param type:

-      const isSet = (
-        value: string | undefined | null,
-      ): value is
-        | "label"
-        | "label_archive"
-        | "label_archive_delayed"
-        | "move_folder"
-        | "move_folder_delayed" => value !== "none" && value !== undefined;
+      const isSet = (
+        value: CategoryAction | "none" | undefined | null,
+      ): value is CategoryAction => {
+        return (
+          value !== null &&
+          value !== undefined &&
+          (value === "label" ||
+            value === "label_archive" ||
+            value === "label_archive_delayed" ||
+            value === "move_folder" ||
+            value === "move_folder_delayed")
+        );
+      };
📝 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
const isSet = (
value: string | undefined | null,
): value is "label" | "label_archive" | "label_archive_delayed" =>
value !== "none" && value !== undefined;
): value is
| "label"
| "label_archive"
| "label_archive_delayed"
| "move_folder"
| "move_folder_delayed" => value !== "none" && value !== undefined;
const isSet = (
value: CategoryAction | "none" | undefined | null,
): value is CategoryAction => {
return (
value !== null &&
value !== undefined &&
(value === "label" ||
value === "label_archive" ||
value === "label_archive_delayed" ||
value === "move_folder" ||
value === "move_folder_delayed")
);
};

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.

1 issue found across 3 files

Prompt for AI agents (all 1 issues)

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


<file name="apps/web/utils/actions/rule.ts">

<violation number="1" location="apps/web/utils/actions/rule.ts:595">
The type guard is unsound: value !== &quot;none&quot; &amp;&amp; value !== undefined returns true for null and arbitrary strings while claiming to narrow to specific literals. Replace with an explicit membership check and include a null check; also tighten the parameter type to the expected union.</violation>
</file>

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

| "label_archive"
| "label_archive_delayed"
| "move_folder"
| "move_folder_delayed" => value !== "none" && value !== undefined;
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Sep 18, 2025

Choose a reason for hiding this comment

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

The type guard is unsound: value !== "none" && value !== undefined returns true for null and arbitrary strings while claiming to narrow to specific literals. Replace with an explicit membership check and include a null check; also tighten the parameter type to the expected union.

Prompt for AI agents
Address the following comment on apps/web/utils/actions/rule.ts at line 595:

<comment>The type guard is unsound: value !== &quot;none&quot; &amp;&amp; value !== undefined returns true for null and arbitrary strings while claiming to narrow to specific literals. Replace with an explicit membership check and include a null check; also tighten the parameter type to the expected union.</comment>

<file context>
@@ -587,8 +587,12 @@ export const createRulesOnboardingAction = actionClient
+        | &quot;label_archive&quot;
+        | &quot;label_archive_delayed&quot;
+        | &quot;move_folder&quot;
+        | &quot;move_folder_delayed&quot; =&gt; value !== &quot;none&quot; &amp;&amp; value !== undefined;
 
       // cold email blocker
</file context>
Fix with Cubic

@elie222 elie222 merged commit b14269b into main Sep 18, 2025
19 checks passed
@elie222 elie222 deleted the chore/economy-model-persona branch September 18, 2025 17:15
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