Explainix — AI-Powered Code Tutor for VS Code
Explainix is an AI-powered code explanation and teaching assistant. Select any function, class, method, or code block, press Ctrl+Enter, and Explainix generates a detailed educational comment block directly above your selection — without ever modifying your code.
Explainix goes beyond summarization: it explains code from the fundamentals, teaches the reasoning behind implementation decisions, describes the purpose of every parameter and variable, and shows how components work together. All explanations are written in Persian (فارسی) or English — you choose.
✨ Features
- One-shortcut workflow — select code, press
Ctrl+Enter, review, insert. Your selection and cursor are preserved; the insertion is a single undoable step (Ctrl+Z).
- Educational explanations, not summaries — the generated comments answer: what the code does, why it exists, which concepts are used, what each parameter/variable represents, how execution flows step by step, how errors are handled, which assumptions and edge cases matter, how the code interacts with other components, and what a beginner should know first.
- Persian & English comments — Persian is the default. Identifiers, function names, class names, and API names are never translated. Switch language at any time — no restart needed.
- Four explanation depths — Beginner, Intermediate, Advanced, Comprehensive (default).
- Language-aware comment formatting — correct syntax per language, doc comments (JSDoc / Rust
/// / C# ///) where appropriate, indentation and line endings preserved, Unicode/Persian-safe.
- Project-aware context — staged context retrieval: unresolved symbols in the selection are looked up in the workspace (definitions, interfaces, implementations), and only the necessary minimal previews are sent. Secrets are never read or transmitted.
- Explain Entire File — inserts a file-overview comment at the top of the document (below shebang lines).
- Explain Project — scans the workspace tree, manifests, and entry points, then produces a full architecture Markdown document in your selected language.
- Preview before insert — review, edit, regenerate, change language/depth, accept, or cancel. Nothing touches your file until you accept.
- Multiple AI providers — OpenAI-compatible APIs, Z.AI GLM Coding Plan, OpenRouter (free and paid models with live catalog), and ChatGPT via the official Codex CLI, behind a clean provider abstraction.
- Process Queue & Task Manager — submit several requests without waiting: they run one at a time in the background with a live queue list (status, progress, ETA), cancel/retry/reorder controls, and persistence across reloads.
- Dynamic model discovery — OpenRouter and OpenAI-compatible catalogs are queried live; Codex CLI models are discovered from the CLI's own cache (
$CODEX_HOME/models_cache.json) with jq plus a native-JSON fallback — no hardcoded model IDs anywhere.
- Secure by design — API keys live only in VS Code SecretStorage; never in settings, source files, logs, or generated comments. Sensitive files (
.env, keys, credentials) are excluded from AI requests by default, with content-based secret detection as defense in depth.
- Non-blocking & reliable — fully asynchronous with progress notifications, request cancellation, timeouts, retry with
Retry-After support, rate-limit handling, malformed-response protection, markdown cleanup, and duplicate-comment detection.
📦 Installation
From the packaged VSIX
code --install-extension explainix-1.2.4.vsix
Then reload VS Code. You will see the Explainix icon in the Activity Bar.
From source
git clone <this-repo> explainix
cd explainix
npm install
npm run package # produces explainix-1.2.4.vsix
code --install-extension explainix-1.2.4.vsix
Troubleshooting: "Could not register service worker"
If the Code Explanation panel shows
Error: Could not register service worker: InvalidStateError, this is a VS Code
webview infrastructure issue (a stale service worker left behind by a previous
install, or an open panel during an update) — not an extension defect. Recovery:
- Run Developer: Reload Window (or fully restart VS Code).
- If it persists, close all VS Code windows and clear the webview caches:
- Windows: delete
%APPDATA%\Code\Service Worker, %APPDATA%\Code\Cache, %APPDATA%\Code\Code Cache
- macOS: delete
~/Library/Application Support/Code/Service Worker, …/Cache, …/Code Cache
- Linux: delete
~/.config/Code/Service Worker, ~/.config/Code/Cache, ~/.config/Code/Code Cache
- Install the extension again and reload the window.
Tip: close the Explanation panel before reinstalling or upgrading the extension.
🚀 Quick Start
- Open a source file and select a function, class, or code block.
- A subtle ⚡ Explainix · Ctrl+Enter affordance appears at the selection (ghost-text decoration + hover with clickable actions — the officially supported mechanisms).
- Press Ctrl+Enter (or Cmd+Enter on macOS).
- The preview panel opens beside the editor and streams the explanation.
- Review/edit the text, then click Insert comments. The comment block is inserted above the selection via the WorkspaceEdit API — one undo step, selection preserved, original code untouched.
If nothing is selected, Explainix shows a helpful message asking you to select code first.
⌨️ Keyboard Shortcuts & Commands
| Shortcut / Command |
Action |
Ctrl+Enter / Cmd+Enter |
Explain the selected code (context-aware: explains selection when present, otherwise shows guidance) |
Explainix: Explain Selected Code |
Same as the shortcut, from the Command Palette and editor context menu |
Explainix: Explain Entire File |
Inserts a file-overview comment at the top of the file |
Explainix: Explain Project |
Generates a project-architecture Markdown document |
Explainix: Select Comment Language / انتخاب زبان توضیحات |
Switch between Persian and English |
Explainix: Select Explanation Depth |
Beginner / Intermediate / Advanced / Comprehensive |
Explainix: Select AI Provider |
OpenAI / Z.AI GLM Coding Plan / OpenRouter / ChatGPT (Codex CLI) |
Explainix: Select AI Model — انتخاب مدل هوش مصنوعی |
Pick the exact model for the active provider (discovered live when supported, curated otherwise, or type any model ID) |
Explainix: Test Connection — تست اتصال |
Verifies authentication, connectivity, and that the selected model responds — using a tiny real request |
Explainix: Show Process Queue — مشاهده صف پردازش |
Opens the sidebar Process Manager (queue status, progress, cancel/retry/reorder) |
Explainix: Login to ChatGPT (Codex) — ورود با مرورگر |
Runs codex login in a terminal — browser-based sign-in for ChatGPT subscriptions (no API key) |
Explainix: Set API Key |
Securely store a provider API key (SecretStorage) |
Explainix: Clear API Key |
Remove a stored API key |
Explainix: Show Output Log |
Open the Explainix output channel |
🌐 Language Selection (Persian / English)
The comment language is a mandatory, first-class setting:
{
"explainix.commentLanguage": "fa",
"explainix.provider": "openai",
"explainix.explanationDepth": "detailed"
}
explainix.commentLanguage: "fa" (Persian, default) or "en" (English).
- Changes apply immediately — no VS Code restart required. You can change it from:
- the status-bar item (
⚡ Explainix · FA/EN, click to change),
- the sidebar webview,
- the preview panel's language dropdown,
- the Command Palette command.
- Persian output rules: natural, technically accurate Persian; programming keywords, identifiers, function/class names, and API names are preserved verbatim; standard Persian technical terminology; renders correctly in the editor.
- English output rules: clear, professional technical English; original identifiers preserved.
- The selected language applies consistently to selection explanations, file overviews, project-architecture documents, and all user-facing messages.
explainix.explanationDepth: beginner | intermediate | advanced | comprehensive (default).
🧠 Model Selection
Explainix separates provider from model, and remembers a model per provider:
- Select provider:
Explainix: Select AI Provider (or the sidebar dropdown). Switching providers preserves each provider's model — switching back restores your previous choice.
- Select model:
Explainix: Select AI Model shows the current provider and model, then lists available models:
- Dynamic discovery — OpenAI-compatible endpoints are queried live (
GET /models); OpenRouter publishes its full catalog with names, pricing and context limits; the Codex CLI's cache ($CODEX_HOME/models_cache.json, default ~/.codex/models_cache.json) is parsed with jq (native JSON fallback). The list refreshes automatically when the settings view opens and on demand via the refresh action. The list status is shown in the picker and the sidebar.
- Curated lists — when a provider exposes no discovery endpoint (the GLM Coding Plan), Explainix shows the officially supported models:
glm-4.6, glm-4.5-air, glm-4.5. A notice makes it clear the list is curated. Codex CLI and OpenRouter have no hardcoded fallback models — discovery failure leaves the model empty so the CLI/provider default is used instead of forcing an unsupported ID.
- Manual entry — type any model ID (QuickPick item or the sidebar input). IDs are validated (no spaces or angle brackets).
- Per-provider storage — the active model is mirrored to
explainix.model, and each provider's choice is stored separately (explainix.openai.model, explainix.zai.model, explainix.openrouter.model, explainix.codexCli.model). Editing explainix.model in the Settings UI syncs to the active provider automatically.
- Model-aware context — the code context sent with each request is capped by the selected model's context window (unknown models get a conservative 32k-token budget), so small-context models work safely.
- Streaming fallback — if a model/endpoint rejects streaming, Explainix retries once with the same model without streaming and informs you. It never silently switches models.
- Model unavailable — 404 / "model does not exist" responses surface an explicit
model_unavailable error with a Select another model action.
- Test Connection —
Explainix: Test Connection sends a tiny request with the exact selected model and reports authentication/connectivity/model availability.
Availability is never assumed: a model existing in a provider's general API is not treated as available on a Coding Plan — only the plan's endpoint and curated list decide, and Test Connection verifies it.
🤖 AI Provider Setup
Providers are pluggable (see src/providers/AIProvider.ts). All providers support model selection, prompt submission, streaming (where available), cancellation, error handling, and token-usage reporting where the backend provides it.
Provider A: OpenAI-compatible API
- Run Explainix: Set API Key and choose OpenAI-compatible API.
- Paste your API key (stored in SecretStorage only).
Configuration:
{
"explainix.provider": "openai",
"explainix.openai.baseUrl": "https://api.openai.com/v1",
"explainix.openai.model": "gpt-4o-mini",
"explainix.openai.requestTimeoutMs": 120000
}
The baseUrl accepts any OpenAI-compatible endpoint.
ChatGPT subscription (Codex CLI) — and its limitations
Important: a ChatGPT (Plus/Pro/Team) subscription does not include access to the public OpenAI API. Explainix does not reverse-engineer private ChatGPT endpoints, reuse browser session cookies, or bypass subscription restrictions.
The supported way to use a ChatGPT subscription is the official, open-source Codex CLI:
- Install the CLI:
npm install -g @openai/codex
- Sign in once with your ChatGPT account:
codex login
- Select the provider: Explainix: Select AI Provider → ChatGPT (Codex CLI)
Explainix then invokes the documented non-interactive mode (codex exec, prompt on stdin, answer from stdout). No API key is needed — authentication is handled by the CLI itself (ChatGPT-account sign-in via codex login).
Model discovery: available models are read from the CLI's own cache — $CODEX_HOME/models_cache.json (default ~/.codex/models_cache.json) — using jq -r '.models[].slug' when jq is installed, with a native JSON-parsing fallback. Model IDs are passed to --model verbatim. If the cache is missing, unreadable, or empty, Explainix shows a notice and leaves codexCli.model empty so the CLI uses its own default model — an unsupported model is never forced.
Configuration:
{
"explainix.provider": "codex-cli",
"explainix.codexCli.path": "codex",
"explainix.codexCli.args": ["exec", "--skip-git-repo-check", "-"],
"explainix.codexCli.model": "",
"explainix.codexCli.requestTimeoutMs": 180000
}
Limitations: streaming and token-usage reporting depend on the CLI version; the binary must be installed and logged in; timeouts and cancellation terminate the child process.
Provider B: Z.AI GLM Coding Plan
Explainix uses the official GLM Coding Plan endpoint — which is distinct from Z.AI's general open-platform API:
https://api.z.ai/api/coding/paas/v4
- Run Explainix: Set API Key, choose Z.AI GLM Coding Plan, and paste your Coding Plan key.
- Configure (defaults shown):
{
"explainix.provider": "zai",
"explainix.zai.baseUrl": "https://api.z.ai/api/coding/paas/v4",
"explainix.zai.model": "glm-4.6",
"explainix.zai.requestTimeoutMs": 120000
}
For China mainland access, set explainix.zai.baseUrl to https://open.bigmodel.cn/api/paas/v4.
Provider C: OpenRouter
OpenRouter gives access to hundreds of models (free and paid) through one OpenAI-compatible API:
https://openrouter.ai/api/v1
- Create an API key at openrouter.ai/keys.
- Run Explainix: Set API Key, choose OpenRouter, and paste the key (stored in SecretStorage only).
- Pick a model via Explainix: Select AI Model — the selector lists the live catalog with display names, per-token pricing and context limits (e.g.
deepseek/deepseek-chat-v1:free · free · 64k ctx). Model IDs are preserved verbatim, including :free suffixes.
Configuration (defaults shown — leave openrouter.model empty until you pick one):
{
"explainix.provider": "openrouter",
"explainix.openrouter.baseUrl": "https://openrouter.ai/api/v1",
"explainix.openrouter.model": "",
"explainix.openrouter.requestTimeoutMs": 120000
}
Features: searchable model selector, manual refresh of the catalog, streaming and non-streaming responses (with the same-model streaming fallback), configurable temperature and max output tokens, request timeouts, connection testing, and clear errors for invalid keys, timeouts and rate limits. The key is never written to logs or the UI.
🧰 Process Queue & Task Manager
Explainix never blocks you on a running request — submit as many explain requests (selection / file / project) as you like:
- New requests are enqueued automatically and executed one at a time in the background; the next request starts as soon as the current one finishes.
- The Process Manager (sidebar card, or
Explainix: Show Process Queue) lists every request with title/description, status (Queued / Processing / Completed / Failed / Cancelled), real-time progress percentage where available, submission time, estimated remaining time, and queue position — fully localized and RTL-aware for Persian.
- Per-request actions: cancel, retry (failed/cancelled), remove, reorder (↑/↓). Global actions: Cancel All, Clear Completed.
- The queue persists across reloads: queued requests resume after a window reload; a request that was mid-flight becomes Failed with a retry action.
- Duplicate protection: submitting an identical request while it is queued/processing is detected and reported instead of being queued twice.
- Completion and failure notifications offer View / Retry actions; a status-bar badge (
$(sync) N) shows active + pending requests.
- Submitting shows: «درخواست شما به صف پردازش اضافه شد. میتوانید وضعیت آن را در بخش مدیریت پردازشها مشاهده کنید.» with a مشاهده صف پردازش button.
🏗️ Architecture
explainix/
├── src/
│ ├── extension.ts # activation, command registration, wiring
│ ├── settings.ts # typed configuration reader/writer
│ ├── types.ts # shared pure types
│ ├── commands/ # explainSelection, explainFile, explainProject, shared flows (submit to queue)
│ ├── queue/ # ProcessQueue (state), executors, QueueController, formatting
│ ├── providers/ # AIProvider abstraction, OpenAI, Z.AI, OpenRouter, Codex CLI (+ model discovery), HTTP client
│ ├── analysis/ # CodeAnalyzer, WorkspaceAnalyzer, ContextResolver
│ ├── comments/ # CommentFormatter, CommentInserter, LanguageRegistry
│ ├── prompts/ # explanationPrompt, projectAnalysisPrompt
│ ├── ui/ # PreviewPanel, ExplainixView (sidebar), LanguageSelector, DecorationController
│ ├── security/ # SecretManager (SecretStorage wrapper)
│ └── utils/ # i18n, logger (redacting), markdown cleanup, retry helpers
├── test/
│ ├── unit/ # pure-logic tests (mocha, no VS Code)
│ └── integration/ # real VS Code workflow tests (@vscode/test-electron)
├── scripts/runIntegration.js
├── esbuild.js # bundler (dev + production)
├── package.json # extension manifest
├── README.md / README.fa.md # English docs / Persian guide
└── CHANGELOG.md
Design notes:
- Pure core — the analyzer, formatter, prompts, retry logic, HTTP client, and the process-queue state machine never import the
vscode runtime, which keeps them fast to test and reusable.
- Provider abstraction —
createProvider(settings, secrets) returns any AIProvider; adding a provider requires no changes to command or comment logic.
- Staged context retrieval — selection → unresolved symbols → workspace symbol lookup → budget-capped previews. The whole project is never sent.
- Safe insertion — document version + first-line revalidation before every edit; existing Explainix blocks are detected and offered for replacement; every change is a single WorkspaceEdit step.
🗣️ Supported Programming Languages
First-release comment formatting is built in for:
Go · Python · JavaScript · TypeScript (and JSX/TSX) · Java · C · C++ · Rust · C# · PHP · Ruby · Kotlin · Swift · SQL · Bash/Shell · PowerShell (plus Scala and Dart as a bonus).
- Doc-style comments are chosen automatically for functions/classes when the language supports them (
comments.docStyle: "auto"); force "line" or "doc" if you prefer.
- Any other language still works through the configurable fallback prefix (
explainix.comments.fallbackLinePrefix, default //).
🔒 Privacy & Security
- API keys are stored only in VS Code SecretStorage and are redacted from logs.
- The files below are never read or sent to any AI provider (configurable):
"explainix.privacy.excludedGlobs": [
"**/.env*", "**/*.pem", "**/*.key", "**/id_rsa*",
"**/credentials*", "**/secrets*", "**/*.p12", "**/*.pfx"
]
- Content-based secret detection adds a second layer: any file whose preview looks like it contains private keys or credentials is skipped.
- Context is budget-capped (
explainix.context.maxContextChars), and only workspace files inside opened folders are accessed.
- Prompt text, responses, and key material are never logged — only lengths, statuses, and redacted error messages.
⚙️ Configuration Reference
| Setting |
Default |
Description |
explainix.commentLanguage |
"fa" |
Comment language: "fa" or "en" |
explainix.explanationDepth |
"comprehensive" |
beginner / intermediate / advanced / comprehensive |
explainix.provider |
"openai" |
openai / zai / openrouter / codex-cli |
explainix.model |
"" |
Active model (mirror). Synced with the per-provider settings; validated against the selected provider |
explainix.insertMode |
"preview" |
preview (review before insert) or direct |
explainix.streaming |
true |
Stream responses where supported |
explainix.temperature |
0.3 |
Sampling temperature |
explainix.maxRetries |
2 |
Retries for transient failures |
explainix.retryBaseDelayMs |
500 |
Exponential backoff base delay |
explainix.outputMaxTokens |
3072 |
Max completion tokens |
explainix.openai.baseUrl / .model / .requestTimeoutMs |
OpenAI defaults |
OpenAI-compatible endpoint settings |
explainix.zai.baseUrl / .model / .requestTimeoutMs |
Coding Plan defaults |
Z.AI GLM Coding Plan settings |
explainix.openrouter.baseUrl / .model / .requestTimeoutMs |
https://openrouter.ai/api/v1 / "" / 120000 |
OpenRouter settings (model picked from the live catalog) |
explainix.codexCli.path / .args / .model / .requestTimeoutMs |
Codex defaults |
Codex CLI integration (model discovered from $CODEX_HOME/models_cache.json) |
explainix.context.includeFileContext |
true |
Include imports + surrounding file code |
explainix.context.includeRelatedFiles |
true |
Look up unresolved symbols in the workspace |
explainix.context.maxRelatedDefinitions |
6 |
Max related definitions retrieved |
explainix.context.maxContextChars |
12000 |
Total context character budget |
explainix.context.maxDefinitionLines |
40 |
Max lines per related definition |
explainix.selection.maxSelectionLines |
800 |
Larger selections are truncated safely |
explainix.selection.maxSelectionChars |
24000 |
Character cap for selections |
explainix.comments.docStyle |
"auto" |
auto / line / doc |
explainix.comments.fallbackLinePrefix |
"//" |
Prefix for unregistered languages |
explainix.privacy.excludedGlobs |
see above |
Files never sent to the provider |
explainix.project.maxFiles / .maxTreeEntries / .maxFilePreviewLines |
400 / 250 / 60 |
Explain Project scan limits |
explainix.statusBar.show |
true |
Show the status-bar language item |
explainix.logLevel |
"info" |
Output channel verbosity |
🧪 Development
Requirements: Node.js ≥ 18, npm ≥ 9.
npm install # install dependencies
npm run compile # esbuild dev bundle → dist/extension.js
npm run watch # rebuild on change
npm run lint # strict TypeScript check (no emit)
npm run test:unit # build + run mocha unit tests
npm run test:integration # run tests inside a real VS Code instance
npm test # unit + integration
Unit tests cover: code-kind detection, comment formatting for every supported language (including Persian text and indentation), markdown/AI-response cleanup, prompt construction (fa/en × 4 depths), provider auth/error paths against a fake HTTP server, SSE streaming, cancellation, timeouts, retries, and Retry-After handling.
Integration tests run the real VS Code workflow: command registration, keybinding behavior, selection handling, Persian and English comment insertion, duplicate detection, undo, document-change revalidation, and workspace context retrieval — verifying that generated comments never alter executable code.
Build & package
npm run package # production bundle + vsce package → explainix-1.2.4.vsix
Install the artifact:
code --install-extension explainix-1.2.4.vsix
🛠️ Troubleshooting
| Problem |
Fix |
| "No API credential is configured" |
Run Explainix: Set API Key and pick the provider you use. |
| HTTP 401/403 |
The key is wrong or lacks access to the configured model. Re-set the key; check openai.model / zai.model. |
| HTTP 429 |
Rate limited. Explainix retries automatically with backoff; wait or reduce usage. |
| Timeout |
Increase openai/zai/openrouter.requestTimeoutMs (or codexCli.requestTimeoutMs). |
| Codex CLI provider: "not found on PATH" |
Install @openai/codex globally and run codex login. |
| Codex model list empty |
Run any codex command once (e.g. codex login) so the CLI writes $CODEX_HOME/models_cache.json; then use ⟳ Refresh. Until then the CLI uses its default model. |
| OpenRouter: 401 "No auth credentials" |
Re-set the key with Explainix: Set API Key (provider: OpenRouter); keys start with sk-or-. |
| OpenRouter: 429 |
Rate limited per model/endpoint — pick another model or wait; Explainix retries with backoff. |
| "No OpenRouter model selected" |
Run Explainix: Select AI Model and pick one of the discovered models (OpenRouter has no hardcoded default). |
| "Z.AI network error: fetch failed" |
The request never reached the server. The error now names the real cause: DNS failure (check base URL/internet), broken IPv6 route (Explainix prefers IPv4 and retries over IPv4 automatically), refused connection or timeout (firewall/proxy blocking api.z.ai), or TLS interception (corporate proxy). A proxy is required if direct egress is blocked. |
| Codex login |
Run Explainix: Login to ChatGPT (Codex) — it starts codex login in a terminal; your browser opens for the ChatGPT subscription sign-in. Then press Ctrl+Enter again. |
| Comments inserted in the wrong language |
The language is captured per request; switch language and press Regenerate in the preview. |
| Explanation looks generic |
Increase depth to Comprehensive, and make sure context.includeRelatedFiles is on so workspace definitions are included. |
| Nothing is inserted after accept |
The file changed during generation — Explainix refuses to write into a changed document. Re-run the command. |
| Persian text looks reversed |
Comments are plain text (LTR storage, standard practice); the preview panel renders RTL correctly. |
| Extension feels stuck |
Requests run one at a time; open the Process Manager to see progress or cancel/retry, or check the output log (Explainix: Show Output Log). |
📄 License
MIT — see LICENSE.