Documentation
Sonar IDE is a real-time collaborative code editor built with Electron + React + Vite, designed for supervised coding environments, pair programming, and monitored exams. It combines the power of the Monaco Editor (the engine behind VS Code) with comprehensive activity monitoring and administrative controls.
Whether you're an administrator setting up exam sessions or a student writing code, this documentation covers everything from installation to the internal architecture.
Installation
Prerequisites
- Node.js v18.x or higher
- NPM v9.x or higher
- Git
Local Development
# Clone and install
git clone https://github.com/rkvishwa/Sonar-Code-Editor.git
cd Sonar-Code-Editor
npm install
# Start all processes (Vite + TypeScript + Electron)
npm run start
Production Build
npm run build
npm run package:win # Windows NSIS installer
npm run package:mac # macOS DMG
npm run package:linux # Linux AppImage
Configuration
Create a .env file in the project root with the following Appwrite variables:
VITE_APPWRITE_ENDPOINT=https://sgp.cloud.appwrite.io/v1
VITE_APPWRITE_PROJECT_ID=your_project_id
VITE_APPWRITE_DB_NAME=devwatch_db
VITE_APPWRITE_COLLECTION_TEAMS=teams
VITE_APPWRITE_COLLECTION_SESSIONS=sessions
VITE_APPWRITE_COLLECTION_ACTIVITY_LOGS=activityLogs
VITE_APPWRITE_COLLECTION_REPORTS=reports
NODE_ENV=development
Architecture Overview
Sonar IDE uses Electron's multi-process model. The Main Process handles native OS APIs, file system operations, and the WebSocket collaboration server. The Renderer Process runs the React-based UI. A Preload Script acts as a secure bridge between the two.
Main Process
Node.js runtime: file I/O, IPC routing, monitoring, collaboration server, static server
Preload Script
Context Bridge: exposes electronAPI safely, KeyShield input capture
Renderer Process
React + Vite UI: pages, components, contexts, hooks, and services
Electron Processes
Main Process Modules
main.ts App lifecycle, window creation, IPC routing, macOS automation permission checkipcHandlers.ts File system ops (read, write, create, delete, rename, search), native dialogs, clipboard accesscollaborationManager.ts WebSocket server (port 1234), room management, team validation, network interface detectionmonitoring.ts 15-second heartbeat timer, activity event collection, offline queue managementstaticServer.ts Express HTTP server for localhost-only preview, auto-port detection starting from 3500Preload Script
preload.ts exposes the electronAPI object via Electron's Context Bridge. This is the only way the Renderer can access file system operations,
collaboration, monitoring, clipboard, and server control — the Renderer has zero direct Node.js access.
IPC Channels
All communication between the Main and Renderer process flows through typed IPC channels via the Context Bridge. Here is the complete channel reference:
File System
fs:readDirectory Recursively read folder structure (excludes dotfiles, node_modules)fs:readFile Read text file (detects binary via NULL byte scan in first 8KB)fs:readFileBase64 Read file as Base64 (for images and binary display)fs:writeFile Write/overwrite file content (auto-creates parent dirs)fs:createFile Create an empty filefs:createFolder Create a new directoryfs:deleteItem Delete file or folder recursively (idempotent)fs:renameItem Rename with case-only rename support via temp file (Windows fix)fs:search Full-text substring search across workspace filesfs:openFolderDialog Native OS folder picker dialogfs:openFileDialog Native OS file picker dialogMonitoring
monitoring:start Begin activity tracking with team credentialsmonitoring:stop End tracking, send final offline heartbeatmonitoring:heartbeat Main→Renderer: 15-second periodic activity syncmonitoring:flushQueue Main→Renderer: Flush offline log queue on reconnectmonitoring:setCurrentFile Renderer→Main: Update currently active file pathCollaboration
collaboration:startHost Launch WebSocket server on port 1234, become hostcollaboration:joinSession Connect to host IP, validates team ID matchcollaboration:stopSession Close WebSocket, clean up Yjs doc and providerscollaboration:getStatus Query current session state (active, mode, users)collaboration:getLocalIp Get LAN IP (prefers physical NICs over virtual)collaboration:getNetworkInterfaces List all available network adapterscollaboration:statusChange Main→Renderer: Connection status broadcastsServer, Network & System
server:start Start HTTP preview server for selected workspaceserver:stop Stop preview serverserver:getUrl Get current server URL (localhost:port)network:status Main→Renderer: Real-time connectivity updatesnetwork:getStatus On-demand network check (HTTP to Appwrite endpoint)clipboard:readText Read current clipboard contentssystem:getActiveWindow macOS: Get focused application titlesystem:checkPermission Check macOS Automation permission statusCode Editor
Powered by the exact Monaco Editor engine from VS Code, Sonar supports 100+ programming languages with full syntax highlighting, IntelliSense, auto-closing brackets, and code formatting.
Editor Features
- Multi-tab file editing with visual tab bar
- Auto-save with configurable 500ms debounce
- Toggleable word wrap and minimap
- JetBrains Mono font with ligatures
- Smooth scrolling and cursor blinking
- Auto-closing brackets, quotes, and HTML tags
Supported Languages
Note: In exam mode, quick suggestions, snippet completions, and parameter hints are intentionally disabled to prevent over-reliance on autocomplete.
File Tree & Workspace
The File Tree provides full workspace management with right-click context menus, inline rename, and keyboard shortcuts.
Ctrl+Alt+N — Create new fileCtrl+Alt+Shift+N — Create new folderCtrl+Z — Restore last deleted item- Recursive folder expansion with type-specific file icons
- Right-click context menu for create, delete, and rename operations
- Inline rename with double-click (Enter to commit, Esc to cancel)
- Binary file detection — images displayed in a preview tab
- Platform-aware indentation (Windows: 16px, macOS: 28px)
- Global undo restores the last deleted file from an internal trash buffer
- KeyShield captures input at the window level to prevent React focus conflicts
Live Collaboration
Google Docs-style real-time code collaboration powered by Yjs (CRDT) and y-monaco bindings. All changes are synchronized automatically with conflict-free resolution — no manual merging required.
How It Works
1. Host starts session — Launches a WebSocket server on port 1234, broadcasts their LAN IP.
2. Client joins — Enters host IP address, connects to ws://hostIp:1234.
3. Team validation — Server verifies the joining client's team ID matches the host's. Mismatches are rejected with WebSocket close code 1008.
4. Workspace sync — Host broadcasts full workspace metadata (folder structure + file contents). Client creates local copies.
5. Live editing — Every keystroke synced via Yjs CRDT. Shared cursors show each user's position with a unique color and name label.
Cursor Colors
Network Interface Selection
Sonar automatically prefers physical network adapters (Ethernet/Wi-Fi) over virtual ones.
Virtual adapters from Hyper-V, WSL, Docker, Tailscale, Hamachi, and VPN tunnels are deprioritized.
If no physical adapter exists, a virtual adapter IP is used as fallback, with 127.0.0.1 as last resort.
Activity Monitoring
The monitoring system operates through a dual-layer architecture: the Main Process sends heartbeats every 15 seconds, while the Renderer tracks local activity events and attaches them to each heartbeat before syncing to Appwrite.
Tracked Events
status_online / status_offline Network connectivity transitions (HTTP-verified against Appwrite endpoint)app_focus / app_blur Window focus state changes — detects when user leaves the IDEclipboard_copy Copy events within the editorclipboard_paste_external Paste from external source (clipboard content doesn't match last in-IDE copy)Active window title OS-level detection of which app the user is currently in (macOS: osascript, Windows: Win32 API)Current file path Which file the user has open in the editor at each heartbeatHeartbeat Payload
Every 15 seconds, the main process sends a heartbeat to the renderer containing:
- Team name and ID
- Current window title and active file path
- Online/offline status with ISO 8601 timestamp
- Extracted application name from window title
- Accumulated local activity events since last heartbeat
Offline Resilience
If the network is unavailable, heartbeats are queued in localStorage under sonar_offline_queue. On reconnect, all queued items are merged into a single
activity log row with an offline period summary (timestamps, duration, apps/files accessed while offline).
Admin Dashboard
Users with role: 'admin' are routed to a dedicated monitoring dashboard
with real-time visibility into all active teams and their activity.
Real-time Monitoring
- Live team list with online/offline status
- Last seen timestamp and current window/file
- Heartbeat stale-check every 5 seconds (30s timeout)
- Realtime Appwrite subscriptions with 30s full-sync fallback
Activity Metrics
- Total heartbeats, unique apps, files, and windows
- Online/offline duration tracking
- Clipboard copy count and external paste detection
- App blur events (suspected app switches)
Dashboard Views
- Table mode (compact, columnar) and Grid mode (card-based)
- Sort by: Team Name, Status, or Last Seen
- Filter by: All, Online Only, or Offline Only
- Case-insensitive search by team name
PDF Report Generation
- Per-team detailed reports via jsPDF
- Summary: total time, online %, disconnections, app switches
- Online/offline timeline with durations
- Suspicious app detection (browsers, chat, AI tools)
Global Dashboard Insights
- Online/offline user count with percentage breakdown
- Top 5 most-accessed external applications
- Recently active teams (within last 5 minutes)
- Estimated average session duration
Local Preview
The integrated preview panel embeds a <webview> restricted to localhost-only URLs. All non-localhost navigation is silently blocked,
preventing exam candidates from accessing external websites.
Navigation Controls
- Embedded Express server starts from port 3500 (auto-finds free port)
- Serves static files from workspace with no-cache headers
- Follow File mode: auto-navigates to the active
.htmlfile - Hot reload: refreshes preview on every file save (toggleable)
- Console capture: intercepts log, warn, error from the loaded page (last 500 entries)
- Inspector button opens DevTools for the webview
- Supports: HTML, CSS, JS, images, fonts, media, PDFs
Search
Full-text search across the entire workspace with 400ms debounce. Results are grouped by file, with click-to-navigate jumping directly to the matching line in the editor.
- Match Case (Aa) — Toggle case-sensitive matching
- Whole Word (ab) — Match only complete words using regex word boundaries
- Results show file path, line number, and highlighted text preview
- Expandable file groups for navigating large result sets
- Skips binary files, node_modules, and dotfiles automatically
Settings
The settings modal provides six tabs for customizing the IDE experience. All settings persist
to localStorage (prefixed with ide-).
Text Editor
Auto-Save (500ms debounce), Hot Reload (refresh preview on save), Word Wrap toggle
Appearance
Theme: Light, Dark, or System (respects OS preference on load)
Collaboration
Show collaborator usernames toggle, username opacity slider (0-100%)
Account
View team name, list team members (student IDs), add members (max 5)
Activity Log
View event timeline, export as color-coded PDF with suspicious activity flags
Security
Change team password (requires current password verification)
Security Model
Sonar enforces multiple layers of security to maintain academic integrity during exams.
Team-Based Authentication
Users authenticate with Team Name + Password via Appwrite. Offline fallback uses locally cached credentials with a simple hash. Role-based routing sends admin users to the dashboard and team users to the IDE.
macOS Automation Permission
On macOS, Sonar requires Automation/System Events permission at startup to monitor application switching. The app blocks until this permission is granted, preventing unmonitored exam sessions.
Input Sanitization
File names reject characters <>:"|?* and reserved names (., ..). Path traversal is prevented by normalizing and validating all paths stay within the workspace root.
Preview Lockdown
The <webview> element intercepts all navigation requests and
validates them against a strict localhost-only policy:
- Only
localhost:*and127.0.0.1:*URLs are permitted - Non-localhost URLs are silently ignored (redirected to server root)
- URL bar input auto-prepends
http://for bare localhost entries - All responses include
Cache-Control: no-cacheheaders
This ensures exam candidates cannot browse the web, access external APIs, or open any online resources from within the IDE.
File System Sandbox
The Renderer process has zero direct access to the file system. All operations go through the Context Bridge → IPC → Main Process pipeline:
- Binary files detected by scanning first 8KB for NULL bytes — prevents garbled data in the editor
- File operations are idempotent: delete/rename treat "already done" as success (collaboration race-condition safety)
- Parent directories are auto-created when writing files (prevents errors during workspace sync)
- Dotfiles (
.git,.env) andnode_modulesare excluded from directory listings - Case-only renames on Windows use a two-step temp-file strategy
Tech Stack
Frontend (Renderer)
- react ^18.2.0
- @monaco-editor/react ^4.6.0
- yjs ^13.6.29
- y-monaco ^0.1.6
- y-websocket ^3.0.0
- react-router-dom ^6.22.0
- react-resizable-panels ^2.0.19
- lucide-react ^0.577.0
- appwrite ^16.0.0
- jspdf ^2.5.1
Desktop & Build
- electron ^28.3.3
- electron-builder ^24.9.1
- electron-store ^8.1.0
- ws ^8.19.0
- typescript ^5.3.3
- vite ^5.0.11
- @vitejs/plugin-react ^4.2.1
- concurrently ^8.2.2
Changelog
- Real-time collaborative code editing powered by Monaco Editor and Yjs
- Secure Admin dashboard for user monitoring and activity tracking
- Custom File Tree navigation and multi-document tabs handling
- Integrated Preview Panel restricted to localhost domains only
- Context Bridge secure IPC between Main and Renderer processes
- Appwrite authentication and cloud synchronization integration
- Offline behavior logging with PDF generation via jsPDF
- WebSocket-based P2P file sharing and workspace synchronization
- Activity event tracking: online/offline, app focus/blur, clipboard operations
- Support for 100+ programming languages via Monaco Editor
- Cross-platform compatibility: Windows, macOS, Linux with native installers
Reporting Security Vulnerabilities
Security issues should not be reported as public GitHub issues.
Please email hello@brainvave.com with a detailed disclosure.
See SECURITY.md for the full policy.