Skip to content

Conversation

@nettee
Copy link
Contributor

@nettee nettee commented Dec 9, 2025

Summary

This PR introduces support for the "auto" model, enabling intelligent model selection and routing.

Key changes include:

  • Provider & UI: Created a new provider and provider item for the auto model, adding its corresponding icon and tooltip.
  • Default Configuration: Agent nodes (both manually created and Copilot-generated) now default to the auto model. Updated the DEFAULT_MODEL_AGENT environment variable's default value to auto.
  • Routing Logic: Implemented auto model routing to intercept model configuration retrieval, laying the groundwork for future intelligent routing strategies and Langfuse monitoring.
  • Billing: Modified the billing logic to calculate auto model costs based on the underlying real model's token usage and the auto model's rate.

Impact Areas

Please check the areas this PR affects:

  • Multi-threaded Dialogues
  • AI-Powered Capabilities (Web Search, Knowledge Base Search, Question Recommendations)
  • Context Memory & References
  • Knowledge Base Integration & RAG
  • Quotes & Citations
  • AI Document Editing & WYSIWYG
  • Free-form Canvas Interface
  • Other

Screenshots/Videos

Before After
... ...

Checklist

Important

Please review the checklist below before submitting your pull request.

  • This change requires a documentation update, included: Refly Documentation
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.
  • I ran dev/reformat(backend) and cd web && npx lint-staged(frontend) to appease the lint gods

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced smart model routing that automatically selects the best available AI model when using the auto-model option.
    • Added descriptive tooltips for models to provide helpful guidance during model selection.
  • Improvements

    • Enhanced default model selection in canvas workflows to use agent models by default.
    • Improved billing transparency to accurately track and display which model was used for billing purposes when auto-routing is active.
  • API Updates

    • Added tooltip field to model configuration schemas for displaying model descriptions.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 9, 2025

Walkthrough

This PR implements automatic model routing capability. When users select an "Auto" model, the system routes requests to an appropriate model from a priority list while tracking the original Auto model selection for billing and logging purposes. The feature spans backend routing logic, frontend UI components, and credit tracking systems.

Changes

Cohort / File(s) Summary
Auto Model Routing Core
packages/utils/src/auto-model.ts, packages/utils/src/index.ts, apps/api/src/modules/provider/auto-model-router.service.ts
Introduces AUTO_MODEL_ID constant, routing priority list, isAutoModel() helper function, and AutoModelRouter service that routes Auto models to available non-reasoning models based on priority, embedding routeData with originalItemId and originalModelId.
Provider Service Integration
apps/api/src/modules/provider/provider.service.ts, packages/providers/src/llm/index.ts
Integrates AutoModelRouter into prepareModelProviderMap to route Auto model selections; adds routeData metadata injection into LLM chat model common parameters.
Skill Execution & Billing
apps/api/src/modules/skill/skill.service.ts, apps/api/src/modules/skill/skill-invoker.service.ts
Updates skill execution to use routed provider items from prepareModelProviderMap while preserving original modelItemId for display; implements Auto model detection in credit processing to track billing model name separately from actual execution model.
Credit & Billing Tracking
apps/api/src/modules/credit/credit.dto.ts, apps/api/src/modules/credit/credit.service.ts
Adds billingModelName and actualModelName fields to credit tracking DTOs; updates credit usage recording to distinguish between the billed model and the actual execution model.
Canvas & State Initialization
apps/api/src/modules/canvas/canvas.service.ts, packages/canvas-common/src/sync.ts
Canvas creation now fetches default agent model and passes it as defaultModelInfo to initEmptyCanvasState; updated initEmptyCanvasState signature to accept optional configuration with defaultModelInfo.
Frontend Model Selection
packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx, packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx
Added defaultScene prop ('chat' or 'agent') to ModelSelector to support scene-specific default model selection; updated configure tab to pass defaultScene="agent".
Frontend UI Components & Hooks
packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx, packages/ai-workspace-common/src/components/common/icon.tsx, packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts, packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
Replaced defaultChatModel references with defaultAgentModel; added AutoIcon rendering for Auto models in ModelIcon; introduced defaultAgentModel derivation from user preferences in useFetchProviderItems hook.
Schema & Type Updates
packages/openapi-schema/schema.yml, packages/openapi-schema/src/schemas.gen.ts, packages/openapi-schema/src/types.gen.ts, packages/utils/src/provider.ts
Added optional tooltip field to ModelInfo, LLMModelConfig, and MediaGenerationModelConfig across schema definitions and types; updated providerItemToModelInfo to include tooltip from provider config.

Sequence Diagram

sequenceDiagram
    participant User
    participant Frontend as Frontend UI
    participant Provider as Provider Service
    participant Router as AutoModelRouter
    participant Skill as Skill Service
    participant Invoker as SkillInvoker
    participant Credit as Credit Service

    User->>Frontend: Select model (Auto or direct)
    Frontend->>Provider: prepareModelProviderMap(llmItems, userId)
    
    alt Model is Auto
        Provider->>Router: route(chatItem)
        Router->>Router: findAvailableModel() from priority list
        Router->>Provider: return routed model with routeData
    else Model is direct
        Provider->>Provider: pass through unchanged
    end
    
    Provider->>Skill: Use routed model in execution context
    Skill->>Invoker: _invokeSkill with model result
    Invoker->>Invoker: Detect Auto model via routeData
    
    alt Routed via Auto
        Invoker->>Credit: Process with Auto model's billing rate
        Credit->>Credit: billingModelName = Auto model, actualModelName = routed model
    else Direct model
        Invoker->>Credit: Process with direct model's billing rate
    end
    
    Credit->>Credit: Record credit usage with model tracking
    Credit-->>User: Billing recorded
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Areas requiring extra attention:

  • AutoModelRouter logic (apps/api/src/modules/provider/auto-model-router.service.ts): Verify priority-based routing, handling of edge cases when no eligible models exist, and routeData embedding correctness.
  • Billing attribution (apps/api/src/modules/skill/skill-invoker.service.ts and credit.service.ts): Ensure Auto model detection and billing model vs. actual model separation is accurate; verify credit rate is applied correctly from the routed model.
  • State flow consistency (skill.service.ts and canvas.service.ts): Confirm that original modelItemId is preserved for display while routed item is used for execution context.
  • Frontend defaultScene propagation (model-selector.tsx): Validate that agent vs. chat defaults are applied correctly and that dependency arrays are complete in useCallback/useEffect hooks.

Possibly related PRs

Suggested reviewers

  • mrcfps
  • lefarcen
  • pftom

🐰 Hop through Auto routes with grace,
Smart models find their perfect place!
Billing tracked from start to end,
On routing logic we depend. ✨🤖

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
Title check ✅ Passed The pull request title clearly summarizes the main objective: adding auto model support and default configuration, which aligns with the substantial changes across provider routing, UI defaults, and billing logic.
Description check ✅ Passed The PR description provides a clear summary of changes, identifies impact areas, and includes all required checklist items marked appropriately. However, it does not explicitly state which issue(s) are being fixed using the recommended Close/Resolves syntax.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/auto-model

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

@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: 6

🧹 Nitpick comments (10)
apps/api/src/tracer.ts (1)

6-6: Remove dead code: commented Prisma import and unused _instrumentations

Line 6’s commented-out PrismaInstrumentation import and the unused _instrumentations on Line 75 are both dead code. They add noise and may trigger lint warnings without providing value.

You can safely remove them and keep a single instrumentations definition.

-import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
+import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
@@
-import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
-// import { PrismaInstrumentation } from '@prisma/instrumentation';
+import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
@@
-  if (options.langfuse) {
-    const processor = createLangfuseProcessor(options.langfuse);
-    if (processor) spanProcessors.push(processor);
-  }
-
-  const _instrumentations = [getNodeAutoInstrumentations()];
-  const instrumentations = [getNodeAutoInstrumentations()];
+  if (options.langfuse) {
+    const processor = createLangfuseProcessor(options.langfuse);
+    if (processor) spanProcessors.push(processor);
+  }
+
+  const instrumentations = [getNodeAutoInstrumentations()];

Also applies to: 75-75

packages/providers/src/llm/index.ts (1)

26-28: Tighten typing for routeData and consider merging existing metadata / tags

The new routeData handling is conceptually sound, but two details are worth adjusting:

  1. Type-safety and optional chaining

Using as any on config weakens type safety and conflicts with the guideline to avoid any. You can keep things typed while still allowing the extra field, and use optional chaining:

-  const routeData = (config as any).routeData;
+  const routeData = (
+    config as LLMModelConfig & { routeData?: Record<string, unknown> }
+  )?.routeData;
  1. Preserving existing metadata / tags

...(routeData ? { metadata: routeData, tags: ['auto-routed'] } : {}) will overwrite any metadata or tags already passed via params/extraParams whenever routeData is present. If callers are already using those fields, this could silently drop important information. Consider merging instead, e.g.:

  • metadata: { ...(existingMetadata ?? {}), routeData }
  • tags: [...(existingTags ?? []), 'auto-routed']

so that auto-routing annotations are additive rather than destructive. As per coding guidelines, this also keeps types explicit and avoids relying on any.

Also applies to: 33-35

packages/openapi-schema/schema.yml (1)

10080-10082: Clarify tooltip vs. description for model configs

LLMModelConfig uses only tooltip as a UI hint, while MediaGenerationModelConfig includes both description and tooltip. Decide whether to align these patterns—either add description to LLMs, or remove it from media models if tooltip alone is sufficient.

packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts (1)

11-12: defaultAgentModel derivation and fallback look correct

Deriving defaultAgentModelId from user preferences and resolving it against providerItems?.data is consistent with how defaultChatModel is computed. The returned defaultAgentModel correctly prefers the agent default and falls back to the chat default, preserving a usable model for existing consumers.

If you ever want to micro-optimize, you could avoid calling providerItemToModelInfo twice for the same provider item by memoizing or reusing the mapped value, but it is not necessary given the small scale here.

Also applies to: 34-48

packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx (1)

1-11: Inline model tooltip rendering is well-integrated

The updated ModelLabel cleanly surfaces model.tooltip with a vertical divider and keeps the main label truncatable, which fits the selector UI. The new Divider import and flex layout look consistent with existing patterns.

If you expect very long tooltip content from the backend, you might consider wrapping model.tooltip with an antd Tooltip (or adding truncation) to avoid overflow in narrower menus, but that’s optional.

Also applies to: 118-137

packages/utils/src/auto-model.ts (1)

15-23: isAutoModel logic is sound; consider tightening typing around safeParseJSON.

The runtime behavior (early-return on falsy/parse failure, then comparing modelId) is correct. To make the types line up better with the runtime checks and avoid relying on an implicit any from safeParseJSON, you could treat the parsed value as possibly null and guard modelId explicitly:

-export const isAutoModel = (configStr: string | null | undefined): boolean => {
-  if (!configStr) {
-    return false;
-  }
-  const config: LLMModelConfig = safeParseJSON(configStr);
-  if (!config) {
-    return false;
-  }
-  return config.modelId === AUTO_MODEL_ID;
-};
+export const isAutoModel = (configStr: string | null | undefined): boolean => {
+  if (!configStr) {
+    return false;
+  }
+
+  const config = safeParseJSON(configStr) as LLMModelConfig | null;
+  if (!config?.modelId) {
+    return false;
+  }
+
+  return config.modelId === AUTO_MODEL_ID;
+};

This keeps the same behavior while making the nullability and shape of config explicit.

apps/api/src/modules/skill/skill.service.ts (1)

486-497: Clarify the flow and type safety of routed provider item.

The logic correctly separates validation (findAndCheckProviderItem) from routing (prepareModelProviderMap). However, line 497 uses a type assertion that depends on prepareModelProviderMap returning items with the provider relation included.

The comment on lines 493-496 is helpful, but the type assertion could fail silently if prepareModelProviderMap ever returns items without the provider field populated.

Consider adding a runtime check or updating the return type of prepareModelProviderMap to explicitly include the provider relation:

-    const providerItem = modelProviderMap.chat as ProviderItemModel & { provider: ProviderModel };
+    const providerItem = modelProviderMap.chat as ProviderItemModel & { provider: ProviderModel };
+    if (!providerItem?.provider) {
+      throw new ProviderItemNotFoundError('provider information missing for routed model');
+    }
auto-model.md (2)

70-76: Track unresolved compatibility concerns.

These TODO items highlight legitimate UX issues:

  1. Vision capability: If config.capabilities.vision isn't set, users won't see the image upload button even though the routed model (Sonnet 4.5) supports vision.
  2. Context limit: Without config.contextLimit, the frontend may show "Limit: 0" or trigger false token-exceeded warnings.

The SQL seed on line 61 does include these fields, but ensure this configuration is actually applied and tested.

Would you like me to open an issue to track these compatibility concerns?


201-201: Add language specifier to fenced code block.

The data flow diagram code block lacks a language specifier, which can affect rendering. Since it's a text-based diagram, consider using text or plaintext.

-```
+```text
 用户选择 Auto
apps/api/src/modules/provider/provider.service.ts (1)

941-956: Consider explicitly filtering out Auto model from candidates.

The loop builds modelMap but doesn't filter out the Auto model itself. If the Auto model has modelId: 'auto' in its config and isn't marked as reasoning, it could be added to modelMap, potentially causing issues.

       // Skip reasoning models
       if (config.capabilities?.reasoning === true) {
         continue;
       }

+      // Skip Auto model to prevent self-routing
+      if (config.modelId === AUTO_MODEL_ID) {
+        continue;
+      }
+
       if (config.modelId) {
         modelMap.set(config.modelId, item);
       }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 79b3c2a and 5f7689b.

⛔ Files ignored due to path filters (1)
  • packages/ai-workspace-common/src/assets/auto-model.svg is excluded by !**/*.svg
📒 Files selected for processing (17)
  • apps/api/src/modules/provider/provider.service.ts (4 hunks)
  • apps/api/src/modules/skill/skill-invoker.service.ts (4 hunks)
  • apps/api/src/modules/skill/skill.service.ts (5 hunks)
  • apps/api/src/tracer.ts (2 hunks)
  • auto-model.md (1 hunks)
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx (3 hunks)
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx (2 hunks)
  • packages/ai-workspace-common/src/components/common/icon.tsx (2 hunks)
  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts (3 hunks)
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts (2 hunks)
  • packages/openapi-schema/schema.yml (3 hunks)
  • packages/openapi-schema/src/schemas.gen.ts (3 hunks)
  • packages/openapi-schema/src/types.gen.ts (3 hunks)
  • packages/providers/src/llm/index.ts (1 hunks)
  • packages/utils/src/auto-model.ts (1 hunks)
  • packages/utils/src/index.ts (1 hunks)
  • packages/utils/src/provider.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (22)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{js,ts,jsx,tsx}: Always use optional chaining (?.) when accessing object properties
Always use nullish coalescing (??) or default values for potentially undefined values
Always check array existence before using array methods
Always validate object properties before destructuring
Always use single quotes for string literals in JavaScript/TypeScript code

**/*.{js,ts,jsx,tsx}: Use semicolons at the end of statements
Include spaces around operators (e.g., a + b instead of a+b)
Always use curly braces for control statements
Place opening braces on the same line as their statement

**/*.{js,ts,jsx,tsx}: Group import statements in order: React/framework libraries, third-party libraries, internal modules, relative path imports, type imports, style imports
Sort imports alphabetically within each import group
Leave a blank line between import groups
Extract complex logic into custom hooks
Use functional updates for state (e.g., setCount(prev => prev + 1))
Split complex state into multiple state variables rather than single large objects
Use useReducer for complex state logic instead of multiple useState calls

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}

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

**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}: All code comments MUST be written in English
All variable names, function names, class names, and other identifiers MUST use English words
Comments should be concise and explain 'why' rather than 'what'
Use proper grammar and punctuation in comments
Keep comments up-to-date when code changes
Document complex logic, edge cases, and important implementation details
Use clear, descriptive names that indicate purpose
Avoid abbreviations unless they are universally understood

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{js,ts,tsx,jsx}

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

Use JSDoc style comments for functions and classes in JavaScript/TypeScript

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Use single quotes for string literals in TypeScript/JavaScript
Always use optional chaining (?.) when accessing object properties in TypeScript/JavaScript
Always use nullish coalescing (??) or default values for potentially undefined values in TypeScript/JavaScript
Always check array existence before using array methods in TypeScript/JavaScript
Validate object properties before destructuring in TypeScript/JavaScript
Use ES6+ features like arrow functions, destructuring, and spread operators in TypeScript/JavaScript
Avoid magic numbers and strings - use named constants in TypeScript/JavaScript
Use async/await instead of raw promises for asynchronous code in TypeScript/JavaScript

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Avoid using any type whenever possible - use unknown type instead with proper type guards
Always define explicit return types for functions, especially for public APIs
Prefer extending existing types over creating entirely new types
Use TypeScript utility types (Partial<T>, Pick<T, K>, Omit<T, K>, Readonly<T>, Record<K, T>) to derive new types
Use union types and intersection types to combine existing types
Always import types explicitly using the import type syntax
Group type imports separately from value imports
Minimize creating local type aliases for imported types

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{js,ts,jsx,tsx,css,json}

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

Maximum line length of 100 characters

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml}

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

Use 2 spaces for indentation, no tabs

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/openapi-schema/schema.yml
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}

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

No trailing whitespace at the end of lines

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • auto-model.md
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/openapi-schema/schema.yml
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{css,scss,sass,less,js,jsx,ts,tsx}

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

**/*.{css,scss,sass,less,js,jsx,ts,tsx}: Primary color (#155EEF) should be used for main brand color in buttons, links, and accents
Error color (#F04438) should be used for error states and destructive actions
Success color (#12B76A) should be used for success states and confirmations
Warning color (#F79009) should be used for warnings and important notifications
Info color (#0BA5EC) should be used for informational elements

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use the translation wrapper component and useTranslation hook in components
Ensure all user-facing text is translatable

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{tsx,ts,json}

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

Support dynamic content with placeholders in translations

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{tsx,ts,jsx,js,vue,css,scss,less}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue,css,scss,less}: Use the primary blue (#155EEF) for main UI elements, CTAs, and active states
Use red (#F04438) only for errors, warnings, and destructive actions
Use green (#12B76A) for success states and confirmations
Use orange (#F79009) for warning states and important notifications
Use blue (#0BA5EC) for informational elements
Primary buttons should be solid with the primary color
Secondary buttons should have a border with transparent or light background
Danger buttons should use the error color
Use consistent padding, border radius, and hover states for all buttons
Follow fixed button sizes based on their importance and context
Use consistent border radius (rounded-lg) for all cards
Apply light shadows (shadow-sm) for card elevation
Maintain consistent padding inside cards (p-4 or p-6)
Use subtle borders for card separation
Ensure proper spacing between card elements
Apply consistent styling to all form inputs
Use clear visual indicators for focus, hover, and error states in form elements
Apply proper spacing between elements using 8px, 16px, 24px increments
Ensure proper alignment of elements (left, center, or right)
Use responsive layouts that work across different device sizes
Maintain a minimum contrast ratio of 4.5:1 for text

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{tsx,ts,jsx,js,vue}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue}: Include appropriate loading states for async actions in buttons
Group related form elements with appropriate spacing
Provide clear validation feedback for forms
Ensure proper labeling and accessibility for form elements
Ensure all interactive elements are keyboard accessible
Include appropriate ARIA attributes for complex components
Provide alternative text for images and icons
Support screen readers with semantic HTML elements

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{ts,tsx,js,jsx}

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

**/*.{ts,tsx,js,jsx}: Follow the TypeScript/JavaScript style guidelines
Ensure code is well-tested and documented

Files:

  • packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts
  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/openapi-schema/src/schemas.gen.ts
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • apps/api/src/tracer.ts
  • packages/utils/src/provider.ts
  • apps/api/src/modules/skill/skill-invoker.service.ts
  • packages/utils/src/index.ts
  • apps/api/src/modules/provider/provider.service.ts
  • packages/providers/src/llm/index.ts
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
  • packages/openapi-schema/src/types.gen.ts
  • packages/utils/src/auto-model.ts
  • apps/api/src/modules/skill/skill.service.ts
  • packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{jsx,tsx}: Always use tailwind css to style the component
Always wrap pure components with React.memo to prevent unnecessary re-renders
Always use useMemo for expensive computations or complex object creation
Always use useCallback for function props to maintain referential equality
Always specify proper dependency arrays in useEffect to prevent infinite loops
Always avoid inline object/array creation in render to prevent unnecessary re-renders
Always use proper key props when rendering lists
Always split nested components with closures into separate components to avoid performance issues and improve code maintainability

**/*.{jsx,tsx}: Always wrap pure components with React.memo to prevent unnecessary re-renders
Always use useMemo for expensive computations or complex object creation in React
Always use useCallback for function props to maintain referential equality in React
Always specify proper dependency arrays in useEffect to prevent infinite loops in React
Always avoid inline object/array creation in render to prevent unnecessary re-renders in React
Always use proper key props when rendering lists in React (avoid using index when possible)
Always split nested components with closures into separate components in React
Use lazy loading for components that are not immediately needed in React
Debounce handlers for events that might fire rapidly (resize, scroll, input) in React
Implement fallback UI for components that might fail in React
Use error boundaries to catch and handle runtime errors in React

**/*.{jsx,tsx}: Place each attribute on a new line when a component has multiple attributes in JSX
Use self-closing tags for elements without children in JSX
Keep JSX expressions simple, extract complex logic to variables
Put closing brackets for multi-line JSX on a new line

**/*.{jsx,tsx}: Component file names should match the component name
Organize function components in order: imports, type definitions, constants, component function, hook calls, e...

Files:

  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
**/*.{jsx,tsx,css}

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

**/*.{jsx,tsx,css}: Use Tailwind CSS for styling components
Follow the utility-first approach with Tailwind CSS
Group related utility classes together in Tailwind CSS
Prefer Tailwind utilities over custom CSS when possible

Files:

  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
**/*.{jsx,tsx,js}

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

Each component file should contain only one main component

Files:

  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
**/*.tsx

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

Explicitly type props with interfaces or types in React components

Files:

  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
**/*.{tsx,jsx}

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

Use React best practices for frontend code

Files:

  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
apps/api/src/**/*.{controller,service}.ts

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

Implement proper error handling in API modules

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/skill/skill.service.ts
**/index.{js,ts,jsx,tsx}

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

Use index files to export multiple components from a directory

Files:

  • packages/utils/src/index.ts
  • packages/providers/src/llm/index.ts
**/*.{md,mdx}

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

Update documentation if needed

Files:

  • auto-model.md
🧠 Learnings (12)
📚 Learning: 2025-11-25T03:05:07.580Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/11-ui-design-patterns.mdc:0-0
Timestamp: 2025-11-25T03:05:07.580Z
Learning: Applies to **/*.{tsx,ts,jsx,js,vue} : Provide alternative text for images and icons

Applied to files:

  • packages/ai-workspace-common/src/components/common/icon.tsx
  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:04:05.715Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Applies to **/index.{js,ts,jsx,tsx} : Use index files to export multiple components from a directory

Applied to files:

  • packages/utils/src/index.ts
📚 Learning: 2025-11-25T03:04:41.334Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/09-i18n-guidelines.mdc:0-0
Timestamp: 2025-11-25T03:04:41.334Z
Learning: Applies to **/*.{tsx,ts} : Use the translation wrapper component and useTranslation hook in components

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-26T05:04:26.523Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/08-contributing-guidelines.mdc:0-0
Timestamp: 2025-11-26T05:04:26.523Z
Learning: Applies to **/*.{tsx,jsx} : Use React best practices for frontend code

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:03:31.945Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/01-code-style.mdc:0-0
Timestamp: 2025-11-25T03:03:31.945Z
Learning: Applies to **/*.{jsx,tsx} : Always use useCallback for function props to maintain referential equality in React

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:03:31.945Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/01-code-style.mdc:0-0
Timestamp: 2025-11-25T03:03:31.945Z
Learning: Applies to **/*.{jsx,tsx} : Implement fallback UI for components that might fail in React

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:02:45.779Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursorrules:0-0
Timestamp: 2025-11-25T03:02:45.779Z
Learning: Applies to **/*.{jsx,tsx} : Always use useCallback for function props to maintain referential equality

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:04:51.017Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/10-testing-guidelines.mdc:0-0
Timestamp: 2025-11-25T03:04:51.017Z
Learning: Applies to **/*.{test,spec}.{ts,tsx,js,jsx} : Use React Testing Library utilities for component testing

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:04:05.715Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Applies to **/*.{jsx,tsx} : Use React state hooks for component internal state

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:04:05.715Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Extract repeated JSX patterns into reusable components

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:04:05.715Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Applies to **/*.{js,ts,jsx,tsx} : Extract complex logic into custom hooks

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
📚 Learning: 2025-11-25T03:04:05.715Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Applies to **/*.{jsx,tsx} : Use context for sharing state across multiple components

Applied to files:

  • packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx
🧬 Code graph analysis (4)
packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts (1)
packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts (1)
  • useFetchProviderItems (6-50)
apps/api/src/modules/skill/skill-invoker.service.ts (1)
apps/api/src/utils/credit-billing.ts (1)
  • normalizeCreditBilling (20-52)
apps/api/src/modules/skill/skill.service.ts (1)
packages/errors/src/errors.ts (1)
  • ProviderItemNotFoundError (259-265)
packages/ai-workspace-common/src/hooks/use-fetch-provider-items.ts (1)
packages/utils/src/provider.ts (1)
  • providerItemToModelInfo (135-171)
🪛 markdownlint-cli2 (0.18.1)
auto-model.md

73-73: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


74-74: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


101-101: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


102-102: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


104-104: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


115-115: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


117-117: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


118-118: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


201-201: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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: build / Build
🔇 Additional comments (14)
packages/ai-workspace-common/src/components/common/icon.tsx (1)

84-84: Auto model icon import and render path look good

The Auto SVG import and the ModelIcon branch for models containing 'auto' are consistent with the existing icon patterns, and the <img> element correctly includes alt text for accessibility. Based on learnings, this satisfies the requirement to provide alternative text for icons.

Also applies to: 243-245

packages/utils/src/index.ts (1)

18-18: Exporting ./auto-model via the barrel is appropriate

Re-exporting ./auto-model from the utils index cleanly exposes the new auto-model helpers without altering existing behavior.

packages/ai-workspace-common/src/components/canvas/copilot/copilot-message.tsx (1)

67-70: Canvas copilot now correctly uses defaultAgentModel

Using defaultAgentModel from useFetchProviderItems for generateCanvasDataFromWorkflowPlan aligns the copilot canvas flow with the new agent/auto-model default while preserving the previous chat-model fallback (handled in the hook). The dependency array update to include defaultAgentModel is also correct.

Also applies to: 110-118, 127-140

packages/ai-workspace-common/src/hooks/canvas/use-add-node.ts (1)

55-58: Defaulting node metadata to defaultAgentModel is sound

Injecting defaultAgentModel via useFetchProviderItems and using it as a fallback for node.data.metadata.modelInfo gives newly added nodes a consistent default model without breaking callers that explicitly supply modelInfo. The dependency array correctly includes defaultAgentModel, so updates to user preferences or provider items will be reflected.

Also applies to: 97-100, 180-188

packages/utils/src/provider.ts (1)

135-153: ModelInfo now consistently exposes tooltip metadata

Adding tooltip: config?.tooltip in both the mediaGeneration and LLM branches of providerItemToModelInfo makes tooltip data available to all consumers of ModelInfo without altering existing fields. This aligns with the schema changes and supports the new UI usage in the model selector.

Also applies to: 155-169

packages/openapi-schema/src/schemas.gen.ts (3)

8198-8205: ModelInfoSchema tooltip addition is consistent and non‑breaking

tooltip is added as an optional string with a clear description and no change to the required list, so it is backward compatible and aligns with how other optional metadata fields are modeled.


8318-8324: LLMModelConfigSchema tooltip field matches ModelInfoSchema usage

Adding tooltip here keeps LLM model config metadata in sync with ModelInfoSchema and remains optional, so it should not impact existing clients.


8425-8432: MediaGenerationModelConfigSchema tooltip follows same pattern

The tooltip property is defined identically to the other schemas, preserving consistency across text and media models without introducing breaking changes.

packages/openapi-schema/src/types.gen.ts (1)

5735-5792: Tooltip additions are consistent and backward compatible.

Adding tooltip?: string (with JSDoc) to ModelInfo, LLMModelConfig, and MediaGenerationModelConfig is a clean, additive change that won’t break existing consumers and matches the intended UI behavior for model tooltips. Assuming the OpenAPI schema and generator have been updated accordingly, this looks good.

Also applies to: 5851-5880, 5921-5958

apps/api/src/modules/skill/skill.service.ts (2)

698-707: LGTM!

The helper method correctly validates that the provider item exists, is of category llm, and is enabled before proceeding with routing. The return type correctly reflects the included provider relation.


822-822: LGTM!

The providerItemId field now correctly stores param.modelItemId (the user's selection, e.g., Auto) rather than the routed model's ID. This aligns with the design where:

  • providerItemId = user's selection (for display/replay)
  • modelName = actual model used (for monitoring/billing)

Also applies to: 856-856

apps/api/src/modules/provider/provider.service.ts (3)

881-889: LGTM!

The routing priority list is well-documented with clear model identifiers. The comment explains the fallback order: Claude 4.5 Sonnet → Claude 4 Sonnet.


1043-1056: LGTM!

The integration correctly applies auto-routing after validation and before building the model config map. The let declaration on line 1043 is appropriate since chatItem is reassigned by routeAutoModel.


30-34: LGTM!

The new imports for auto-model utilities (isAutoModel, AUTO_MODEL_ID) and JSON serialization (safeStringifyJSON) are appropriate for the routing implementation.

Comment on lines +1358 to +1379
// If this is an Auto model request, use Auto model's billing rate instead of the actual model's rate
let autoProviderItem: any = null;
try {
const actionResult = await this.prisma.actionResult.findFirst({
where: { resultId, version },
});

if (actionResult?.providerItemId) {
const originalItem = await this.providerService.findProviderItemById(
user,
actionResult.providerItemId,
);

if (originalItem) {
if (isAutoModel(originalItem.config)) {
autoProviderItem = originalItem;
}
}
}
} catch (error) {
this.logger.warn(`[Billing] Failed to check Auto model routing: ${error?.message}`);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if ProviderItem is imported in the file
rg -n "import.*ProviderItem|from.*provider" apps/api/src/modules/skill/skill-invoker.service.ts | head -20

Repository: refly-ai/refly

Length of output: 275


🏁 Script executed:

#!/bin/bash
# Find and inspect syncBatchTokenCreditUsage
rg -n "syncBatchTokenCreditUsage" apps/api/src -A 10 -B 2

Repository: refly-ai/refly

Length of output: 275


🏁 Script executed:

#!/bin/bash
# Check how TokenUsageItem is defined and used
rg -n "TokenUsageItem|interface TokenUsageItem|type TokenUsageItem" apps/api/src -A 5

Repository: refly-ai/refly

Length of output: 275


Use explicit type for autoProviderItem instead of any.

The autoProviderItem variable should be typed as ProviderItem | null rather than any to match TypeScript best practices and your existing imports:

-    let autoProviderItem: any = null;
+    let autoProviderItem: ProviderItem | null = null;

This provides type safety for the later use of billingItem.creditBilling.

Verify that usage fields align with billing intent.

The usage object fields (tier, modelProvider, modelName) are currently sourced from the underlying providerItem, even when billingItem is set to autoProviderItem. Confirm this is intentional—if CreditService.syncBatchTokenCreditUsage expects these fields to align with the billing configuration, you may need to derive them from billingItem when an Auto model is detected, rather than always using the real model's metadata.

🤖 Prompt for AI Agents
In apps/api/src/modules/skill/skill-invoker.service.ts around lines 1358-1379,
change autoProviderItem from type any to the explicit ProviderItem | null type
(use the existing ProviderItem import) so later access to
billingItem.creditBilling is type-safe; additionally, when you detect an Auto
model and set billingItem = autoProviderItem, ensure the usage object fields
(tier, modelProvider, modelName) are derived from billingItem (the auto provider
item) rather than always from the underlying providerItem so
CreditService.syncBatchTokenCreditUsage receives metadata that matches the
billing configuration.

auto-model.md Outdated

模型列表中新增一个 auto 模型,背后可以自动做模型路由。

目前默认路由到 Claude 4.5 Opus (TODO),未来可能根据各种情况(agent 复杂性、任务类型)等进行路由。
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Inconsistency: Documentation says "Claude 4.5 Opus" but code routes to Sonnet.

The documentation states the default routing target is "Claude 4.5 Opus", but provider.service.ts defines AUTO_MODEL_ROUTING_PRIORITY with Claude 4.5 Sonnet and Claude 4 Sonnet. Please update the documentation to match the actual implementation.

🤖 Prompt for AI Agents
In auto-model.md around line 7, the doc states the default route is "Claude 4.5
Opus" but the code (provider.service.ts's AUTO_MODEL_ROUTING_PRIORITY) routes to
"Claude 4.5 Sonnet"; update the documentation to match the implementation by
replacing "Claude 4.5 Opus" with "Claude 4.5 Sonnet" (or alternatively, if you
intend Opus, update AUTO_MODEL_ROUTING_PRIORITY in provider.service.ts to use
Opus consistently) and ensure any other mentions in this file match the chosen
model name.

Comment on lines +9915 to +9917
tooltip:
type: string
description: Tooltip text for the model (e.g., "Smart Routing")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cd packages/openapi-schema && wc -l schema.yml

Repository: refly-ai/refly

Length of output: 74


🏁 Script executed:

cd packages/openapi-schema && sed -n '9910,9920p' schema.yml

Repository: refly-ai/refly

Length of output: 489


🏁 Script executed:

cd packages/openapi-schema && sed -n '10000,10010p' schema.yml

Repository: refly-ai/refly

Length of output: 474


🏁 Script executed:

cd packages/openapi-schema && sed -n '10075,10085p' schema.yml

Repository: refly-ai/refly

Length of output: 479


🏁 Script executed:

find . -name "types.gen.ts" -o -name "schemas.gen.ts" | head -5

Repository: refly-ai/refly

Length of output: 291


🏁 Script executed:

rg -l "tooltip" --type ts --type tsx --type js --type jsx packages/ | head -20

Repository: refly-ai/refly

Length of output: 85


🏁 Script executed:

rg "tooltipDict|tooltip.*locale|i18n.*tooltip" --type ts --type tsx packages/ 2>/dev/null | head -10

Repository: refly-ai/refly

Length of output: 40


🏁 Script executed:

rg "innerHTML.*tooltip|dangerouslySetInnerHTML.*tooltip" --type tsx packages/ 2>/dev/null || echo "No dangerous HTML patterns found"

Repository: refly-ai/refly

Length of output: 90


🏁 Script executed:

rg "tooltip" ./packages/openapi-schema/src/types.gen.ts -A2 -B2 | head -30

Repository: refly-ai/refly

Length of output: 402


🏁 Script executed:

rg "tooltip" ./packages/openapi-schema/src/schemas.gen.ts -A2 -B2 | head -30

Repository: refly-ai/refly

Length of output: 550


🏁 Script executed:

rg -t ts -t js "tooltip" packages/ --glob "*.tsx" --glob "*.jsx" -l | head -10

Repository: refly-ai/refly

Length of output: 819


🏁 Script executed:

find packages -name "*.tsx" -o -name "*.jsx" | xargs rg -l "tooltip" 2>/dev/null | head -10

Repository: refly-ai/refly

Length of output: 812


🏁 Script executed:

rg "ModelInfo.*tooltip|LLMModelConfig.*tooltip|MediaGenerationModelConfig.*tooltip" --type ts -B5 -A5 packages/ 2>/dev/null | head -40

Repository: refly-ai/refly

Length of output: 40


🏁 Script executed:

# Check how similar string fields are handled in UI for i18n patterns
rg "description.*string.*type.*object" packages/openapi-schema/schema.yml -A2 | grep -E "(description|i18n|translate)" | head -20

Repository: refly-ai/refly

Length of output: 40


🏁 Script executed:

# Search for actual tooltip field usage in components
rg "\.tooltip" packages/ --type ts --type js -B3 -A3 | head -50

Repository: refly-ai/refly

Length of output: 4287


🏁 Script executed:

# Look for Tooltip component and how it renders content
rg "Tooltip|tooltip" packages/ai-workspace-common/src/components/ -l | xargs grep -l "tooltip" | head -5

Repository: refly-ai/refly

Length of output: 440


🏁 Script executed:

# Check how similar string fields are wrapped with i18n (t function)
rg "t\(" packages/ --type ts --type js | grep -E "(description|name|label)" | head -10

Repository: refly-ai/refly

Length of output: 1432


🏁 Script executed:

# Check if tooltip is being passed through i18n function
rg "t\(.*tooltip|tooltip.*i18n|i18n.*tooltip" packages/ --type ts --type js

Repository: refly-ai/refly

Length of output: 3573


🏁 Script executed:

# Look at a specific component file to see how tooltip is used
head -100 packages/ai-workspace-common/src/components/workspace/resource-list/index.tsx

Repository: refly-ai/refly

Length of output: 4001


🏁 Script executed:

rg "config.*tooltip|item.*tooltip" packages/ --type ts --type js -B2 -A2 | head -60

Repository: refly-ai/refly

Length of output: 1389


🏁 Script executed:

# Search for where tooltip from model config is used in UI rendering
rg "modelInfo.*tooltip|llmModel.*tooltip" packages/ --type ts --type js -B3 -A3

Repository: refly-ai/refly

Length of output: 40


🏁 Script executed:

# Check model selector or display components
find packages -name "*model*" -name "*.tsx" | xargs grep -l "tooltip" 2>/dev/null | head -5

Repository: refly-ai/refly

Length of output: 150


🏁 Script executed:

# Look for model display/selector components that might use tooltip field
rg "ModelInfo|LLMModelConfig" packages/ai-workspace-common/src/components --type ts --type js -l | head -10

Repository: refly-ai/refly

Length of output: 876


🏁 Script executed:

# Check if tooltip is used in model cards or selection UI
rg "model.*card|ModelCard" packages/ --type ts --type js -l | head -5

Repository: refly-ai/refly

Length of output: 87


🏁 Script executed:

cat -n packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx

Repository: refly-ai/refly

Length of output: 18976


🏁 Script executed:

wc -l packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx

Repository: refly-ai/refly

Length of output: 154


🏁 Script executed:

head -150 packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx

Repository: refly-ai/refly

Length of output: 5031


🏁 Script executed:

# Search for tooltip rendering in model components
rg "tooltip" packages/ai-workspace-common/src/components/canvas/launchpad/ --type ts --type js -B2 -A2

Repository: refly-ai/refly

Length of output: 2691


🏁 Script executed:

# Check model-form to see how tooltip field is used
grep -n "tooltip" packages/ai-workspace-common/src/components/settings/model-config/model-form.tsx -B3 -A3

Repository: refly-ai/refly

Length of output: 40


🏁 Script executed:

# Check if there's any i18n wrapping expected for model tooltip at the source
rg "tooltip" packages/openapi-schema/ --type yaml -B5 -A5 | head -30

Repository: refly-ai/refly

Length of output: 2072


🏁 Script executed:

# Check if other model fields like description have i18n handling
rg "description.*i18n|i18n.*description" packages/ --type ts --type js | head -5

Repository: refly-ai/refly

Length of output: 40


🏁 Script executed:

# Verify the tooltip rendering one more time to be absolutely certain
sed -n '118,145p' packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx

Repository: refly-ai/refly

Length of output: 1109


Apply i18n wrapping to tooltip field; clarify content expectations.

The tooltip field is rendered directly to users in ModelSelector without i18n wrapping (line 133: {model.tooltip}), while other UI strings in the same component use t(). This breaks the i18n-guidelines compliance for user-facing text.

To fix:

  • Wrap tooltip with a translation function (e.g., t(model.tooltip)) if tooltips are meant to be translatable keys, or implement a tooltipDict: { [locale]: string } variant for server-provided translations.
  • If tooltips are always plain text (no HTML/markdown), add a clarifying note in the schema description to prevent rendering surprises.

Generated types correctly include the optional tooltip?: string field; no action needed there.

Comment on lines +10004 to +10006
tooltip:
type: string
description: Tooltip text for the model (e.g., "Smart Routing")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# First, let's understand the file structure and find the relevant config sections
wc -l packages/openapi-schema/schema.yml

Repository: refly-ai/refly

Length of output: 98


🏁 Script executed:

#!/bin/bash
# Search for EmbeddingModelConfig and RerankerModelConfig definitions
rg -n 'EmbeddingModelConfig|RerankerModelConfig' packages/openapi-schema/schema.yml -A 10 -B 2

Repository: refly-ai/refly

Length of output: 1430


🏁 Script executed:

#!/bin/bash
# Also search for where the tooltip was just added to understand the context
rg -n -B 15 'Tooltip text for the model' packages/openapi-schema/schema.yml

Repository: refly-ai/refly

Length of output: 1974


Add tooltip field to Embedding and Reranker model configs for consistency

The tooltip field has been added to LLMModelConfig and MediaGenerationModelConfig but is missing from EmbeddingModelConfig and RerankerModelConfig. For consistency across all model configs, either add the tooltip field to these two configs or create a shared ModelBaseConfig to avoid future drift.

🤖 Prompt for AI Agents
packages/openapi-schema/schema.yml around lines 10004-10006:
EmbeddingModelConfig and RerankerModelConfig are missing the tooltip field that
exists on LLMModelConfig and MediaGenerationModelConfig; add a tooltip property
to both configs with type: string and a matching description like "Tooltip text
for the model (e.g., 'Smart Routing')" so all model configs remain consistent
(alternatively extract a shared ModelBaseConfig and add tooltip there if you
prefer a refactor to prevent future drift).

Copy link

@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: 0

♻️ Duplicate comments (1)
apps/api/src/modules/provider/auto-model-router.service.ts (1)

82-118: Fallback can still pick Auto or reasoning models; align fallback with filtered candidates

The findAvailableModel logic promises to exclude reasoning models, but the fallback currently returns llmItems[0], which:

  • Ignores the earlier filtering (it may select a reasoning model), and
  • Can select an Auto model item whose modelId is AUTO_MODEL_ID, so Auto may “route” back to Auto instead of a real target model.

This undermines the “non‑reasoning only” guarantee and the PR’s goal that Auto resolves to a concrete model. A safer approach is:

  1. Skip Auto items when building modelMap.
  2. Use the filtered modelMap values for the fallback instead of the raw llmItems array.
@@
   private findAvailableModel(): ProviderItemModel {
     const { llmItems } = this.context;
@@
-    for (const item of llmItems) {
-      const config: LLMModelConfig = safeParseJSON(item.config);
+    for (const item of llmItems) {
+      const config: LLMModelConfig = safeParseJSON(item.config);
@@
-      if (!config) {
+      if (!config) {
         continue;
       }
 
-      // Skip reasoning models
-      if (config.capabilities?.reasoning === true) {
+      // Skip Auto model itself as a routing target
+      if (config.modelId === AUTO_MODEL_ID) {
+        continue;
+      }
+
+      // Skip reasoning models
+      if (config.capabilities?.reasoning === true) {
         continue;
       }
@@
-    // Find the first available model from the priority list
+    // Find the first available model from the priority list
     for (const candidateModelId of AUTO_MODEL_ROUTING_PRIORITY) {
       const item = modelMap.get(candidateModelId);
       if (item) {
         return item;
       }
     }
 
-    // Fallback to the first available model
-    if (llmItems.length > 0) {
-      return llmItems[0];
-    }
+    // Fallback to the first available filtered model
+    const filteredItems = Array.from(modelMap.values());
+    if (filteredItems.length > 0) {
+      return filteredItems[0];
+    }
 
     throw new ProviderItemNotFoundError('Auto model routing failed: no model available');
   }

This keeps the fallback consistent with the stated constraints and avoids accidentally re‑selecting Auto or reasoning models.

🧹 Nitpick comments (1)
apps/api/src/modules/provider/provider.service.ts (1)

59-63: AutoModelRouter integration in prepareModelProviderMap looks correct

Switching chatItem to let and routing it through new AutoModelRouter({ llmItems, userId: user.uid }).route(chatItem) after validation is a clean insertion point:

  • Non‑Auto models pass through unchanged.
  • Auto models are resolved once before assembling the modelConfigMap, so downstream consumers (including billing and monitoring) see the routed item.

Error behavior remains consistent, since any ProviderItemNotFoundError from the router will surface similarly to the existing 'chat model not configured' / “not valid” errors. Once the router’s fallback filtering is fixed as suggested in the router file, this wiring should be good to go.

Also applies to: 948-963

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f7689b and 245e5d0.

📒 Files selected for processing (3)
  • apps/api/src/modules/provider/auto-model-router.service.ts (1 hunks)
  • apps/api/src/modules/provider/provider.service.ts (3 hunks)
  • packages/utils/src/auto-model.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/utils/src/auto-model.ts
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{js,ts,jsx,tsx}: Always use optional chaining (?.) when accessing object properties
Always use nullish coalescing (??) or default values for potentially undefined values
Always check array existence before using array methods
Always validate object properties before destructuring
Always use single quotes for string literals in JavaScript/TypeScript code

**/*.{js,ts,jsx,tsx}: Use semicolons at the end of statements
Include spaces around operators (e.g., a + b instead of a+b)
Always use curly braces for control statements
Place opening braces on the same line as their statement

**/*.{js,ts,jsx,tsx}: Group import statements in order: React/framework libraries, third-party libraries, internal modules, relative path imports, type imports, style imports
Sort imports alphabetically within each import group
Leave a blank line between import groups
Extract complex logic into custom hooks
Use functional updates for state (e.g., setCount(prev => prev + 1))
Split complex state into multiple state variables rather than single large objects
Use useReducer for complex state logic instead of multiple useState calls

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}

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

**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}: All code comments MUST be written in English
All variable names, function names, class names, and other identifiers MUST use English words
Comments should be concise and explain 'why' rather than 'what'
Use proper grammar and punctuation in comments
Keep comments up-to-date when code changes
Document complex logic, edge cases, and important implementation details
Use clear, descriptive names that indicate purpose
Avoid abbreviations unless they are universally understood

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{js,ts,tsx,jsx}

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

Use JSDoc style comments for functions and classes in JavaScript/TypeScript

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Use single quotes for string literals in TypeScript/JavaScript
Always use optional chaining (?.) when accessing object properties in TypeScript/JavaScript
Always use nullish coalescing (??) or default values for potentially undefined values in TypeScript/JavaScript
Always check array existence before using array methods in TypeScript/JavaScript
Validate object properties before destructuring in TypeScript/JavaScript
Use ES6+ features like arrow functions, destructuring, and spread operators in TypeScript/JavaScript
Avoid magic numbers and strings - use named constants in TypeScript/JavaScript
Use async/await instead of raw promises for asynchronous code in TypeScript/JavaScript

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Avoid using any type whenever possible - use unknown type instead with proper type guards
Always define explicit return types for functions, especially for public APIs
Prefer extending existing types over creating entirely new types
Use TypeScript utility types (Partial<T>, Pick<T, K>, Omit<T, K>, Readonly<T>, Record<K, T>) to derive new types
Use union types and intersection types to combine existing types
Always import types explicitly using the import type syntax
Group type imports separately from value imports
Minimize creating local type aliases for imported types

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{js,ts,jsx,tsx,css,json}

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

Maximum line length of 100 characters

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml}

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

Use 2 spaces for indentation, no tabs

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}

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

No trailing whitespace at the end of lines

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
apps/api/src/**/*.{controller,service}.ts

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

Implement proper error handling in API modules

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{css,scss,sass,less,js,jsx,ts,tsx}

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

**/*.{css,scss,sass,less,js,jsx,ts,tsx}: Primary color (#155EEF) should be used for main brand color in buttons, links, and accents
Error color (#F04438) should be used for error states and destructive actions
Success color (#12B76A) should be used for success states and confirmations
Warning color (#F79009) should be used for warnings and important notifications
Info color (#0BA5EC) should be used for informational elements

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use the translation wrapper component and useTranslation hook in components
Ensure all user-facing text is translatable

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{tsx,ts,json}

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

Support dynamic content with placeholders in translations

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{tsx,ts,jsx,js,vue,css,scss,less}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue,css,scss,less}: Use the primary blue (#155EEF) for main UI elements, CTAs, and active states
Use red (#F04438) only for errors, warnings, and destructive actions
Use green (#12B76A) for success states and confirmations
Use orange (#F79009) for warning states and important notifications
Use blue (#0BA5EC) for informational elements
Primary buttons should be solid with the primary color
Secondary buttons should have a border with transparent or light background
Danger buttons should use the error color
Use consistent padding, border radius, and hover states for all buttons
Follow fixed button sizes based on their importance and context
Use consistent border radius (rounded-lg) for all cards
Apply light shadows (shadow-sm) for card elevation
Maintain consistent padding inside cards (p-4 or p-6)
Use subtle borders for card separation
Ensure proper spacing between card elements
Apply consistent styling to all form inputs
Use clear visual indicators for focus, hover, and error states in form elements
Apply proper spacing between elements using 8px, 16px, 24px increments
Ensure proper alignment of elements (left, center, or right)
Use responsive layouts that work across different device sizes
Maintain a minimum contrast ratio of 4.5:1 for text

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{tsx,ts,jsx,js,vue}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue}: Include appropriate loading states for async actions in buttons
Group related form elements with appropriate spacing
Provide clear validation feedback for forms
Ensure proper labeling and accessibility for form elements
Ensure all interactive elements are keyboard accessible
Include appropriate ARIA attributes for complex components
Provide alternative text for images and icons
Support screen readers with semantic HTML elements

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
**/*.{ts,tsx,js,jsx}

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

**/*.{ts,tsx,js,jsx}: Follow the TypeScript/JavaScript style guidelines
Ensure code is well-tested and documented

Files:

  • apps/api/src/modules/provider/provider.service.ts
  • apps/api/src/modules/provider/auto-model-router.service.ts
🧬 Code graph analysis (2)
apps/api/src/modules/provider/provider.service.ts (1)
apps/api/src/modules/provider/auto-model-router.service.ts (1)
  • AutoModelRouter (34-119)
apps/api/src/modules/provider/auto-model-router.service.ts (3)
packages/skill-template/src/engine/index.ts (1)
  • Logger (36-36)
packages/utils/src/auto-model.ts (3)
  • isAutoModel (26-35)
  • AUTO_MODEL_ID (8-8)
  • AUTO_MODEL_ROUTING_PRIORITY (14-19)
packages/errors/src/errors.ts (1)
  • ProviderItemNotFoundError (259-265)
⏰ 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: build / Build
🔇 Additional comments (2)
apps/api/src/modules/provider/auto-model-router.service.ts (2)

17-38: RouterContext and AutoModelRouter structure look solid

Clear separation of routing context (pre‑fetched llmItems + userId) and a focused AutoModelRouter class keeps responsibilities tidy and makes the router easy to test and reuse. No issues here.


48-71: Routing behavior and metadata injection are well‑structured

Early return for non‑Auto configs, single findAvailableModel() call, logging with userId, and attaching routeData into the routed config via safeParseJSON/safeStringifyJSON are all appropriate and match the intended monitoring semantics.

Copy link

@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: 0

🧹 Nitpick comments (1)
apps/api/src/modules/skill/skill.service.ts (1)

780-856: Persisting providerItemId as param.modelItemId—confirm downstream expectations

Using providerItemId: param.modelItemId in both the re-run and initial actionResult.create paths keeps persisted results tied to the logical/virtual model choice (e.g., Auto) while tier/modelName come from the routed providerItem. This looks intentional and coherent with the routing changes.

If any downstream consumers currently rely on ActionResult.providerItemId being the concrete routed item ID (for analytics, debugging, or replay fidelity), they will now see the virtual ID instead. If that becomes an issue, consider optionally persisting the routed item ID separately (e.g., in metadata) rather than overloading providerItemId.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 245e5d0 and 5283bd6.

📒 Files selected for processing (1)
  • apps/api/src/modules/skill/skill.service.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{js,ts,jsx,tsx}: Always use optional chaining (?.) when accessing object properties
Always use nullish coalescing (??) or default values for potentially undefined values
Always check array existence before using array methods
Always validate object properties before destructuring
Always use single quotes for string literals in JavaScript/TypeScript code

**/*.{js,ts,jsx,tsx}: Use semicolons at the end of statements
Include spaces around operators (e.g., a + b instead of a+b)
Always use curly braces for control statements
Place opening braces on the same line as their statement

**/*.{js,ts,jsx,tsx}: Group import statements in order: React/framework libraries, third-party libraries, internal modules, relative path imports, type imports, style imports
Sort imports alphabetically within each import group
Leave a blank line between import groups
Extract complex logic into custom hooks
Use functional updates for state (e.g., setCount(prev => prev + 1))
Split complex state into multiple state variables rather than single large objects
Use useReducer for complex state logic instead of multiple useState calls

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}

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

**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}: All code comments MUST be written in English
All variable names, function names, class names, and other identifiers MUST use English words
Comments should be concise and explain 'why' rather than 'what'
Use proper grammar and punctuation in comments
Keep comments up-to-date when code changes
Document complex logic, edge cases, and important implementation details
Use clear, descriptive names that indicate purpose
Avoid abbreviations unless they are universally understood

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{js,ts,tsx,jsx}

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

Use JSDoc style comments for functions and classes in JavaScript/TypeScript

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Use single quotes for string literals in TypeScript/JavaScript
Always use optional chaining (?.) when accessing object properties in TypeScript/JavaScript
Always use nullish coalescing (??) or default values for potentially undefined values in TypeScript/JavaScript
Always check array existence before using array methods in TypeScript/JavaScript
Validate object properties before destructuring in TypeScript/JavaScript
Use ES6+ features like arrow functions, destructuring, and spread operators in TypeScript/JavaScript
Avoid magic numbers and strings - use named constants in TypeScript/JavaScript
Use async/await instead of raw promises for asynchronous code in TypeScript/JavaScript

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Avoid using any type whenever possible - use unknown type instead with proper type guards
Always define explicit return types for functions, especially for public APIs
Prefer extending existing types over creating entirely new types
Use TypeScript utility types (Partial<T>, Pick<T, K>, Omit<T, K>, Readonly<T>, Record<K, T>) to derive new types
Use union types and intersection types to combine existing types
Always import types explicitly using the import type syntax
Group type imports separately from value imports
Minimize creating local type aliases for imported types

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{js,ts,jsx,tsx,css,json}

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

Maximum line length of 100 characters

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml}

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

Use 2 spaces for indentation, no tabs

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}

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

No trailing whitespace at the end of lines

Files:

  • apps/api/src/modules/skill/skill.service.ts
apps/api/src/**/*.{controller,service}.ts

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

Implement proper error handling in API modules

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{css,scss,sass,less,js,jsx,ts,tsx}

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

**/*.{css,scss,sass,less,js,jsx,ts,tsx}: Primary color (#155EEF) should be used for main brand color in buttons, links, and accents
Error color (#F04438) should be used for error states and destructive actions
Success color (#12B76A) should be used for success states and confirmations
Warning color (#F79009) should be used for warnings and important notifications
Info color (#0BA5EC) should be used for informational elements

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use the translation wrapper component and useTranslation hook in components
Ensure all user-facing text is translatable

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{tsx,ts,json}

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

Support dynamic content with placeholders in translations

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{tsx,ts,jsx,js,vue,css,scss,less}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue,css,scss,less}: Use the primary blue (#155EEF) for main UI elements, CTAs, and active states
Use red (#F04438) only for errors, warnings, and destructive actions
Use green (#12B76A) for success states and confirmations
Use orange (#F79009) for warning states and important notifications
Use blue (#0BA5EC) for informational elements
Primary buttons should be solid with the primary color
Secondary buttons should have a border with transparent or light background
Danger buttons should use the error color
Use consistent padding, border radius, and hover states for all buttons
Follow fixed button sizes based on their importance and context
Use consistent border radius (rounded-lg) for all cards
Apply light shadows (shadow-sm) for card elevation
Maintain consistent padding inside cards (p-4 or p-6)
Use subtle borders for card separation
Ensure proper spacing between card elements
Apply consistent styling to all form inputs
Use clear visual indicators for focus, hover, and error states in form elements
Apply proper spacing between elements using 8px, 16px, 24px increments
Ensure proper alignment of elements (left, center, or right)
Use responsive layouts that work across different device sizes
Maintain a minimum contrast ratio of 4.5:1 for text

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{tsx,ts,jsx,js,vue}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue}: Include appropriate loading states for async actions in buttons
Group related form elements with appropriate spacing
Provide clear validation feedback for forms
Ensure proper labeling and accessibility for form elements
Ensure all interactive elements are keyboard accessible
Include appropriate ARIA attributes for complex components
Provide alternative text for images and icons
Support screen readers with semantic HTML elements

Files:

  • apps/api/src/modules/skill/skill.service.ts
**/*.{ts,tsx,js,jsx}

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

**/*.{ts,tsx,js,jsx}: Follow the TypeScript/JavaScript style guidelines
Ensure code is well-tested and documented

Files:

  • apps/api/src/modules/skill/skill.service.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). (1)
  • GitHub Check: build / Build
🔇 Additional comments (2)
apps/api/src/modules/skill/skill.service.ts (2)

6-11: ProviderModel import for routed provider typing looks good

Importing Provider as ProviderModel from Prisma cleanly supports the enriched providerItem intersection type used later, without introducing new behavior or style issues.


487-502: Original provider validation and routed provider selection are consistent with Auto-model routing

The added originalProviderItem check (presence, llm category, enabled) before routing, and then deriving the execution providerItem from prepareModelProviderMap (with the comment clarifying logical vs routed IDs), looks correct and aligns with the intended Auto-model behavior. It avoids redundant lookups and clearly separates validation (original item) from execution/billing (routed item).

Copy link

@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: 0

♻️ Duplicate comments (3)
apps/api/src/modules/skill/skill-invoker.service.ts (1)

1358-1379: Use explicit type ProviderItem | null instead of any.

The autoProviderItem variable should be typed explicitly for type safety:

-    let autoProviderItem: any = null;
+    let autoProviderItem: ProviderItem | null = null;

ProviderItem is already imported at line 17 from @refly/openapi-schema. Based on coding guidelines, avoid using any type whenever possible.

auto-model.md (2)

7-7: Internal documentation inconsistency about routing target.

Line 7 states the default route is "Claude 4.5 Opus", but line 89 mentions "Sonnet 4.5":

  • Line 7: "目前默认路由到 Claude 4.5 Opus"
  • Line 89: "此次是直接路由到 Sonnet 4.5"

Please update for consistency. Based on the past review comment mentioning AUTO_MODEL_ROUTING_PRIORITY in provider.service.ts uses Sonnet, line 7 should likely be corrected to "Claude 4.5 Sonnet".


35-66: Hardcoded pk values may cause conflicts.

The SQL seed uses hardcoded pk values (40 for provider, 118 for provider_item). This can cause primary key conflicts if these IDs already exist in a database.

Consider:

  1. Omitting pk from inserts to use auto-increment
  2. Using upsert semantics: ON CONFLICT (provider_id) DO NOTHING
  3. Documenting the expected database state before running these seeds
🧹 Nitpick comments (1)
auto-model.md (1)

205-223: Add language specifier to fenced code block.

The diagram code block at line 205 lacks a language specification. For better rendering and linting compliance, add a language identifier:

-```
+```text
 用户选择 Auto
   ↓
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 345e3ff and d8ba04c.

📒 Files selected for processing (3)
  • apps/api/src/modules/skill/skill-invoker.service.ts (3 hunks)
  • auto-model.md (1 hunks)
  • packages/utils/src/auto-model.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/utils/src/auto-model.ts
🧰 Additional context used
📓 Path-based instructions (16)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{js,ts,jsx,tsx}: Always use optional chaining (?.) when accessing object properties
Always use nullish coalescing (??) or default values for potentially undefined values
Always check array existence before using array methods
Always validate object properties before destructuring
Always use single quotes for string literals in JavaScript/TypeScript code

**/*.{js,ts,jsx,tsx}: Use semicolons at the end of statements
Include spaces around operators (e.g., a + b instead of a+b)
Always use curly braces for control statements
Place opening braces on the same line as their statement

**/*.{js,ts,jsx,tsx}: Group import statements in order: React/framework libraries, third-party libraries, internal modules, relative path imports, type imports, style imports
Sort imports alphabetically within each import group
Leave a blank line between import groups
Extract complex logic into custom hooks
Use functional updates for state (e.g., setCount(prev => prev + 1))
Split complex state into multiple state variables rather than single large objects
Use useReducer for complex state logic instead of multiple useState calls

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}

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

**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}: All code comments MUST be written in English
All variable names, function names, class names, and other identifiers MUST use English words
Comments should be concise and explain 'why' rather than 'what'
Use proper grammar and punctuation in comments
Keep comments up-to-date when code changes
Document complex logic, edge cases, and important implementation details
Use clear, descriptive names that indicate purpose
Avoid abbreviations unless they are universally understood

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{js,ts,tsx,jsx}

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

Use JSDoc style comments for functions and classes in JavaScript/TypeScript

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Use single quotes for string literals in TypeScript/JavaScript
Always use optional chaining (?.) when accessing object properties in TypeScript/JavaScript
Always use nullish coalescing (??) or default values for potentially undefined values in TypeScript/JavaScript
Always check array existence before using array methods in TypeScript/JavaScript
Validate object properties before destructuring in TypeScript/JavaScript
Use ES6+ features like arrow functions, destructuring, and spread operators in TypeScript/JavaScript
Avoid magic numbers and strings - use named constants in TypeScript/JavaScript
Use async/await instead of raw promises for asynchronous code in TypeScript/JavaScript

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Avoid using any type whenever possible - use unknown type instead with proper type guards
Always define explicit return types for functions, especially for public APIs
Prefer extending existing types over creating entirely new types
Use TypeScript utility types (Partial<T>, Pick<T, K>, Omit<T, K>, Readonly<T>, Record<K, T>) to derive new types
Use union types and intersection types to combine existing types
Always import types explicitly using the import type syntax
Group type imports separately from value imports
Minimize creating local type aliases for imported types

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{js,ts,jsx,tsx,css,json}

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

Maximum line length of 100 characters

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml}

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

Use 2 spaces for indentation, no tabs

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}

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

No trailing whitespace at the end of lines

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
  • auto-model.md
apps/api/src/**/*.{controller,service}.ts

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

Implement proper error handling in API modules

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{css,scss,sass,less,js,jsx,ts,tsx}

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

**/*.{css,scss,sass,less,js,jsx,ts,tsx}: Primary color (#155EEF) should be used for main brand color in buttons, links, and accents
Error color (#F04438) should be used for error states and destructive actions
Success color (#12B76A) should be used for success states and confirmations
Warning color (#F79009) should be used for warnings and important notifications
Info color (#0BA5EC) should be used for informational elements

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use the translation wrapper component and useTranslation hook in components
Ensure all user-facing text is translatable

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{tsx,ts,json}

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

Support dynamic content with placeholders in translations

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{tsx,ts,jsx,js,vue,css,scss,less}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue,css,scss,less}: Use the primary blue (#155EEF) for main UI elements, CTAs, and active states
Use red (#F04438) only for errors, warnings, and destructive actions
Use green (#12B76A) for success states and confirmations
Use orange (#F79009) for warning states and important notifications
Use blue (#0BA5EC) for informational elements
Primary buttons should be solid with the primary color
Secondary buttons should have a border with transparent or light background
Danger buttons should use the error color
Use consistent padding, border radius, and hover states for all buttons
Follow fixed button sizes based on their importance and context
Use consistent border radius (rounded-lg) for all cards
Apply light shadows (shadow-sm) for card elevation
Maintain consistent padding inside cards (p-4 or p-6)
Use subtle borders for card separation
Ensure proper spacing between card elements
Apply consistent styling to all form inputs
Use clear visual indicators for focus, hover, and error states in form elements
Apply proper spacing between elements using 8px, 16px, 24px increments
Ensure proper alignment of elements (left, center, or right)
Use responsive layouts that work across different device sizes
Maintain a minimum contrast ratio of 4.5:1 for text

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{tsx,ts,jsx,js,vue}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue}: Include appropriate loading states for async actions in buttons
Group related form elements with appropriate spacing
Provide clear validation feedback for forms
Ensure proper labeling and accessibility for form elements
Ensure all interactive elements are keyboard accessible
Include appropriate ARIA attributes for complex components
Provide alternative text for images and icons
Support screen readers with semantic HTML elements

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{ts,tsx,js,jsx}

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

**/*.{ts,tsx,js,jsx}: Follow the TypeScript/JavaScript style guidelines
Ensure code is well-tested and documented

Files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
**/*.{md,mdx}

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

Update documentation if needed

Files:

  • auto-model.md
🧠 Learnings (1)
📚 Learning: 2025-11-25T03:03:43.116Z
Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/03-typescript-guidelines.mdc:0-0
Timestamp: 2025-11-25T03:03:43.116Z
Learning: Applies to **/*.{ts,tsx} : Avoid using `any` type whenever possible - use `unknown` type instead with proper type guards

Applied to files:

  • apps/api/src/modules/skill/skill-invoker.service.ts
🧬 Code graph analysis (1)
apps/api/src/modules/skill/skill-invoker.service.ts (2)
packages/utils/src/auto-model.ts (1)
  • isAutoModel (27-36)
apps/api/src/utils/credit-billing.ts (1)
  • normalizeCreditBilling (20-52)
🪛 markdownlint-cli2 (0.18.1)
auto-model.md

78-78: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


79-79: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


105-105: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


106-106: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


108-108: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


119-119: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


121-121: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


122-122: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


205-205: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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: build / Build
🔇 Additional comments (2)
apps/api/src/modules/skill/skill-invoker.service.ts (2)

31-31: LGTM!

The import of isAutoModel from @refly/utils is correctly added to support the Auto model routing detection in billing logic.


1427-1444: LGTM!

The billing logic correctly implements the intended design:

  • Billing rate: Derived from billingItem (Auto model's rate when applicable)
  • Usage metadata: Derived from providerItem (actual executing model for tracking)

This matches the documented approach: "Token 计算(真实模型)+ 费率计算(Auto 模型)= 最终费用" (token count from real model + billing rate from Auto model).

Copy link

@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

♻️ Duplicate comments (1)
auto-model.md (1)

7-7: Inconsistency: Documentation still says "Claude 4.5 Opus" but should be "Claude 4.5 Sonnet".

This was flagged in a previous review but remains unresolved. The documentation states the default routing target is "Claude 4.5 Opus", but the implementation (referenced in the prior review) routes to Claude 4.5 Sonnet. Please update this line to match the actual implementation.

- 目前默认路由到 Claude 4.5 Opus,未来可能根据各种情况(agent 复杂性、任务类型)等进行路由。
+ 目前默认路由到 Claude 4.5 Sonnet,未来可能根据各种情况(agent 复杂性、任务类型)等进行路由。
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8ba04c and c11eec7.

📒 Files selected for processing (1)
  • auto-model.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}

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

No trailing whitespace at the end of lines

Files:

  • auto-model.md
**/*.{md,mdx}

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

Update documentation if needed

Files:

  • auto-model.md
🪛 markdownlint-cli2 (0.18.1)
auto-model.md

95-95: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


96-96: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


122-122: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


123-123: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


125-125: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


136-136: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


138-138: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


139-139: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


222-222: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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: build / Build
🔇 Additional comments (2)
auto-model.md (2)

35-45: Verify necessity of sequence reset SQL statements.

The SQL seed includes SELECT setval(...) statements to reset sequences. While this prevents potential pk conflicts, clarify whether this is necessary for your deployment workflow and whether all developers/operators understand this prerequisite. If this is a one-time bootstrap, consider documenting when and why these resets are needed.


1-256: Comprehensive documentation is well-structured and detailed.

The document provides a thorough explanation of the Auto model routing feature, including requirements, implementation strategy, routing logic, display layer changes, and billing. The comparison of two routing approaches (decision-layer vs. execution-layer) and the final recommendation is particularly clear. Schema and data flow diagrams add valuable context.

Please verify that:

  1. All references to model names (especially Opus vs. Sonnet) align with the actual backend implementation.
  2. The SQL seed section reflects the current database schema and migration approach.
  3. Any front-end or back-end code changes mentioned in the design (e.g., modifications to ProviderService.prepareModelProviderMap, getChatModel, and ActionResult handling) have been implemented and tested.

auto-model.md Outdated
Comment on lines 95 to 96
- 无法上传图片:前端通过检查 config.capabilities.vision 来决定是否显示上传图片按钮。如果 config 里没存,默认为 false,Auto 模型就无法发图了(虽然背后的 Sonnet 4.5 支持)。
- Context 长度误报:前端会读取 config.contextLimit 做上下文长度检查。如果没存,默认为 0,可能会导致前端提示“Token 超限”或显示“Limit: 0”。
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Fix markdown list indentation per MD007 rule.

Unordered list items must use 2-space indentation, but several nested lists use 4 spaces. Update the following lines:

  • Lines 95-96 (within the "TODO 待确认的问题" section)
  • Lines 122-123, 125 (within "方案一" advantages/disadvantages)
  • Lines 136, 138-139 (within "方案二" advantages/disadvantages)

Apply this diff to standardize list indentation to 2 spaces:

  - provider_items 的 config 字段可能带来的兼容性问题
-     - 无法上传图片:...
-     - Context 长度误报:...
+  - 无法上传图片:...
+  - Context 长度误报:...

(Apply similar corrections to the nested lists in lines 122–125 and 136–139.)

Also applies to: 122-123, 125-125, 136-136, 138-139

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

95-95: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


96-96: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

🤖 Prompt for AI Agents
In auto-model.md around lines 95-96 (and similarly at 122-123, 125, 136,
138-139), several unordered list items are indented with 4 spaces violating
MD007; change those nested list item indentations to 2 spaces so all nested
bullets use exactly 2-space indentation, ensuring consistent markdown list
structure across the "TODO 待确认的问题", "方案一" and "方案二" sections.

auto-model.md Outdated
Comment on lines 222 to 240
```
用户选择 Auto
param.modelItemId = Auto itemId
prepareModelProviderMap(param.modelItemId)
内部路由,返回真实模型
param.modelItemId 保持不变 ← 关键!
providerItem = Claude Sonnet 4.5 (执行用)
param.modelItemId = Auto itemId (展示用)
创建 ActionResult:
- providerItemId = param.modelItemId (Auto itemId)
- modelName = providerItem.config.modelId (真实模型)
前端读取 providerItemId → 显示 Auto ✓
Langfuse 读取 modelName + routeData → 追踪真实模型 + Auto 标签 ✓
```
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Specify language for fenced code block per MD040 rule.

The data flow diagram at line 222 is in a fenced code block without a language identifier. While the content is ASCII text, specify a language or use a plain text block for clarity.

- ```
+ ```text
  用户选择 Auto
    ↓
  param.modelItemId = Auto itemId
  ...
- ```
+ ```
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

222-222: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
In auto-model.md around lines 222 to 240, the fenced code block containing the
ASCII data flow diagram lacks a language identifier (MD040); update the opening
fence to include a language tag such as "text" (i.e. change ``` to ```text) so
the block is explicitly marked as plain text, leaving the content and closing
fence unchanged.

Copy link

@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: 0

♻️ Duplicate comments (3)
auto-model.md (3)

94-97: Fix nested list indentation to satisfy MD007.

Several nested list items are indented with 4 spaces instead of 2 (markdownlint MD007), e.g.:

  • Lines 95–96 under “TODO 待确认的问题”
  • Lines 132–133, 135 and 146, 148–149 under the 方案一 / 方案二 sections

Adjust these child bullets to use 2-space indentation. For example:

-    - 无法上传图片:...
-    - Context 长度误报:...
+  - 无法上传图片:...
+  - Context 长度误报:...

(and apply the same pattern to the other affected nested lists).

Also applies to: 132-136, 146-149


232-250: Specify a language for the data-flow fenced block as well (MD040).

The ASCII data-flow diagram is in a fenced block without a language. To satisfy MD040 and clarify intent, tag it as plain text:

-```
+```text
 用户选择 Auto
   ↓
 ...
-```
+```

7-8: Align documented default route target with actual implementation (Opus vs Sonnet).

The doc states the Auto model “目前默认路由到 Claude 4.5 Opus”, but the routing code (e.g., AUTO_MODEL_ROUTING_PRIORITY in provider.service.ts) uses Claude Sonnet variants. Please update either the documentation or the routing constant so they describe the same default target, and ensure all mentions in this file are consistent.

Also applies to: 112-118

🧹 Nitpick comments (2)
apps/api/src/modules/canvas/canvas.service.ts (1)

51-51: Default model injection is sound; consider tightening the typing instead of as any.

Fetching the default agent item, converting via providerItem2ModelInfo, and passing defaultModelInfo into initEmptyCanvasState is logically correct and preserves behavior when no default exists (falls back to no model). The only rough edge is the cast:

const defaultModelInfo = defaultAgentItem
  ? providerItem2ModelInfo(defaultAgentItem as any)
  : undefined;

If feasible, it would be cleaner to align findDefaultProviderItem’s return type with providerItem2ModelInfo’s input (e.g., by including the optional provider relation in the query) and drop the as any cast.

Also applies to: 594-601

auto-model.md (1)

102-104: Add a language identifier to the env-var fenced code block (MD040).

The DEFAULT_MODEL_AGENT=auto example uses a bare code fence; markdownlint (MD040) expects a language. Consider:

-```
+```bash
 DEFAULT_MODEL_AGENT=auto

(or another appropriate language tag).

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used**: CodeRabbit UI

**Review profile**: CHILL

**Plan**: Pro

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between c11eec799502e68280c82de6b9f0ca6324d4f49b and 6eed128cf5bbb88a927f98dacfdbd69f57acaaef.

</details>

<details>
<summary>📒 Files selected for processing (5)</summary>

* `apps/api/src/modules/canvas/canvas.service.ts` (2 hunks)
* `auto-model.md` (1 hunks)
* `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx` (7 hunks)
* `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx` (1 hunks)
* `packages/canvas-common/src/sync.ts` (3 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>📓 Path-based instructions (21)</summary>

<details>
<summary>**/*.{js,ts,jsx,tsx}</summary>


**📄 CodeRabbit inference engine (.cursorrules)**

> `**/*.{js,ts,jsx,tsx}`: Always use optional chaining (?.) when accessing object properties
> Always use nullish coalescing (??) or default values for potentially undefined values
> Always check array existence before using array methods
> Always validate object properties before destructuring
> Always use single quotes for string literals in JavaScript/TypeScript code
> 
> `**/*.{js,ts,jsx,tsx}`: Use semicolons at the end of statements
> Include spaces around operators (e.g., `a + b` instead of `a+b`)
> Always use curly braces for control statements
> Place opening braces on the same line as their statement
> 
> `**/*.{js,ts,jsx,tsx}`: Group import statements in order: React/framework libraries, third-party libraries, internal modules, relative path imports, type imports, style imports
> Sort imports alphabetically within each import group
> Leave a blank line between import groups
> Extract complex logic into custom hooks
> Use functional updates for state (e.g., `setCount(prev => prev + 1)`)
> Split complex state into multiple state variables rather than single large objects
> Use useReducer for complex state logic instead of multiple useState calls

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/00-language-priority.mdc)**

> `**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}`: All code comments MUST be written in English
> All variable names, function names, class names, and other identifiers MUST use English words
> Comments should be concise and explain 'why' rather than 'what'
> Use proper grammar and punctuation in comments
> Keep comments up-to-date when code changes
> Document complex logic, edge cases, and important implementation details
> Use clear, descriptive names that indicate purpose
> Avoid abbreviations unless they are universally understood

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{js,ts,tsx,jsx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/00-language-priority.mdc)**

> Use JSDoc style comments for functions and classes in JavaScript/TypeScript

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{js,jsx,ts,tsx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/01-code-style.mdc)**

> `**/*.{js,jsx,ts,tsx}`: Use single quotes for string literals in TypeScript/JavaScript
> Always use optional chaining (`?.`) when accessing object properties in TypeScript/JavaScript
> Always use nullish coalescing (`??`) or default values for potentially undefined values in TypeScript/JavaScript
> Always check array existence before using array methods in TypeScript/JavaScript
> Validate object properties before destructuring in TypeScript/JavaScript
> Use ES6+ features like arrow functions, destructuring, and spread operators in TypeScript/JavaScript
> Avoid magic numbers and strings - use named constants in TypeScript/JavaScript
> Use async/await instead of raw promises for asynchronous code in TypeScript/JavaScript

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{ts,tsx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/03-typescript-guidelines.mdc)**

> `**/*.{ts,tsx}`: Avoid using `any` type whenever possible - use `unknown` type instead with proper type guards
> Always define explicit return types for functions, especially for public APIs
> Prefer extending existing types over creating entirely new types
> Use TypeScript utility types (`Partial<T>`, `Pick<T, K>`, `Omit<T, K>`, `Readonly<T>`, `Record<K, T>`) to derive new types
> Use union types and intersection types to combine existing types
> Always import types explicitly using the `import type` syntax
> Group type imports separately from value imports
> Minimize creating local type aliases for imported types

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{js,ts,jsx,tsx,css,json}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/04-code-formatting.mdc)**

> Maximum line length of 100 characters

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{js,ts,jsx,tsx,css,json,yml,yaml}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/04-code-formatting.mdc)**

> Use 2 spaces for indentation, no tabs

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/04-code-formatting.mdc)**

> No trailing whitespace at the end of lines

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `auto-model.md`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{css,scss,sass,less,js,jsx,ts,tsx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/09-design-system.mdc)**

> `**/*.{css,scss,sass,less,js,jsx,ts,tsx}`: Primary color (#155EEF) should be used for main brand color in buttons, links, and accents
> Error color (#F04438) should be used for error states and destructive actions
> Success color (#12B76A) should be used for success states and confirmations
> Warning color (#F79009) should be used for warnings and important notifications
> Info color (#0BA5EC) should be used for informational elements

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{tsx,ts}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/09-i18n-guidelines.mdc)**

> `**/*.{tsx,ts}`: Use the translation wrapper component and useTranslation hook in components
> Ensure all user-facing text is translatable

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{tsx,ts,json}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/09-i18n-guidelines.mdc)**

> Support dynamic content with placeholders in translations

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{tsx,ts,jsx,js,vue,css,scss,less}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)**

> `**/*.{tsx,ts,jsx,js,vue,css,scss,less}`: Use the primary blue (#155EEF) for main UI elements, CTAs, and active states
> Use red (#F04438) only for errors, warnings, and destructive actions
> Use green (#12B76A) for success states and confirmations
> Use orange (#F79009) for warning states and important notifications
> Use blue (#0BA5EC) for informational elements
> Primary buttons should be solid with the primary color
> Secondary buttons should have a border with transparent or light background
> Danger buttons should use the error color
> Use consistent padding, border radius, and hover states for all buttons
> Follow fixed button sizes based on their importance and context
> Use consistent border radius (`rounded-lg`) for all cards
> Apply light shadows (`shadow-sm`) for card elevation
> Maintain consistent padding inside cards (`p-4` or `p-6`)
> Use subtle borders for card separation
> Ensure proper spacing between card elements
> Apply consistent styling to all form inputs
> Use clear visual indicators for focus, hover, and error states in form elements
> Apply proper spacing between elements using 8px, 16px, 24px increments
> Ensure proper alignment of elements (left, center, or right)
> Use responsive layouts that work across different device sizes
> Maintain a minimum contrast ratio of 4.5:1 for text

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{tsx,ts,jsx,js,vue}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)**

> `**/*.{tsx,ts,jsx,js,vue}`: Include appropriate loading states for async actions in buttons
> Group related form elements with appropriate spacing
> Provide clear validation feedback for forms
> Ensure proper labeling and accessibility for form elements
> Ensure all interactive elements are keyboard accessible
> Include appropriate ARIA attributes for complex components
> Provide alternative text for images and icons
> Support screen readers with semantic HTML elements

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{ts,tsx,js,jsx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/08-contributing-guidelines.mdc)**

> `**/*.{ts,tsx,js,jsx}`: Follow the TypeScript/JavaScript style guidelines
> Ensure code is well-tested and documented

Files:
- `packages/canvas-common/src/sync.ts`
- `apps/api/src/modules/canvas/canvas.service.ts`
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>apps/api/src/**/*.{controller,service}.ts</summary>


**📄 CodeRabbit inference engine (.cursor/rules/06-api-structure.mdc)**

> Implement proper error handling in API modules

Files:
- `apps/api/src/modules/canvas/canvas.service.ts`

</details>
<details>
<summary>**/*.{md,mdx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/08-contributing-guidelines.mdc)**

> Update documentation if needed

Files:
- `auto-model.md`

</details>
<details>
<summary>**/*.{jsx,tsx}</summary>


**📄 CodeRabbit inference engine (.cursorrules)**

> `**/*.{jsx,tsx}`: Always use tailwind css to style the component
> Always wrap pure components with React.memo to prevent unnecessary re-renders
> Always use useMemo for expensive computations or complex object creation
> Always use useCallback for function props to maintain referential equality
> Always specify proper dependency arrays in useEffect to prevent infinite loops
> Always avoid inline object/array creation in render to prevent unnecessary re-renders
> Always use proper key props when rendering lists
> Always split nested components with closures into separate components to avoid performance issues and improve code maintainability
> 
> `**/*.{jsx,tsx}`: Always wrap pure components with React.memo to prevent unnecessary re-renders
> Always use useMemo for expensive computations or complex object creation in React
> Always use useCallback for function props to maintain referential equality in React
> Always specify proper dependency arrays in useEffect to prevent infinite loops in React
> Always avoid inline object/array creation in render to prevent unnecessary re-renders in React
> Always use proper key props when rendering lists in React (avoid using index when possible)
> Always split nested components with closures into separate components in React
> Use lazy loading for components that are not immediately needed in React
> Debounce handlers for events that might fire rapidly (resize, scroll, input) in React
> Implement fallback UI for components that might fail in React
> Use error boundaries to catch and handle runtime errors in React
> 
> `**/*.{jsx,tsx}`: Place each attribute on a new line when a component has multiple attributes in JSX
> Use self-closing tags for elements without children in JSX
> Keep JSX expressions simple, extract complex logic to variables
> Put closing brackets for multi-line JSX on a new line
> 
> `**/*.{jsx,tsx}`: Component file names should match the component name
> Organize function components in order: imports, type definitions, constants, component function, hook calls, e...

Files:
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{jsx,tsx,css}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/01-code-style.mdc)**

> `**/*.{jsx,tsx,css}`: Use Tailwind CSS for styling components
> Follow the utility-first approach with Tailwind CSS
> Group related utility classes together in Tailwind CSS
> Prefer Tailwind utilities over custom CSS when possible

Files:
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{jsx,tsx,js}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/05-code-organization.mdc)**

> Each component file should contain only one main component

Files:
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.tsx</summary>


**📄 CodeRabbit inference engine (.cursor/rules/05-code-organization.mdc)**

> Explicitly type props with interfaces or types in React components

Files:
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>
<details>
<summary>**/*.{tsx,jsx}</summary>


**📄 CodeRabbit inference engine (.cursor/rules/08-contributing-guidelines.mdc)**

> Use React best practices for frontend code

Files:
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`
- `packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx`

</details>

</details><details>
<summary>🧠 Learnings (12)</summary>

<details>
<summary>📚 Learning: 2025-11-25T03:03:49.987Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/04-code-formatting.mdc:0-0
Timestamp: 2025-11-25T03:03:49.987Z
Learning: Applies to **/*.{js,ts,jsx,tsx,css,json,yml,yaml} : Use 2 spaces for indentation, no tabs


**Applied to files:**
- `auto-model.md`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:04:41.334Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/09-i18n-guidelines.mdc:0-0
Timestamp: 2025-11-25T03:04:41.334Z
Learning: Applies to **/*.{tsx,ts} : Use the translation wrapper component and useTranslation hook in components


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-26T05:04:26.523Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/08-contributing-guidelines.mdc:0-0
Timestamp: 2025-11-26T05:04:26.523Z
Learning: Applies to **/*.{tsx,jsx} : Use React best practices for frontend code


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:03:31.945Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/01-code-style.mdc:0-0
Timestamp: 2025-11-25T03:03:31.945Z
Learning: Applies to **/*.{jsx,tsx} : Always use useCallback for function props to maintain referential equality in React


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:03:31.945Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/01-code-style.mdc:0-0
Timestamp: 2025-11-25T03:03:31.945Z
Learning: Applies to **/*.{jsx,tsx} : Implement fallback UI for components that might fail in React


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:02:45.779Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursorrules:0-0
Timestamp: 2025-11-25T03:02:45.779Z
Learning: Applies to **/*.{jsx,tsx} : Always use useCallback for function props to maintain referential equality


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:04:51.017Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/10-testing-guidelines.mdc:0-0
Timestamp: 2025-11-25T03:04:51.017Z
Learning: Applies to **/*.{test,spec}.{ts,tsx,js,jsx} : Use React Testing Library utilities for component testing


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:04:05.715Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Applies to **/*.{jsx,tsx} : Use React state hooks for component internal state


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:04:05.715Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Extract repeated JSX patterns into reusable components


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:04:05.715Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/05-code-organization.mdc:0-0
Timestamp: 2025-11-25T03:04:05.715Z
Learning: Applies to **/*.{js,ts,jsx,tsx} : Extract complex logic into custom hooks


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:03:31.945Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/01-code-style.mdc:0-0
Timestamp: 2025-11-25T03:03:31.945Z
Learning: Applies to **/*.{jsx,tsx} : Always specify proper dependency arrays in useEffect to prevent infinite loops in React


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>
<details>
<summary>📚 Learning: 2025-11-25T03:05:07.580Z</summary>

Learnt from: CR
Repo: refly-ai/refly PR: 0
File: .cursor/rules/11-ui-design-patterns.mdc:0-0
Timestamp: 2025-11-25T03:05:07.580Z
Learning: Applies to **/*.{tsx,ts,jsx,js,vue} : Provide alternative text for images and icons


**Applied to files:**
- `packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx`

</details>

</details><details>
<summary>🧬 Code graph analysis (2)</summary>

<details>
<summary>packages/canvas-common/src/sync.ts (3)</summary><blockquote>

<details>
<summary>packages/openapi-schema/src/types.gen.ts (2)</summary>

* `ModelInfo` (5735-5792)
* `CanvasState` (2553-2578)

</details>
<details>
<summary>packages/request/src/requests/types.gen.ts (2)</summary>

* `ModelInfo` (5735-5788)
* `CanvasState` (2553-2578)

</details>
<details>
<summary>packages/canvas-common/src/types.ts (1)</summary>

* `CanvasState` (217-221)

</details>

</blockquote></details>
<details>
<summary>apps/api/src/modules/canvas/canvas.service.ts (2)</summary><blockquote>

<details>
<summary>apps/api/src/modules/provider/provider.dto.ts (1)</summary>

* `providerItem2ModelInfo` (49-64)

</details>
<details>
<summary>packages/canvas-common/src/sync.ts (1)</summary>

* `initEmptyCanvasState` (24-64)

</details>

</blockquote></details>

</details><details>
<summary>🪛 markdownlint-cli2 (0.18.1)</summary>

<details>
<summary>auto-model.md</summary>

95-95: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

96-96: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

102-102: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

132-132: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

133-133: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

135-135: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

146-146: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

148-148: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

149-149: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

---

232-232: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

</details>

<details>
<summary>⏰ 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)</summary>

* GitHub Check: build / Build

</details>

<details>
<summary>🔇 Additional comments (4)</summary><blockquote>

<details>
<summary>packages/canvas-common/src/sync.ts (1)</summary><blockquote>

`7-8`: **InitEmptyCanvasOptions and defaultModelInfo wiring look correct and backward compatible.**

Importing `ModelInfo`, adding `InitEmptyCanvasOptions`, and routing `options?.defaultModelInfo` into `metadata.modelInfo` keeps the API backward compatible and cleanly exposes the new capability.




Also applies to: 19-22, 24-24, 46-49

</blockquote></details>
<details>
<summary>packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/configure-tab.tsx (1)</summary><blockquote>

`132-143`: **Passing `defaultScene="agent"` is consistent with the new ModelSelector API.**

Using `defaultScene="agent"` here correctly opts this Agent configure tab into the agent-specific default model selection path, while leaving other callers on the `'chat'` default.

</blockquote></details>
<details>
<summary>packages/ai-workspace-common/src/components/canvas/launchpad/chat-actions/model-selector.tsx (2)</summary><blockquote>

`120-139`: **ModelLabel tooltip integration and layout look good.**

The updated `ModelLabel` cleanly adds optional tooltip text with a vertical divider and maintains truncation and error-icon behavior. This is a straightforward, purely presentational enhancement with no functional risk.

---

`43-45`: **`defaultScene`-driven default model selection is correctly wired and dependency-safe.**

The new `defaultScene?: 'chat' | 'agent'` prop, its default of `'chat'`, and the selection effect:

```ts
const defaultModel = userProfile?.preferences?.defaultModel;
const defaultModelItemId =
  defaultScene === 'agent'
    ? (defaultModel?.agent?.itemId ?? defaultModel?.chat?.itemId)
    : defaultModel?.chat?.itemId;

ensure:

  • Agent scenes prefer the agent default, gracefully falling back to the chat default.
  • Chat scenes keep existing behavior.
  • The effect only auto-selects when model is unset and modelList is non-empty.
  • Dependencies now include defaultScene and userProfile?.preferences?.defaultModel, and the memo comparator also checks defaultScene, so updates re-run when the scene changes.

This is a solid extension of the component API without breaking existing callers.

Also applies to: 208-209, 395-406, 418-425, 481-481

@nettee nettee changed the title [WIP] feat/auto model feat: Add auto model support and default configuration Dec 9, 2025
@nettee nettee requested a review from mrcfps December 9, 2025 06:38
Copy link

@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: 0

🧹 Nitpick comments (2)
apps/api/src/modules/credit/credit.service.ts (1)

857-905: Make modelName robust to missing billingModelName for older job payloads

The new split between modelName: billingModelName and actualModelName: usage.modelName looks right for distinguishing billing vs routed models. One small robustness concern: if any queued CreditUsageStep payloads were created before billingModelName was added, it will be undefined here and JSON.stringify will drop modelName entirely for those entries.

To keep historical data readable while preserving the new behavior for fresh jobs, consider a fallback:

-      modelUsageDetails.push({
-        modelName: billingModelName,
-        actualModelName: usage.modelName,
+      modelUsageDetails.push({
+        modelName: billingModelName ?? usage.modelName ?? 'unknown',
+        actualModelName: usage.modelName,
         inputTokens,
         outputTokens,
         creditCost: creditCost,
       });

This still prefers the billing label when present, but gracefully handles older or malformed payloads.

If you expect no legacy jobs in the queue, you can skip this, but it is worth double‑checking any async producers of SyncBatchTokenCreditUsageJobData to confirm they always send billingModelName.

apps/api/src/modules/credit/credit.dto.ts (1)

39-54: Interface additions align well with new routing semantics

The additions of actualModelName?: string on ModelUsageDetail and billingModelName: string on CreditUsageStep cleanly model the distinction between billed model vs actual routed model, and they match the usage in syncBatchTokenCreditUsage.

If you want to make the contract even clearer for future contributors, you could extend the comments slightly to call out expectations and legacy behavior, e.g.:

/** User-facing model name used for billing (e.g. "Auto" or direct selection). */
modelName: string;
/** Actual provider model used for execution; may be absent for legacy records. */
actualModelName?: string;

/** Model name used for billing (Auto or direct model selection), persisted in usage logs. */
billingModelName: string;

Purely a documentation refinement; the current typing and comments are already sound.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6eed128 and 2598dcf.

📒 Files selected for processing (3)
  • apps/api/src/modules/credit/credit.dto.ts (2 hunks)
  • apps/api/src/modules/credit/credit.service.ts (2 hunks)
  • apps/api/src/modules/skill/skill-invoker.service.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/api/src/modules/skill/skill-invoker.service.ts
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{js,ts,jsx,tsx}: Always use optional chaining (?.) when accessing object properties
Always use nullish coalescing (??) or default values for potentially undefined values
Always check array existence before using array methods
Always validate object properties before destructuring
Always use single quotes for string literals in JavaScript/TypeScript code

**/*.{js,ts,jsx,tsx}: Use semicolons at the end of statements
Include spaces around operators (e.g., a + b instead of a+b)
Always use curly braces for control statements
Place opening braces on the same line as their statement

**/*.{js,ts,jsx,tsx}: Group import statements in order: React/framework libraries, third-party libraries, internal modules, relative path imports, type imports, style imports
Sort imports alphabetically within each import group
Leave a blank line between import groups
Extract complex logic into custom hooks
Use functional updates for state (e.g., setCount(prev => prev + 1))
Split complex state into multiple state variables rather than single large objects
Use useReducer for complex state logic instead of multiple useState calls

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}

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

**/*.{js,ts,tsx,jsx,py,java,cpp,c,cs,rb,go,rs,php,swift,kt,scala,r,m,mm,sql}: All code comments MUST be written in English
All variable names, function names, class names, and other identifiers MUST use English words
Comments should be concise and explain 'why' rather than 'what'
Use proper grammar and punctuation in comments
Keep comments up-to-date when code changes
Document complex logic, edge cases, and important implementation details
Use clear, descriptive names that indicate purpose
Avoid abbreviations unless they are universally understood

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{js,ts,tsx,jsx}

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

Use JSDoc style comments for functions and classes in JavaScript/TypeScript

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: Use single quotes for string literals in TypeScript/JavaScript
Always use optional chaining (?.) when accessing object properties in TypeScript/JavaScript
Always use nullish coalescing (??) or default values for potentially undefined values in TypeScript/JavaScript
Always check array existence before using array methods in TypeScript/JavaScript
Validate object properties before destructuring in TypeScript/JavaScript
Use ES6+ features like arrow functions, destructuring, and spread operators in TypeScript/JavaScript
Avoid magic numbers and strings - use named constants in TypeScript/JavaScript
Use async/await instead of raw promises for asynchronous code in TypeScript/JavaScript

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Avoid using any type whenever possible - use unknown type instead with proper type guards
Always define explicit return types for functions, especially for public APIs
Prefer extending existing types over creating entirely new types
Use TypeScript utility types (Partial<T>, Pick<T, K>, Omit<T, K>, Readonly<T>, Record<K, T>) to derive new types
Use union types and intersection types to combine existing types
Always import types explicitly using the import type syntax
Group type imports separately from value imports
Minimize creating local type aliases for imported types

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{js,ts,jsx,tsx,css,json}

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

Maximum line length of 100 characters

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml}

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

Use 2 spaces for indentation, no tabs

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{js,ts,jsx,tsx,css,json,yml,yaml,md}

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

No trailing whitespace at the end of lines

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
apps/api/src/**/*.{controller,service}.ts

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

Implement proper error handling in API modules

Files:

  • apps/api/src/modules/credit/credit.service.ts
**/*.{css,scss,sass,less,js,jsx,ts,tsx}

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

**/*.{css,scss,sass,less,js,jsx,ts,tsx}: Primary color (#155EEF) should be used for main brand color in buttons, links, and accents
Error color (#F04438) should be used for error states and destructive actions
Success color (#12B76A) should be used for success states and confirmations
Warning color (#F79009) should be used for warnings and important notifications
Info color (#0BA5EC) should be used for informational elements

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use the translation wrapper component and useTranslation hook in components
Ensure all user-facing text is translatable

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{tsx,ts,json}

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

Support dynamic content with placeholders in translations

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{tsx,ts,jsx,js,vue,css,scss,less}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue,css,scss,less}: Use the primary blue (#155EEF) for main UI elements, CTAs, and active states
Use red (#F04438) only for errors, warnings, and destructive actions
Use green (#12B76A) for success states and confirmations
Use orange (#F79009) for warning states and important notifications
Use blue (#0BA5EC) for informational elements
Primary buttons should be solid with the primary color
Secondary buttons should have a border with transparent or light background
Danger buttons should use the error color
Use consistent padding, border radius, and hover states for all buttons
Follow fixed button sizes based on their importance and context
Use consistent border radius (rounded-lg) for all cards
Apply light shadows (shadow-sm) for card elevation
Maintain consistent padding inside cards (p-4 or p-6)
Use subtle borders for card separation
Ensure proper spacing between card elements
Apply consistent styling to all form inputs
Use clear visual indicators for focus, hover, and error states in form elements
Apply proper spacing between elements using 8px, 16px, 24px increments
Ensure proper alignment of elements (left, center, or right)
Use responsive layouts that work across different device sizes
Maintain a minimum contrast ratio of 4.5:1 for text

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{tsx,ts,jsx,js,vue}

📄 CodeRabbit inference engine (.cursor/rules/11-ui-design-patterns.mdc)

**/*.{tsx,ts,jsx,js,vue}: Include appropriate loading states for async actions in buttons
Group related form elements with appropriate spacing
Provide clear validation feedback for forms
Ensure proper labeling and accessibility for form elements
Ensure all interactive elements are keyboard accessible
Include appropriate ARIA attributes for complex components
Provide alternative text for images and icons
Support screen readers with semantic HTML elements

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.ts
**/*.{ts,tsx,js,jsx}

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

**/*.{ts,tsx,js,jsx}: Follow the TypeScript/JavaScript style guidelines
Ensure code is well-tested and documented

Files:

  • apps/api/src/modules/credit/credit.service.ts
  • apps/api/src/modules/credit/credit.dto.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). (1)
  • GitHub Check: build / Build

@mrcfps mrcfps merged commit 573af51 into main Dec 9, 2025
2 checks passed
@mrcfps mrcfps deleted the feat/auto-model branch December 9, 2025 07:54
mrcfps added a commit that referenced this pull request Dec 9, 2025
* fix(auth): short-circuit failed-auth redirect (#1749)

fix(auth): short-circuit failed-auth redirect; clarify root cause vs fixes

Summary:
- Break the login/workspace refresh loop by short-circuiting failed-auth navigation when already on public pages (incl. '/login') or root '/'.
- Keep success path and AppLayout root redirection unchanged; work together with #1733 to reduce redundant triggers and avoid loops.

Root cause (not all three are causes):
- 36b7ceb introduced root-path redirection ("/" -> "/login" or "/workspace") and simplified logout to clear storage and redirect, amplifying downstream redirects.
- PR #1730 added public-page checks and (initially) put location.pathname into useEffect deps in use-get-user-settings; in failed-auth it navigated to "/?...". Combined with the root redirection, this formed a loop: protected route -> failed auth -> navigate('/?returnUrl=...') -> AppLayout redirects to '/login' -> login check retriggers -> repeat.
- PR #1733 is a fix (not a cause): it removed the location dependency (using window.location.pathname inside async), which reduces unnecessary retriggers.

Fix (this commit):
- In use-get-user-settings.ts, read currentPath via window.location.pathname and short-circuit navigation on public pages or when at root '/'. Only navigate back to '/?...' when currentPath is non-public and not '/' and not '/login'.

Impact:
- No change to success path (userStore updates, localStorage writes, i18n) or to AppLayout's authority over root redirection.
- Public pages remain accessible; protected pages still end up at '/login' via root handler.

Verification:
- Clear browser cache to fetch latest bundle, then verify: '/login' stable, public pages do not bounce, protected routes still route to '/login' via '/', unauthenticated workspace no longer flickers.

Refs:
- 36b7ceb (fix: optimize canvas initial load and page redirection) 36b7ceb37
- PR #1730 (prevent public pages from redirecting to login on 401) #1730
- PR #1733 (prevent workspace tab switching from triggering login status check) #1733

* feat: add login page telemetry event (#1754)

feat: login page login event

* feat(workflow): update create modal component (#1755)

* feat: add dual file URL placeholders for emails and improve HTTP cache validation with OSS lastModified (#1756)

feat: Use OSS lastModified for file metadata and enhance SendEmailTool to support direct content URLs for embedded files.

* chore: improve deployment configuration and simplify module initialization patterns (#1751)

* chore: update deploy-test workflow with additional environment variables

- Added new environment variables for VITE API and collaboration endpoints, Sentry configuration, and subscription settings to enhance deployment capabilities.
- Updated AWS region configuration to use variables for improved flexibility and maintainability.
- Ensured compliance with existing coding standards and best practices.

* refactor(api): enhance module initialization with timeout and retry logic

- Replaced manual timeout handling in multiple services with a unified `runModuleInitWithTimeoutAndRetry` utility for improved readability and maintainability.
- Updated `onModuleInit` methods across various services including PrismaService, RedisService, FulltextSearchService, and others to utilize the new utility.
- Ensured compliance with existing coding standards, including optional chaining and nullish coalescing for safer property access.
- Enhanced logging for better traceability during initialization processes.

* chore(api): remove PrismaService from multiple modules and update package.json

- Removed PrismaService from the providers in CopilotAutogenModule, CreditModule, FormModule, InvitationModule, InternalMcpModule, and McpServerModule to streamline dependencies.
- Updated package.json to remove the Prisma instrumentation dependency, reflecting the changes in module structure.
- Ensured compliance with existing coding standards and best practices.

* refactor(api): remove Redis session middleware and update Redis client initialization for bullmq

- Removed Redis session middleware from the main application bootstrap process to streamline session management.
- Updated RedisService to enhance client initialization with improved configuration options, including maxRetriesPerRequest for better handling of blocking commands.
- Adjusted module imports to utilize the new CommonModule and RedisService for Redis client management.
- Ensured compliance with existing coding standards and best practices.

* chore: update deploy-test workflow conditions for EKS image updates

- Modified conditions for updating API and Web deployment images on EKS to only trigger on 'main' or 'stable' branches, enhancing deployment control.
- Updated kubeconfig step to align with the new branch conditions for improved workflow clarity and maintainability.
- Ensured compliance with existing coding standards and best practices.

* feat(utils): enhance module initialization with retry delay and improved logging

- Added retryDelayMs option to ModuleInitOptions for configurable retry delays during initialization.
- Introduced sleep function to facilitate delays between retry attempts.
- Updated logging to provide clearer feedback on retry attempts and success.
- Ensured compliance with existing coding standards, including optional chaining and nullish coalescing for safer property access.

* fix(api): add error handling for uninitialized Redis client

- Implemented a check in the getClient method of RedisService to throw an error if the Redis client is not initialized, improving robustness and error handling.
- Ensured compliance with existing coding standards and best practices.

* refactor: optimize PriceContent component and update translations (#1759)

* refactor: update priceContent component styles and translations

- Changed font weight of the feature name in the priceContent component for better visual consistency.
- Removed unnecessary padding from the sub-items list in the priceContent component to streamline layout.
- Updated translations for point-free tools in both English and Chinese, enhancing clarity and accuracy of tool names.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* fix(i18n): update duration in translations from '365 DAYS' to '1 MONTH'

- Changed the duration value in the translations to reflect a more accurate time frame.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* feat: implement comprehensive canvas data sanitization for workflow a… (#1762)

* feat: implement comprehensive canvas data sanitization for workflow app sharing

* refactor: streamline minimap URL handling and add defensive checks for file IDs

- Simplified minimap URL usage by directly utilizing the existing published URL from canvas data.
- Added defensive checks to ensure only files with valid file IDs are processed in the workflow app.

* feat: optimize tool installation and dependency checker (#1764)

* fix: update default formatter for SQL files and enhance billing service logic for free tool access

* fix: update toolset authorization logic to use user tools instead of installed toolsets

* fix: update ToolInstallModal component for improved user experience

* refactor: simplify workflow plan schema and update documentation (#1765)

* refactor: simplify workflow plan schema and update documentation

- Removed unnecessary product-related fields from the workflow plan schema to streamline the structure.
- Updated documentation in the copilot-agent prompts to reflect the changes in the expected input arrays for the `generate_workflow` tool.
- Enhanced clarity in the documentation regarding task dependencies and tool selection guidelines.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* refactor: update documentation for web search constraints and tool usage

- Removed outdated web search constraint and clarified the tools available for information retrieval in the copilot-agent documentation.
- Updated guidelines for task execution and data flow to enhance clarity for users.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* feat: Add auto model support and default configuration (#1763)

* req

* [local dev]

* add auto to model list

* icon for auto

* tooltip for auto

* default agent node model

* model routing

* fix billing

* fix fallback

* big review

* refactor model router

* refactor skills

* 2

* revert tracer

* fix

* fix TODOs

* update sql

* fix default model

* revert doc

* credit usage

* feat: improve mention insertion and keyboard navigation (#1766)

* fix: update default formatter for SQL files and enhance billing service logic for free tool access

* fix: update toolset authorization logic to use user tools instead of installed toolsets

* fix: update ToolInstallModal component for improved user experience

* fix: enhance mention handling and range resolution in RichChatInput component

* feat: enhance toolset handling with type definitions and MCP support

* fix: missing billing info for composio-based tools (#1772)

- Introduced optional resultId and version properties in ProcessBillingOptions interface to enhance flexibility in billing processes.
- Updated BillingService to utilize these new properties, falling back to context values if not provided.
- Modified ComposioService and PostHandlerService to include resultId and version in context handling, improving data consistency across services.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* chore: refactor staging and prod deployment workflows (#1769)

* chore: refactor deployment workflows to use a shared deploy API configuration

- Updated the deploy API workflows for production and staging to utilize a shared configuration file, reducing redundancy and improving maintainability.
- Removed individual steps for kubectl installation and configuration, streamlining the deployment process.
- Ensured compliance with existing coding standards and best practices.

* chore: remove outdated Docker build workflow

- Deleted the build and push Docker images workflow from GitHub Actions as it is no longer needed.
- Ensured compliance with existing coding standards and best practices.

* Revert "feat: implement comprehensive canvas data sanitization (#1773)

Revert "feat: implement comprehensive canvas data sanitization for workflow a… (#1762)"

This reverts commit 4a71185.

* Feat/document download (#1767)

* refactor: streamline drive and knowledge modules, enhance markdown tool integration

- Refactored drive.controller.ts and drive.service.ts for improved code clarity and maintainability.
- Updated document.service.ts and knowledge.controller.ts to enhance functionality and performance.
- Enhanced product-card.tsx and NodeRenderer.tsx components with Tailwind CSS for consistent styling.
- Improved use-export-document.ts and services.gen.ts for better service management.
- Updated i18n translations in ui.ts files for English and Chinese to ensure consistency.
- Refactored OpenAPI schema and types.gen.ts for better API documentation and structure.
- Ensured compliance with optional chaining and nullish coalescing for safer property access throughout the codebase.

* refactor: update import-from-file component and enhance translations

- Refactored the ImportFromFile component to simplify file parsing usage checks and improve user messaging.
- Updated translations in English and Chinese to include a new message for maximum upload size.
- Ensured compliance with Tailwind CSS for consistent styling and applied optional chaining and nullish coalescing for safer property access.

* Optimize the fallback icon of mcp 

* fix: update default formatter for SQL files and enhance billing service logic for free tool access

* fix: update toolset authorization logic to use user tools instead of installed toolsets

* fix: update ToolInstallModal component for improved user experience

* fix: enhance mention handling and range resolution in RichChatInput component

* feat: enhance toolset handling with type definitions and MCP support

* refactor: simplify Favicon component by removing isMcp prop and related logic

* fix: update logEvent calls to include timestamps for better tracking (#1775)

- Modified multiple components to include the current timestamp when logging events, enhancing the accuracy of event tracking.
- Ensured compliance with coding standards, including the use of optional chaining and nullish coalescing where applicable.
- Wrapped components with React.memo to optimize performance and prevent unnecessary re-renders.

* feat: optimize copilot plan schema and update recommendations (#1774)

* feat: update recommendations for copilot

- Revised query translations in both English and Chinese to provide clearer and more specific instructions for users.
- Enhanced the accuracy of the queries related to Warren Buffett's stock portfolio and Product Hunt listings.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* refactor: simplify workflow plan schema and enhance documentation

- Removed validation messages for task and variable fields in the workflow plan schema to streamline the structure.
- Updated documentation in the copilot-agent prompts to include new variable design principles, enhancing clarity and usability.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* feat: enhance copilo recommendations for clarity and specificity

- Updated query translations in both English and Chinese to provide clearer instructions for users regarding Warren Buffett's stock portfolio and Product Hunt listings.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* fix: handle null form definition in getFormDefinition method

- Updated the getFormDefinition method to return null if no form definition is found, improving error handling.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* feat: track view_template_detail event on page load (#1779)

- Added a useEffect hook to log the 'view_template_detail' event when the page loads completely, ensuring that shareId, loading state, and workflowApp are validated before logging.
- Utilized optional chaining and nullish coalescing for safer property access and default values.

* reduce the constrains of url in composio

* fix: update default formatter for SQL files and enhance billing service logic for free tool access

* fix: update toolset authorization logic to use user tools instead of installed toolsets

* fix: update ToolInstallModal component for improved user experience

* fix: enhance mention handling and range resolution in RichChatInput component

* feat: enhance toolset handling with type definitions and MCP support

* refactor: simplify Favicon component by removing isMcp prop and related logic

* correct toolset authorization logic in isToolsetAuthorized function

* fix(api): expose internal toolsets to be visible to copilot  (#1783)

* fix(api): expose internal toolsets to be visible to copilot

- Updated SkillService to include toolsets in the JSON stringification process, ensuring all relevant parameters are captured.
- Simplified the filtering logic in ToolService to enhance readability while maintaining functionality.
- Ensured compliance with coding standards, including optional chaining and nullish coalescing for safer property access.

* fix(i18n): correct punctuation in query translation for clarity

- Updated the query translation for Warren Buffett's holdings to include a period at the end, enhancing clarity and consistency in the text.
- Ensured compliance with coding standards, including the use of optional chaining and nullish coalescing for safer property access.

---------

Co-authored-by: Achieve <[email protected]>
Co-authored-by: lefarcen <[email protected]>
Co-authored-by: Siri-Ray <[email protected]>
Co-authored-by: a1chzt <[email protected]>
Co-authored-by: William Liu <[email protected]>
Co-authored-by: Sophia <[email protected]>
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.

3 participants