Skip to main content

Overview

Polaris IDE integrates cutting-edge AI capabilities directly into your coding workflow, providing inline suggestions, natural language editing, and contextual code assistance.

Auto-Suggestions

Real-time code completions as you type

Quick Edit

Transform code using natural language

Context-Aware

AI understands your entire codebase

AI Providers

Polaris supports multiple AI providers for maximum flexibility:
ProviderModelUse CaseConfiguration
OpenRouterMoonshot AI Kimi K2.5Primary coding assistant (recommended)OPENROUTER_API_KEY
CerebrasCerebras GLM-4.7Free fallback, fast inferenceCEREBRAS_API_KEY
From package.json:
{
  "@ai-sdk/anthropic": "^3.0.28",
  "@cerebras/cerebras_cloud_sdk": "^1.64.1",
  "ai": "^6.0.6"
}
Note: @ai-sdk/anthropic is used as a client but configured to connect to OpenRouter’s API endpoint.
Moonshot AI Kimi K2.5 via OpenRouter is the preferred model for production use, offering excellent performance for code generation. Cerebras GLM-4.7 provides a free, high-speed fallback.

Inline Suggestions

How It Works

As you type, Polaris analyzes your code and suggests completions in real-time:
1

Trigger

Start typing code - suggestions appear after 300ms of inactivity
2

Preview

Ghost text appears showing the AI’s suggestion
3

Accept

Press Tab to accept the suggestion

Contextual Intelligence

The AI considers multiple factors when generating suggestions:
const payload = {
  fileName,              // File context
  code,                  // Full file content
  currentLine,           // Active line
  previousLines,         // 5 lines before cursor
  textBeforeCursor,      // Text on current line before cursor
  textAfterCursor,       // Text on current line after cursor
  nextLines,             // 5 lines after cursor
  lineNumber,            // Current position
};
// From suggestion/index.ts
const generatePayload = (view: EditorView, fileName: string) => {
  const code = view.state.doc.toString();
  const cursorPosition = view.state.selection.main.head;
  const currentLine = view.state.doc.lineAt(cursorPosition);

  // Gather context: 5 lines before and after
  const previousLines: string[] = [];
  for (let i = Math.min(5, currentLine.number - 1); i >= 1; i--) {
    previousLines.push(view.state.doc.line(currentLine.number - i).text);
  }

  const nextLines: string[] = [];
  const totalLines = view.state.doc.lines;
  for (let i = 1; i <= Math.min(5, totalLines - currentLine.number); i++) {
    nextLines.push(view.state.doc.line(currentLine.number + i).text);
  }

  return {
    fileName,
    code,
    currentLine: currentLine.text,
    previousLines: previousLines.join("\n"),
    nextLines: nextLines.join("\n"),
    lineNumber: currentLine.number,
  };
};

Debouncing & Performance

Suggestions are optimized to avoid overwhelming the AI API:

Smart Debouncing

  • 300ms delay after typing stops before requesting suggestions
  • Request cancellation when you continue typing
  • Abort controllers prevent stale suggestions from appearing
const DEBOUNCE_DELAY = 300;
let currentAbortController: AbortController | null = null;

// Cancel previous request
if (currentAbortController !== null) {
  currentAbortController.abort();
}

// Wait for user to stop typing
debounceTimer = window.setTimeout(async () => {
  currentAbortController = new AbortController();
  const suggestion = await fetcher(payload, currentAbortController.signal);
}, DEBOUNCE_DELAY);

Quick Edit (Cmd+K)

Natural Language Code Editing

Transform selected code using plain English instructions:
1

Select Code

Highlight the code you want to modify
2

Press Cmd+K

A tooltip appears with an input field
3

Describe Changes

Type what you want to change (e.g., “add error handling”)
4

Submit

AI rewrites the code and replaces your selection

Example Use Cases

Refactoring

“Convert this to async/await”

Error Handling

“Add try-catch blocks”

Optimization

“Make this function more efficient”

Documentation

“Add JSDoc comments”

How It Works

Quick Edit sends your instruction along with code context to the AI:
// From quick-edit/index.ts
const payload = {
  selectedCode,    // The code you selected
  fullCode,        // Complete file for context
  instruction,     // Your natural language instruction
};

const editedCode = await fetcher(payload, signal);

// Replace selected code with AI's version
view.dispatch({
  changes: {
    from: selection.from,
    to: selection.to,
    insert: editedCode,
  },
});
Be specific in your instructions for best results. Instead of “improve this”, try “add input validation and error messages”.

Selection Tooltip

When you select code, a contextual toolbar appears with AI actions:

Available Actions

  • Add to Chat - Send selected code to AI conversation
  • Quick Edit (⌘K) - Transform code with natural language
// Tooltip appears when you select text
const createTooltipForSelection = (state: EditorState) => {
  const selection = state.selection.main;
  if (selection.empty) return [];

  return [{
    pos: selection.to,
    create() {
      const addToChatButton = document.createElement("button");
      addToChatButton.textContent = "Add to Chat";
      
      const quickEditButton = document.createElement("button");
      quickEditButton.textContent = "Quick Edit ⌘K";
      
      // ... button handlers
    }
  }];
};

AI Integration Architecture

Extension System

AI features are implemented as CodeMirror extensions:
// From code-editor.tsx
const view = new EditorView({
  extensions: [
    // ... base extensions
    suggestion(fileName),      // Inline AI suggestions
    quickEdit(fileName),       // Cmd+K editing
    selectionTooltip(),        // Selection actions
  ],
});
Each extension is self-contained with:
  • State management (StateField)
  • UI rendering (ViewPlugin, WidgetType)
  • Keyboard shortcuts (keymap)
  • API integration (fetcher functions)

State Management

AI features use CodeMirror’s state system:
import { StateField, StateEffect } from "@codemirror/state";

// Define an effect to update suggestion
const setSuggestionEffect = StateEffect.define<string | null>();

// Store suggestion in editor state
const suggestionState = StateField.define<string | null>({
  create() {
    return null;
  },
  update(value, transaction) {
    for (const effect of transaction.effects) {
      if (effect.is(setSuggestionEffect)) {
        return effect.value;
      }
    }
    return value;
  },
});

Best Practices

Context Matters

The AI works better with well-structured code and clear variable names

Incremental Changes

Use Quick Edit for focused transformations rather than rewriting entire functions

Review AI Output

Always review AI-generated code before committing changes

Specific Instructions

Detailed prompts produce better results than vague requests

API Endpoints

AI features connect to API routes for processing:
API endpoints handle authentication, rate limiting, and AI provider communication. All requests are authenticated using Stack Auth.
// Suggestion fetcher
async function fetcher(payload: SuggestionPayload, signal: AbortSignal) {
  const response = await fetch('/api/ai/suggest', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
    signal,
  });
  
  return await response.text();
}

Limitations

  • Suggestions may take 1-3 seconds depending on API response time
  • Very large files (>5000 lines) may have reduced context
  • API rate limits apply based on your subscription tier

Next Steps

Code Editor

Learn about core editor features and shortcuts

Real-Time Collaboration

See how changes sync across users in real-time

Build docs developers (and LLMs) love