Skip to content

WIP: migrate to ai sdk v5. (Blocked by OpenRouter)#546

Closed
elie222 wants to merge 11 commits intomainfrom
chore/ai-sdk-v5
Closed

WIP: migrate to ai sdk v5. (Blocked by OpenRouter)#546
elie222 wants to merge 11 commits intomainfrom
chore/ai-sdk-v5

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jul 6, 2025

Waiting for OpenRouter support for till we can migrate:
https://github.com/OpenRouterTeam/ai-sdk-provider/pull/77/files

This may also work with OpenRouter but haven't tried it yet:
https://ai-sdk.dev/providers/openai-compatible-providers

Summary by CodeRabbit

  • New Features

    • Enhanced chat tools with specialized UI components for distinct tool types and improved error handling.
    • Modularized assistant chat tool logic for better extensibility and maintainability.
  • Refactor

    • Updated chat message structure to use a richer, part-based format.
    • Simplified chat input and message state management for a more responsive user experience.
    • Improved message transformation and streaming for chat responses.
    • Upgraded AI SDK and related dependencies to latest beta versions.
    • Refined model selection logic with updated SDK support and disabled unsupported providers.
    • Streamlined chat API message handling with batch saving and UI message abstractions.
    • Removed global fetcher disabling and introduced explicit chat transport configuration.
    • Removed legacy data stream handler component and related code.
  • Bug Fixes

    • Improved error display for tool outputs within chat messages.
  • Chores

    • Updated type definitions for chat messages, tools, and usage tracking to align with new SDK conventions.
    • Removed unused components and legacy workaround code.
    • Adjusted usage tracking and cost calculation to use standardized usage types.
    • Updated dependency versions and added new AI SDK provider package.
    • Enforced stricter hook usage by throwing errors when context is missing.
    • Minor UI text and styling adjustments in assistant overview component.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 6, 2025

Walkthrough

This update refactors the assistant chat system to use more explicit and extensible types for messages and tools, modularizes tool definitions, and upgrades AI SDK dependencies to new beta versions. It updates message handling, streaming, and UI components to use new abstractions, improves error handling, removes deprecated or workaround code, and removes Ollama support throughout the chat and tool flow.

Changes

File(s) Change Summary
apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx Updated import for useCompletion to new package path.
apps/web/app/api/chat/route.ts Refactored message transformation and streaming logic to use new UI message abstraction and conversion utilities; removed deprecated helpers and commented code; added batch message saving with error capture.
apps/web/components/assistant-chat/chat.tsx Removed SWR workaround; introduced explicit chat transport; improved local state/input handling; updated message conversion and submission flow.
apps/web/components/assistant-chat/data-stream-handler.tsx Deleted file and removed DataStreamHandler component and related types.
apps/web/components/assistant-chat/helpers.ts Added convertToUIMessages helper for chat response to UI message conversion.
apps/web/components/assistant-chat/message-editor.tsx Updated to use ChatMessage and message parts; added helper for extracting text; changed regeneration logic.
apps/web/components/assistant-chat/message.tsx Refactored tool part rendering to handle each tool type explicitly; improved error handling and UI specialization.
apps/web/components/assistant-chat/messages.tsx Updated types to use ChatMessage; renamed reload prop to regenerate.
apps/web/components/assistant-chat/multimodal-input.tsx Updated type annotations for props to use ChatMessage generics.
apps/web/components/assistant-chat/tools.tsx Replaced generic tool schemas with specific types; removed dispatcher; updated and renamed tool-related components.
apps/web/components/assistant-chat/types.ts Defined ChatMessage, ChatTools, and placeholder for UI data types; improved typing for input setter.
apps/web/package.json Upgraded ai and @ai-sdk/* dependencies to new beta versions; added @ai-sdk/provider.
apps/web/utils/ai/assistant/chat.ts Modularized tool definitions; improved type usage; updated message parameter types; removed onFinish callback.
apps/web/utils/ai/choose-rule/ai-choose-args.ts Updated error class, schema naming, and response parsing to match new conventions.
apps/web/utils/llms/index.ts Replaced CoreMessage with ModelMessage; updated streaming stop condition logic and callbacks.
apps/web/utils/llms/model.ts Switched to LanguageModelV2; commented out unsupported providers; updated OpenRouter logic.
apps/web/utils/redis/usage.ts Updated usage parameter to LanguageModelUsage; added new Redis fields for token tracking.
apps/web/utils/usage.ts Updated usage and cost calculation to use LanguageModelUsage and new token property names.
apps/web/components/assistant-chat/overview.tsx Removed external UseChatHelpers type import; changed setInput prop to direct function type; updated heading text and added CSS class for font size.
apps/web/components/assistant-chat/ChatContext.tsx Enforced stricter useChat usage by throwing error if used outside ChatProvider.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ChatUI
    participant ChatAPI
    participant aiProcessAssistantChat
    participant ToolModules
    participant Model

    User->>ChatUI: Enter message
    ChatUI->>ChatAPI: Send message (via DefaultChatTransport)
    ChatAPI->>aiProcessAssistantChat: Convert UI messages to model messages
    aiProcessAssistantChat->>ToolModules: Initialize tools with user/account
    aiProcessAssistantChat->>Model: Process chat with tools
    Model-->>aiProcessAssistantChat: Stream response
    aiProcessAssistantChat->>ChatAPI: Convert model messages to UI messages
    ChatAPI-->>ChatUI: Stream UI message response
    ChatUI-->>User: Display assistant response
Loading

Possibly related PRs

  • Add Ollama support #269: Adds Ollama support and integration, related to the removal of Ollama support in this PR.
  • Chat history #441: Introduces persistent chat state management and individual message saving, related to chat message handling refactored here.
  • New chat #444: Modifies chat creation logic and input schema, related by file to chat API route changes in this PR.

Poem

In the warren, code hops anew,
With tools and messages, shiny and true.
Types are crisp, the streams now flow,
Beta bunnies in the dependencies row.
Old hacks gone, new helpers appear—
The assistant chat is crystal clear!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/web/components/assistant-chat/ChatContext.tsx

Oops! Something went wrong! :(

ESLint: 9.28.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7976f8b and 0cb6d90.

📒 Files selected for processing (1)
  • apps/web/components/assistant-chat/ChatContext.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
apps/web/**/*.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • apps/web/CLAUDE.md
apps/web/**/*.tsx

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • apps/web/CLAUDE.md
**/*.tsx

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

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

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/form-handling.mdc
🧠 Learnings (1)
apps/web/components/assistant-chat/ChatContext.tsx (8)
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Prefer functional components with hooks
Learnt from: elie222
PR: elie222/inbox-zero#485
File: apps/web/app/(landing)/login/page.tsx:41-43
Timestamp: 2025-06-05T09:49:12.168Z
Learning: In Next.js App Router, components that use the `useSearchParams` hook require a Suspense boundary to handle the asynchronous nature of search parameter access. The Suspense wrapper is necessary and should not be removed when a component uses useSearchParams.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:59.468Z
Learning: For components with onClick handlers in Next.js App Router, ensure they are client components by including the 'use client' directive at the top of the file.
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: Custom React hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: For form text inputs in React using Shadcn UI, use the `Input` component with `registerProps` from a form library (such as react-hook-form) and pass any validation errors to the `error` prop.
⏰ 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: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/web/components/assistant-chat/ChatContext.tsx (1)

26-29: Excellent improvement to enforce proper context usage.

The change from a fallback return to throwing an error is a significant improvement that enforces proper usage of the useChat hook within its provider. This fail-fast approach prevents potential null pointer exceptions and makes the API more predictable and type-safe.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

@vercel
Copy link

vercel bot commented Jul 6, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ❌ Failed (Inspect) Jul 14, 2025 5:51pm

@socket-security
Copy link

socket-security bot commented Jul 6, 2025

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

🔭 Outside diff range comments (2)
apps/web/app/api/chat/route.ts (1)

1-14: Critical: appendResponseMessages is used but not imported

The function appendResponseMessages is called on line 102 but it's not imported at the top of the file. This will cause a runtime error. Based on the new imports, it seems this should be replaced with the new message conversion utilities.

Consider updating this section to use the new conversion utilities or add the missing import if the function still exists.

Also applies to: 102-114

apps/web/components/assistant-chat/message-editor.tsx (1)

87-88: Address the TypeScript error instead of suppressing it.

The @ts-expect-error comment indicates a type mismatch between UIMessage and the expected message type. This should be properly resolved rather than suppressed.

Consider updating the setMessages type definition or ensuring proper type compatibility:

-// @ts-expect-error todo: support UIMessage in setMessages
-setMessages((messages) => {
+setMessages((messages: ChatMessage[]) => {
🧹 Nitpick comments (4)
apps/web/utils/redis/usage.ts (1)

35-42: LGTM! Correct property mapping and new token types support.

The updates correctly:

  • Map outputTokens/inputTokens from the new LanguageModelUsage interface
  • Add support for cachedInputTokens and reasoningTokens
  • Use nullish coalescing to handle optional properties

Consider addressing the TODO comment about the naming inconsistency - the Redis keys still reference "openai" but now support any LLM.

apps/web/components/assistant-chat/message.tsx (1)

342-344: Consider using consistent error styling.

The ErrorToolCard uses inline styles. Consider using your design system's error components for consistency.

-function ErrorToolCard({ error }: { error: string }) {
-  return <div className="rounded border p-2 text-red-500">Error: {error}</div>;
-}
+function ErrorToolCard({ error }: { error: string }) {
+  return (
+    <Card className="border-destructive">
+      <CardContent className="p-2">
+        <p className="text-sm text-destructive">Error: {error}</p>
+      </CardContent>
+    </Card>
+  );
+}
apps/web/components/assistant-chat/chat.tsx (1)

178-188: Consider simplifying the destructuring pattern for better readability

The destructuring with property renaming in the function parameters makes the code harder to follow. Consider accepting the chat object as a whole or using a clearer destructuring pattern.

-function ChatUI({
-  chat: { messages, setMessages, status, stop, regenerate },
-  input,
-  setInput,
-  handleSubmit,
-}: {
-  chat: ReturnType<typeof useChat<ChatMessage>>;
-  input: string;
-  setInput: (input: string) => void;
-  handleSubmit: () => void;
-}) {
+function ChatUI({
+  chat,
+  input,
+  setInput,
+  handleSubmit,
+}: {
+  chat: ReturnType<typeof useChat<ChatMessage>>;
+  input: string;
+  setInput: (input: string) => void;
+  handleSubmit: () => void;
+}) {
+  const { messages, setMessages, status, stop, regenerate } = chat;
apps/web/components/assistant-chat/tools.tsx (1)

212-216: Simplify the generic type constraint

The generic type constraint is overly specific for an internal helper function. Consider using a simpler type or removing the generic altogether since this function is only used internally.

-  const formatActions = <
-    T extends { type: string; fields: Record<string, string | null> },
-  >(
-    actions: T[],
-  ) => {
+  const formatActions = (
+    actions: Array<{ type: string; fields: Record<string, string | null> }>,
+  ) => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 053574e and 3424d2f.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (18)
  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx (1 hunks)
  • apps/web/app/api/chat/route.ts (4 hunks)
  • apps/web/components/assistant-chat/chat.tsx (5 hunks)
  • apps/web/components/assistant-chat/data-stream-handler.tsx (0 hunks)
  • apps/web/components/assistant-chat/helpers.ts (1 hunks)
  • apps/web/components/assistant-chat/message-editor.tsx (4 hunks)
  • apps/web/components/assistant-chat/message.tsx (4 hunks)
  • apps/web/components/assistant-chat/messages.tsx (2 hunks)
  • apps/web/components/assistant-chat/multimodal-input.tsx (3 hunks)
  • apps/web/components/assistant-chat/tools.tsx (8 hunks)
  • apps/web/components/assistant-chat/types.ts (1 hunks)
  • apps/web/package.json (2 hunks)
  • apps/web/utils/ai/assistant/chat.ts (5 hunks)
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts (4 hunks)
  • apps/web/utils/llms/index.ts (9 hunks)
  • apps/web/utils/llms/model.ts (3 hunks)
  • apps/web/utils/redis/usage.ts (2 hunks)
  • apps/web/utils/usage.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/components/assistant-chat/data-stream-handler.tsx
🧰 Additional context used
📓 Path-based instructions (6)
`apps/web/**/*.{ts,tsx}`: Use TypeScript with strict null checks Path aliases: U...

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

📄 Source: CodeRabbit Inference Engine (apps/web/CLAUDE.md)

List of files the instruction was applied to:

  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx
  • apps/web/components/assistant-chat/helpers.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/redis/usage.ts
  • apps/web/components/assistant-chat/messages.tsx
  • apps/web/utils/usage.ts
  • apps/web/utils/llms/index.ts
  • apps/web/app/api/chat/route.ts
  • apps/web/components/assistant-chat/types.ts
  • apps/web/components/assistant-chat/multimodal-input.tsx
  • apps/web/utils/llms/model.ts
  • apps/web/components/assistant-chat/message-editor.tsx
  • apps/web/components/assistant-chat/message.tsx
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/components/assistant-chat/tools.tsx
  • apps/web/components/assistant-chat/chat.tsx
`apps/web/app/**/*`: NextJS app router structure with (app) directory

apps/web/app/**/*: NextJS app router structure with (app) directory

📄 Source: CodeRabbit Inference Engine (apps/web/CLAUDE.md)

List of files the instruction was applied to:

  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx
  • apps/web/app/api/chat/route.ts
`apps/web/**/*.tsx`: Follow tailwindcss patterns with prettier-plugin-tailwindcs...

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data

📄 Source: CodeRabbit Inference Engine (apps/web/CLAUDE.md)

List of files the instruction was applied to:

  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx
  • apps/web/components/assistant-chat/messages.tsx
  • apps/web/components/assistant-chat/multimodal-input.tsx
  • apps/web/components/assistant-chat/message-editor.tsx
  • apps/web/components/assistant-chat/message.tsx
  • apps/web/components/assistant-chat/tools.tsx
  • apps/web/components/assistant-chat/chat.tsx
`**/*.tsx`: For API GET requests to server, use the `swr` package Use `result?.serverError` with `toastError` and `toastSuccess` for error handling; success toast is optional

**/*.tsx: For API GET requests to server, use the swr package
Use result?.serverError with toastError and toastSuccess for error handling; success toast is optional

📄 Source: CodeRabbit Inference Engine (.cursor/rules/data-fetching.mdc)

List of files the instruction was applied to:

  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx
  • apps/web/components/assistant-chat/messages.tsx
  • apps/web/components/assistant-chat/multimodal-input.tsx
  • apps/web/components/assistant-chat/message-editor.tsx
  • apps/web/components/assistant-chat/message.tsx
  • apps/web/components/assistant-chat/tools.tsx
  • apps/web/components/assistant-chat/chat.tsx
`**/*.tsx`: Use React Hook Form with Zod for validation Validate form inputs before submission Show validation errors inline next to form fields

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

📄 Source: CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

List of files the instruction was applied to:

  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx
  • apps/web/components/assistant-chat/messages.tsx
  • apps/web/components/assistant-chat/multimodal-input.tsx
  • apps/web/components/assistant-chat/message-editor.tsx
  • apps/web/components/assistant-chat/message.tsx
  • apps/web/components/assistant-chat/tools.tsx
  • apps/web/components/assistant-chat/chat.tsx
`**/*.{ts,tsx}`: Define validation schemas using Zod Apply the same validation in both client and server Use descriptive error messages

**/*.{ts,tsx}: Define validation schemas using Zod
Apply the same validation in both client and server
Use descriptive error messages

📄 Source: CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

List of files the instruction was applied to:

  • apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx
  • apps/web/components/assistant-chat/helpers.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/redis/usage.ts
  • apps/web/components/assistant-chat/messages.tsx
  • apps/web/utils/usage.ts
  • apps/web/utils/llms/index.ts
  • apps/web/app/api/chat/route.ts
  • apps/web/components/assistant-chat/types.ts
  • apps/web/components/assistant-chat/multimodal-input.tsx
  • apps/web/utils/llms/model.ts
  • apps/web/components/assistant-chat/message-editor.tsx
  • apps/web/components/assistant-chat/message.tsx
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/components/assistant-chat/tools.tsx
  • apps/web/components/assistant-chat/chat.tsx
🧠 Learnings (16)
apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx (13)
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Prefer functional components with hooks
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.{ts,tsx} : Path aliases: Use `@/` for imports from project root
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: Each custom React hook should have a single responsibility and be kept as simple as possible.
Learnt from: elie222
PR: elie222/inbox-zero#485
File: apps/web/app/(landing)/login/page.tsx:41-43
Timestamp: 2025-06-05T09:49:12.168Z
Learning: In Next.js App Router, components that use the `useSearchParams` hook require a Suspense boundary to handle the asynchronous nature of search parameter access. The Suspense wrapper is necessary and should not be removed when a component uses useSearchParams.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: Custom React hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use LoadingContent component for async data
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:59.468Z
Learning: For components with onClick handlers in Next.js App Router, ensure they are client components by including the 'use client' directive at the top of the file.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: For data fetching in custom React hooks, prefer using the useSWR hook. The custom hook should typically wrap useSWR, handle the API endpoint URL, and return the data, loading state, error state, and potentially the mutate function from SWR.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:47.630Z
Learning: In deeply nested React components within the Next.js app directory, use the SWR library to fetch data via API instead of loading data directly in the component.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: To handle loading and error states in UI components, wrap content with a `LoadingContent` component that takes `loading` and `error` props, and only renders the main content when data is available.
apps/web/package.json (3)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: The project uses PostgreSQL as the database with Prisma.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/__mocks__/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.
apps/web/utils/ai/choose-rule/ai-choose-args.ts (6)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: Implement early returns for invalid inputs, use proper error types and logging, provide fallbacks for AI failures, and add retry logic for transient failures (e.g., using a 'withRetry' utility).
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: When implementing LLM-related functions in TypeScript, follow a standard structure: create a scoped logger, define a Zod schema for output validation, perform early input validation and returns, separate system and user prompts, log inputs and outputs, call the LLM with proper configuration, and return the validated result.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-06-23T12:27:35.927Z
Learning: Use lodash utilities for common operations involving arrays, objects, and strings to promote code consistency and reliability.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-06-23T12:27:23.938Z
Learning: Input validation schemas for server actions should be defined using Zod in dedicated .validation.ts files, which can be reused on the client for form validation.
apps/web/utils/redis/usage.ts (3)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: When implementing LLM-related functions in TypeScript, follow a standard structure: create a scoped logger, define a Zod schema for output validation, perform early input validation and returns, separate system and user prompts, log inputs and outputs, call the LLM with proper configuration, and return the validated result.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-06-23T12:27:23.938Z
Learning: Input validation schemas for server actions should be defined using Zod in dedicated .validation.ts files, which can be reused on the client for form validation.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
apps/web/components/assistant-chat/messages.tsx (3)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Prefer functional components with hooks
apps/web/utils/usage.ts (1)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/logging.mdc:0-0
Timestamp: 2025-06-23T12:26:43.177Z
Learning: In TypeScript backend code, use the `createScopedLogger` function from `@/utils/logger` to perform logging. Typically, instantiate the logger at the top of the file with a relevant scope string.
apps/web/utils/llms/index.ts (3)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: When implementing LLM-related functions in TypeScript, follow a standard structure: create a scoped logger, define a Zod schema for output validation, perform early input validation and returns, separate system and user prompts, log inputs and outputs, call the LLM with proper configuration, and return the validated result.
apps/web/app/api/chat/route.ts (5)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-06-23T12:26:14.189Z
Learning: Always use wrapper functions from the utils folder (e.g., apps/web/utils/gmail/message.ts) to interact with provider APIs, ensuring maintainability and easier future provider support.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/logging.mdc:0-0
Timestamp: 2025-06-23T12:26:43.177Z
Learning: In TypeScript backend code, use the `createScopedLogger` function from `@/utils/logger` to perform logging. Typically, instantiate the logger at the top of the file with a relevant scope string.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/__mocks__/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
apps/web/components/assistant-chat/types.ts (2)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: Use TypeScript types for all parameters and return values, and define clear interfaces for complex input and output structures to ensure type safety.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.{ts,tsx} : Use TypeScript with strict null checks
apps/web/components/assistant-chat/multimodal-input.tsx (4)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: For multi-line text input, use the `Input` component with `type="text"`, `autosizeTextarea`, and `rows` props to create an autosizing textarea, and handle validation and errors similarly to single-line inputs.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: For form text inputs in React using Shadcn UI, use the `Input` component with `registerProps` from a form library (such as react-hook-form) and pass any validation errors to the `error` prop.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.tsx : Validate form inputs before submission
apps/web/utils/llms/model.ts (2)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-06-23T12:26:27.693Z
Learning: When writing tests for LLM-related functionality in TypeScript (e.g., in 'apps/web/__tests__/*.test.ts'), always create helper functions for common test data to ensure consistency and reduce duplication.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
apps/web/components/assistant-chat/message-editor.tsx (2)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
apps/web/components/assistant-chat/message.tsx (11)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:59.468Z
Learning: For components with onClick handlers in Next.js App Router, ensure they are client components by including the 'use client' directive at the top of the file.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: Custom React hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Prefer functional components with hooks
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: For form text inputs in React using Shadcn UI, use the `Input` component with `registerProps` from a form library (such as react-hook-form) and pass any validation errors to the `error` prop.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: For data fetching in custom React hooks, prefer using the useSWR hook. The custom hook should typically wrap useSWR, handle the API endpoint URL, and return the data, loading state, error state, and potentially the mutate function from SWR.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-07-03T12:02:38.024Z
Learning: Applies to **/*.tsx : Use `result?.serverError` with `toastError` and `toastSuccess` for error handling; success toast is optional
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: To handle loading and error states in UI components, wrap content with a `LoadingContent` component that takes `loading` and `error` props, and only renders the main content when data is available.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.tsx : Show validation errors inline next to form fields
apps/web/utils/ai/assistant/chat.ts (5)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: When implementing LLM-related functions in TypeScript, follow a standard structure: create a scoped logger, define a Zod schema for output validation, perform early input validation and returns, separate system and user prompts, log inputs and outputs, call the LLM with proper configuration, and return the validated result.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-06-23T12:27:23.938Z
Learning: Input validation schemas for server actions should be defined using Zod in dedicated .validation.ts files, which can be reused on the client for form validation.
apps/web/components/assistant-chat/tools.tsx (8)
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Follow consistent naming conventions (PascalCase for components)
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/types/**/*.{ts,d.ts} : Centralize types in dedicated type files when shared
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Prefer functional components with hooks
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-07-03T12:02:38.024Z
Learning: For mutating data, use Next.js server actions
apps/web/components/assistant-chat/chat.tsx (16)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:47.630Z
Learning: In deeply nested React components within the Next.js app directory, use the SWR library to fetch data via API instead of loading data directly in the component.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Prefer functional components with hooks
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:59.468Z
Learning: Use SWR for data fetching in deeply nested components in Next.js App Router projects to enable efficient client-side data fetching and caching.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: For data fetching in custom React hooks, prefer using the useSWR hook. The custom hook should typically wrap useSWR, handle the API endpoint URL, and return the data, loading state, error state, and potentially the mutate function from SWR.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-06-23T12:26:59.468Z
Learning: For components with onClick handlers in Next.js App Router, ensure they are client components by including the 'use client' directive at the top of the file.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: When fetching data from an API in a Next.js React application, use the `swr` package for GET requests to the server. This provides built-in caching, revalidation, and error handling.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-07-03T12:02:38.024Z
Learning: Applies to **/*.tsx : For API GET requests to server, use the `swr` package
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-06-23T12:26:16.769Z
Learning: Custom React hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-03T12:02:16.137Z
Learning: Applies to apps/web/**/*.tsx : Use LoadingContent component for async data
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-06-23T12:26:14.189Z
Learning: Always use wrapper functions from the utils folder (e.g., apps/web/utils/gmail/message.ts) to interact with provider APIs, ensuring maintainability and easier future provider support.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-07-03T12:02:38.024Z
Learning: For mutating data, use Next.js server actions
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-06-23T12:27:23.938Z
Learning: Server actions must only be used for mutations (create, update, delete operations) and never for data fetching (GET operations); data fetching should be handled via dedicated GET API routes and SWR hooks.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: For form text inputs in React using Shadcn UI, use the `Input` component with `registerProps` from a form library (such as react-hook-form) and pass any validation errors to the `error` prop.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-06-23T12:27:33.499Z
Learning: For multi-line text input, use the `Input` component with `type="text"`, `autosizeTextarea`, and `rows` props to create an autosizing textarea, and handle validation and errors similarly to single-line inputs.
🧬 Code Graph Analysis (9)
apps/web/components/assistant-chat/helpers.ts (2)
apps/web/app/api/chats/[chatId]/route.ts (1)
  • GetChatResponse (5-5)
apps/web/components/assistant-chat/types.ts (3)
  • ChatMessage (44-49)
  • CustomUIDataTypes (33-42)
  • ChatTools (21-30)
apps/web/components/assistant-chat/messages.tsx (1)
apps/web/components/assistant-chat/types.ts (1)
  • ChatMessage (44-49)
apps/web/app/api/chat/route.ts (2)
apps/web/components/assistant-chat/helpers.ts (1)
  • convertToUIMessages (9-20)
apps/web/utils/ai/assistant/chat.ts (1)
  • aiProcessAssistantChat (645-947)
apps/web/components/assistant-chat/types.ts (1)
apps/web/utils/ai/assistant/chat.ts (8)
  • GetUserRulesAndSettingsTool (125-127)
  • GetLearnedPatternsTool (176-178)
  • CreateRuleTool (247-247)
  • UpdateRuleConditionsTool (348-350)
  • UpdateRuleActionsTool (460-462)
  • UpdateLearnedPatternsTool (563-565)
  • UpdateAboutTool (600-600)
  • AddToKnowledgeBaseTool (641-643)
apps/web/components/assistant-chat/multimodal-input.tsx (1)
apps/web/components/assistant-chat/types.ts (1)
  • ChatMessage (44-49)
apps/web/utils/llms/model.ts (2)
apps/web/utils/llms/config.ts (1)
  • Provider (7-15)
apps/web/env.ts (1)
  • env (5-214)
apps/web/components/assistant-chat/message-editor.tsx (1)
apps/web/components/assistant-chat/types.ts (1)
  • ChatMessage (44-49)
apps/web/components/assistant-chat/message.tsx (2)
apps/web/components/assistant-chat/types.ts (1)
  • ChatMessage (44-49)
apps/web/components/assistant-chat/tools.tsx (7)
  • BasicToolInfo (23-29)
  • CreatedRuleToolCard (31-102)
  • UpdatedRuleConditions (104-191)
  • UpdatedRuleActions (193-279)
  • UpdatedLearnedPatterns (281-335)
  • UpdateAbout (337-344)
  • AddToKnowledgeBase (346-369)
apps/web/components/assistant-chat/tools.tsx (2)
apps/web/components/ui/card.tsx (1)
  • Card (137-137)
apps/web/utils/ai/assistant/chat.ts (6)
  • CreateRuleTool (247-247)
  • UpdateRuleConditionsTool (348-350)
  • UpdateRuleActionsTool (460-462)
  • UpdateLearnedPatternsTool (563-565)
  • UpdateAboutTool (600-600)
  • AddToKnowledgeBaseTool (641-643)
🪛 GitHub Check: test
apps/web/utils/llms/model.ts

[failure] 106-106: utils/llms/model.test.ts > Models > getModel > should configure Ollama model correctly
Error: Ollama is not supported. Revert to version v1.7.28 or older to use it.
❯ selectModel utils/llms/model.ts:106:13
❯ selectDefaultModel utils/llms/model.ts:263:10
❯ Module.getModel utils/llms/model.ts:19:7
❯ utils/llms/model.test.ts:167:22

⏰ 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: Analyze (javascript-typescript)
🔇 Additional comments (25)
apps/web/app/(app)/[emailAccountId]/simple/Summary.tsx (1)

3-3: LGTM! Import path updated correctly for AI SDK v5.

The import path change from "ai/react" to "@ai-sdk/react" aligns with the AI SDK v5 migration and package.json updates.

apps/web/components/assistant-chat/helpers.ts (1)

9-20: LGTM! Well-structured helper function with proper error handling.

The convertToUIMessages function correctly:

  • Handles null/undefined chat with optional chaining
  • Performs appropriate type casting for the AI SDK v5 migration
  • Returns empty array as fallback

Consider uncommenting the metadata section in the future if timestamp information is needed in the UI.

apps/web/utils/ai/choose-rule/ai-choose-args.ts (4)

2-2: LGTM! Correct error class import for AI SDK v5.

The import change from InvalidToolArgumentsError to InvalidArgumentError aligns with the AI SDK v5 API updates.


83-83: LGTM! Correct schema property name for AI SDK v5.

The change from parameters to inputSchema follows the new AI SDK v5 naming convention for tool configuration.


97-97: LGTM! Updated retry condition for new error type.

The retry condition correctly checks for InvalidArgumentError instances, matching the updated import.


107-107: LGTM! Correct tool call property access for AI SDK v5.

The change from toolCall.args to toolCall.input aligns with the new AI SDK v5 tool call structure.

apps/web/utils/redis/usage.ts (2)

3-3: LGTM! Correct type import for AI SDK v5.

The import of LanguageModelUsage from the ai package aligns with the standardized usage tracking in AI SDK v5.


27-27: LGTM! Updated parameter type for consistency.

The change to use LanguageModelUsage type provides better type safety and consistency with the AI SDK v5 interface.

apps/web/components/assistant-chat/messages.tsx (1)

8-17: Type safety improvements look good!

The migration to use the ChatMessage type parameter for UseChatHelpers and the rename from reload to regenerate improve type specificity and API clarity. These changes are consistent with the broader assistant chat refactor.

Also applies to: 23-23, 42-42

apps/web/utils/usage.ts (1)

1-1: Usage tracking migration looks correct!

The updates to use LanguageModelUsage type and the property renaming from promptTokens/completionTokens to inputTokens/outputTokens properly align with AI SDK v5 conventions. The nullish coalescing operators with fallback to 0 ensure safe handling of optional properties.

Also applies to: 18-18, 29-31, 139-139

apps/web/components/assistant-chat/multimodal-input.tsx (1)

14-14: Type refinements are consistent and correct!

The addition of the ChatMessage type parameter to all UseChatHelpers type annotations improves type safety without changing any logic. These updates align well with the broader migration to AI SDK v5.

Also applies to: 29-38, 172-172

apps/web/utils/llms/model.ts (1)

77-104: OpenRouter workaround is reasonable but needs error handling

The temporary workaround using OpenAI client with OpenRouter's endpoint is understandable given the blocked dependency. However, consider adding error handling or validation to ensure the OpenRouter models work correctly with the OpenAI client wrapper.

Would you like me to add error handling to catch any compatibility issues between OpenRouter models and the OpenAI client?

apps/web/utils/llms/index.ts (4)

4-4: Good type migration to ModelMessage.

The migration from Message to ModelMessage and addition of stepCountIs aligns well with the AI SDK v5 updates.

Also applies to: 13-13


135-135: Explicit output parameter improves clarity.

Adding output: "object" makes the expected output format explicit, which is a good practice.


197-197: Clean migration to flexible stopping conditions.

The migration from maxSteps to stopWhen with stepCountIs provides more flexible control over generation stopping criteria while maintaining backward compatibility.

Also applies to: 279-279, 334-334


302-302: Verify the removal of await is intentional.

Removing await from the streamText call changes the return type to the stream itself rather than the resolved value. While the comment indicates this function is "not in use atm", this is a breaking change if any code depends on it.

Also applies to: 328-328

apps/web/components/assistant-chat/types.ts (1)

1-50: Well-structured type definitions for the chat system.

The type definitions provide a solid foundation for the chat system with proper separation of concerns:

  • Tool types are properly imported and aggregated
  • The ChatMessage type correctly specializes UIMessage
  • Placeholder comments indicate planned future extensions
apps/web/components/assistant-chat/message-editor.tsx (1)

114-119: Clean text extraction helper.

The getTextFromMessage helper properly handles the new message structure by filtering and joining text parts.

apps/web/components/assistant-chat/message.tsx (1)

111-333: Comprehensive tool-specific handling improves type safety and UX.

The migration from generic tool handling to specific handlers for each tool type provides:

  • Better type safety with tool-specific input/output types
  • Consistent error handling across all tools
  • Tailored UI for each tool's input and output states

The implementation follows a consistent pattern which makes it maintainable.

apps/web/utils/ai/assistant/chat.ts (2)

29-643: Excellent modularization of chat tools.

The refactoring of inline tool definitions into separate functions provides:

  • Better code organization and reusability
  • Clear separation of concerns
  • Consistent parameter passing pattern
  • Type safety with InferUITool exports

Each tool follows a consistent pattern with proper error handling and database operations.


651-651: Clean integration of modularized tools.

The use of toolOptions object and consistent tool instantiation pattern makes the code more maintainable and reduces parameter duplication.

Also applies to: 921-942

apps/web/components/assistant-chat/chat.tsx (2)

97-98: LGTM! Clean local state management implementation

The local input state management and the handleSubmit function properly handle message creation with the new message format structure.

Also applies to: 131-143


106-114: Context Is Preserved Server-Side
The server’s /api/chat/route.ts loads the full conversation from the database, prepends the incoming message (message: messages.at(-1)), and then passes [message, ...existingMessages] into aiProcessAssistantChat. Sending only the last message on the client is intentional to reduce payload, since the backend rehydrates the full history before calling the AI.

apps/web/components/assistant-chat/tools.tsx (2)

4-11: LGTM! Well-organized type imports

The migration to specific tool types from the utils module improves type safety and aligns with the modularization of tool definitions.


31-37: LGTM! Improved component naming and type safety

The component renaming to include specific tool names and the use of dedicated tool types significantly improves code clarity and type safety.

Also applies to: 104-114, 193-203, 281-287, 337-344, 346-350

Comment on lines 105 to 116
case Provider.OLLAMA: {
const model = aiModel || env.NEXT_PUBLIC_OLLAMA_MODEL;
if (!model) throw new Error("Ollama model is not set");
return {
provider: Provider.OLLAMA!,
model,
llmModel: createOllama({ baseURL: env.OLLAMA_BASE_URL })(model),
};
throw new Error(
"Ollama is not supported. Revert to version v1.7.28 or older to use it.",
);
// const model = aiModel || env.NEXT_PUBLIC_OLLAMA_MODEL;
// if (!model) throw new Error("Ollama model is not set");
// return {
// provider: Provider.OLLAMA!,
// model,
// llmModel: createOllama({ baseURL: env.OLLAMA_BASE_URL })(model),
// };
}
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

Consider a more graceful approach for Ollama deprecation

Throwing an error for Ollama users breaks existing functionality. This could be handled more gracefully:

  1. Log a deprecation warning
  2. Provide migration guidance
  3. Consider feature flagging to allow users to opt-in to the v5 migration

The test failure confirms this breaks existing functionality.

Would you like me to implement a more graceful deprecation strategy that maintains backward compatibility while warning users about the upcoming removal?

🧰 Tools
🪛 GitHub Check: test

[failure] 106-106: utils/llms/model.test.ts > Models > getModel > should configure Ollama model correctly
Error: Ollama is not supported. Revert to version v1.7.28 or older to use it.
❯ selectModel utils/llms/model.ts:106:13
❯ selectDefaultModel utils/llms/model.ts:263:10
❯ Module.getModel utils/llms/model.ts:19:7
❯ utils/llms/model.test.ts:167:22

🤖 Prompt for AI Agents
In apps/web/utils/llms/model.ts between lines 105 and 116, the current code
throws an error immediately when the Provider is Ollama, which breaks existing
functionality. Instead, replace the error throw with a console warning or logger
call that informs users about the deprecation and suggests reverting to version
v1.7.28 or older. Optionally, implement a feature flag to allow users to opt-in
to the new version while maintaining backward compatibility. This approach will
prevent breaking existing users and provide clear migration guidance.

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 (1)
apps/web/utils/llms/index.ts (1)

301-352: Consider removing commented code.

The streamCompletionTools function has been updated to match the new patterns but is commented out. If this function is no longer needed, consider removing it entirely to keep the codebase clean. If it might be used in the future, consider moving it to a separate file or adding a TODO comment explaining why it's kept.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6597855 and 9e47468.

📒 Files selected for processing (3)
  • apps/web/app/api/chat/route.ts (3 hunks)
  • apps/web/utils/ai/assistant/chat.ts (5 hunks)
  • apps/web/utils/llms/index.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/utils/ai/assistant/chat.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/web/**/*.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • apps/web/CLAUDE.md
**/*.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/form-handling.mdc
apps/web/app/**/*

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • apps/web/CLAUDE.md
🧠 Learnings (2)
apps/web/utils/llms/index.ts (5)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Use descriptive error messages
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: When implementing LLM-related functions in TypeScript, follow a standard structure: create a scoped logger, define a Zod schema for output validation, perform early input validation and returns, separate system and user prompts, log inputs and outputs, call the LLM with proper configuration, and return the validated result.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-06-23T12:26:36.694Z
Learning: Implement early returns for invalid inputs, use proper error types and logging, provide fallbacks for AI failures, and add retry logic for transient failures (e.g., using a 'withRetry' utility).
apps/web/app/api/chat/route.ts (2)
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-03T12:02:53.001Z
Learning: Applies to **/*.{ts,tsx} : Define validation schemas using Zod
🧬 Code Graph Analysis (1)
apps/web/utils/llms/index.ts (1)
apps/web/utils/usage.ts (1)
  • saveAiUsage (8-41)
⏰ 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: Static Code Analysis Js
  • GitHub Check: Jit Security
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
apps/web/app/api/chat/route.ts (2)

1-10: LGTM! Imports properly updated for AI SDK v5.

The migration to use convertToModelMessages and UIMessage types aligns with the new SDK structure. Good addition of the Prisma type import for type safety.


78-82: Excellent refactor to use batch message saving!

The new streaming response pattern with toUIMessageStreamResponse and batch saving in onFinish is more efficient than the previous individual message saves.

apps/web/utils/llms/index.ts (3)

4-14: Type updates correctly implemented for AI SDK v5.

All CoreMessage references have been properly replaced with ModelMessage, and the new streaming callback types are correctly imported and used throughout the file.

Also applies to: 104-104, 175-175, 246-246


194-194: Good implementation of the new stopWhen pattern.

The migration from maxSteps to stopWhen: maxSteps ? stepCountIs(maxSteps) : undefined provides more flexibility and aligns with AI SDK v5's step control mechanism.

Also applies to: 278-278


200-210: Efficient concurrent promise handling!

Using Promise.all to execute usage saving and the onFinish callback concurrently is a good performance optimization since these operations are independent.

@elie222
Copy link
Owner Author

elie222 commented Jul 24, 2025

Closed in favour of: #592

@elie222 elie222 closed this Jul 24, 2025
@elie222 elie222 deleted the chore/ai-sdk-v5 branch December 18, 2025 22:59
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

Comments