Electron Development workflow skill. Use this skill when the user needs Master Electron desktop app development with secure IPC, contextIsolation, preload scripts, multi-process architecture, electron-builder packaging, code signing, and auto-update and the operator should preserve the upstream workflow, copied support files, and provenance before merging or handing off.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Instruções da origem · Visualização somente leitura
name
electron-development
description
Electron Development workflow skill. Use this skill when the user needs Master Electron desktop app development with secure IPC, contextIsolation, preload scripts, multi-process architecture, electron-builder packaging, code signing, and auto-update and the operator should preserve the upstream workflow, copied support files, and provenance before merging or handing off.
This public intake copy packages plugins/antigravity-awesome-skills-claude/skills/electron-development from https://github.com/sickn33/antigravity-awesome-skills into the native Omni Skills editorial shape without hiding its origin.
Use it when the operator needs the upstream workflow, support files, and repository context to stay intact while the public validator and private enhancer continue their normal downstream flow.
This intake keeps the copied upstream files intact and uses metadata.json plus ORIGIN.md as the provenance anchor for review.
Electron Development You are a senior Electron engineer specializing in secure, production-grade desktop application architecture. You have deep expertise in Electron's multi-process model, IPC security patterns, native OS integration, application packaging, code signing, and auto-update strategies.
Imported source sections that did not map cleanly to the public headings are still preserved below or in the support files. Notable imported sections: Core Expertise Areas, Application Lifecycle Management, Common Issue Diagnostics, Limitations.
When to Use This Skill
Use this section as the trigger filter. It should make the activation boundary explicit before the operator loads files, runs commands, or opens a pull request.
Building new Electron desktop applications from scratch
Securing an Electron app (contextIsolation, sandbox, CSP, nodeIntegration)
Setting up IPC communication between main, renderer, and preload processes
Packaging and distributing Electron apps with electron-builder or electron-forge
Implementing auto-update with electron-updater
Debugging main process issues or renderer crashes
Operating Table
Situation
Start here
Why it matters
First-time use
metadata.json
Confirms repository, branch, commit, and imported path before touching the copied workflow
Provenance review
ORIGIN.md
Gives reviewers a plain-language audit trail for the imported source
Workflow execution
SKILL.md
Starts with the smallest copied file that materially changes execution
Supporting context
SKILL.md
Adds the next most relevant copied source file without loading the entire package
Handoff decision
## Related Skills
Helps the operator switch to a stronger native skill when the task drifts
Workflow
This workflow is intentionally editorial and operational at the same time. It keeps the imported source useful to the operator while still satisfying the public intake standards that feed the downstream enhancer flow.
Analyze the project structure and identify process boundaries.
Separate entry points: Main, preload, and renderer each have their own build configuration.
Shared types, not shared modules: The shared/ directory contains only types, constants, and enums — never executable code imported across process boundaries.
Keep main process lean: Main should orchestrate windows, handle IPC, and manage app lifecycle. Business logic belongs in the renderer or dedicated worker processes.
2. Process Model (Main / Renderer / Preload / Utility)
Electron runs multiple processes that are isolated by design:
⚠️ CRITICAL: Never set nodeIntegration: true or contextIsolation: false in production. These settings expose the renderer to remote code execution (RCE) attacks through XSS vulnerabilities.
3. Secure IPC Communication
IPC is the only safe channel for communication between main and renderer processes. All IPC must flow through the preload script.
// src/renderer/App.tsx — or any renderer code// The electronAPI is globally available via contextBridgedeclareglobal {
interfaceWindow {
electronAPI: {
send: (channel: string, ...args: unknown[]) =>void;
invoke: (channel: string, ...args: unknown[]) =>Promise<unknown>;
on: (channel: string, callback: (...args: unknown[]) => void) =>() =>void;
};
}
}
// Open a file via IPCasyncfunctionopenFile() {
const result = awaitwindow.electronAPI.invoke('file:open');
if (result) {
console.log('File content:', result.content);
}
}
// Subscribe to updates from main processconst unsubscribe = window.electronAPI.on('update:available', (version) => {
console.log('Update available:', version);
});
// Cleanup on unmount// unsubscribe();
IPC Pattern Summary:
Pattern
Method
Use Case
Fire-and-forget
ipcRenderer.send() → ipcMain.on()
Logging, telemetry, non-critical notifications
Request/Response
ipcRenderer.invoke() → ipcMain.handle()
File operations, dialogs, data queries
Push to renderer
webContents.send() → ipcRenderer.on()
Progress updates, download status, auto-update
⚠️ Never use ipcRenderer.sendSync() in production — it blocks the renderer's event loop and freezes the UI.
4. Security Hardening
Production Security Checklist
── MANDATORY ──
[ ] contextIsolation: true
[ ] nodeIntegration: false
[ ] sandbox: true
[ ] webSecurity: true
[ ] allowRunningInsecureContent: false
── IPC ──
[ ] Preload uses contextBridge with explicit channel whitelisting
[ ] All IPC inputs are validated in the main process
[ ] No raw ipcRenderer exposed to renderer context
[ ] No use of ipcRenderer.sendSync()
── CONTENT ──
[ ] Content Security Policy (CSP) headers set on all windows
[ ] No use of eval(), new Function(), or innerHTML with untrusted data
[ ] Remote content (if any) loaded in separate BrowserView with restricted permissions
[ ] protocol.registerSchemesAsPrivileged() uses minimal permissions
── NAVIGATION ──
[ ] webContents 'will-navigate' event intercepted — block unexpected URLs
[ ] webContents 'new-window' event intercepted — prevent pop-up exploitation
[ ] No shell.openExternal() with unsanitized URLs
── PACKAGING ──
[ ] ASAR archive enabled (protects source from casual inspection)
[ ] No sensitive credentials or API keys bundled in the app
[ ] Code signing configured for both Windows and macOS
[ ] Auto-update uses HTTPS and verifies signatures
Preventing Navigation Hijacking:
// In main process, after creating a BrowserWindow
win.webContents.on('will-navigate', (event, url) => {
const parsedUrl = newURL(url);
// Only allow navigation within your appif (parsedUrl.origin !== 'http://localhost:5173') { // dev server
event.preventDefault();
console.warn(`Blocked navigation to: ${url}`);
}
});
// Prevent new windows from being opened
win.webContents.setWindowOpenHandler(({ url }) => {
try {
const externalUrl = newURL(url);
const allowedHosts = newSet(['example.com', 'docs.example.com']);
// Never forward raw renderer-controlled URLs to the OS.// Unvalidated links can enable phishing or abuse platform URL handlers.if (externalUrl.protocol === 'https:' && allowedHosts.has(externalUrl.hostname)) {
require('electron').shell.openExternal(externalUrl.toString());
} else {
console.warn(`Blocked external URL: ${url}`);
}
} catch {
console.warn(`Rejected invalid external URL: ${url}`);
}
return { action: 'deny' }; // Block all new Electron windows
});
Custom Protocol Registration (secure):
import { protocol } from'electron';
import path from'node:path';
import { readFile } from'node:fs/promises';
import { URL } from'node:url';
// Register a custom protocol for loading local assets securely
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { standard: true, secure: true, supportFetchAPI: true } },
]);
app.whenReady().then(() => {
protocol.handle('app', async (request) => {
const url = newURL(request.url);
const baseDir = path.resolve(__dirname, '../renderer');
// Strip the leading slash so path.resolve keeps baseDir as the root.const relativePath = path.normalize(decodeURIComponent(url.pathname).replace(/^[/\\]+/, ''));
const filePath = path.resolve(baseDir, relativePath);
if (!filePath.startsWith(baseDir)) {
returnnewResponse('Forbidden', { status: 403 });
}
const data = awaitreadFile(filePath);
returnnewResponse(data);
});
});
5. State Management Across Processes
Strategy 1: Main process as single source of truth (recommended for most apps)
// Main process: broadcast state changes to all windowsimport { BrowserWindow } from'electron';
functionbroadcastToAllWindows(channel: string, data: unknown): void {
for (const win ofBrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
win.webContents.send(channel, data);
}
}
}
// When theme changes:
ipcMain.handle('settings:set-theme', (_event, theme: 'light' | 'dark') => {
store.set('theme', theme);
broadcastToAllWindows('settings:theme-changed', theme);
});
6. Build, Signing & Distribution
electron-builder Configuration
# electron-builder.ymlappId:com.mycompany.myappproductName:MyAppdirectories:output:distbuildResources:resourcesfiles:-"out/**/*"# compiled main + preload-"renderer/**/*"# built renderer assets-"package.json"asar:truecompression:maximum# ── macOS ──mac:category:public.app-category.developer-toolshardenedRuntime:truegatekeeperAssess:falseentitlements:resources/entitlements.mac.plistentitlementsInherit:resources/entitlements.mac.plisttarget:-target:dmgarch: [x64, arm64]
-target:ziparch: [x64, arm64]
# ── Windows ──win:target:-target:nsisarch: [x64, arm64]
signingHashAlgorithms: [sha256]
nsis:oneClick:falseallowToChangeInstallationDirectory:trueperMachine:false# ── Linux ──linux:target:-target:AppImage-target:debcategory:Developmentmaintainer:your-email@example.com# ── Auto Update ──publish:provider:githubowner:your-orgrepo:your-repo
Code Signing
# macOS: requires Apple Developer certificate# Set environment variables before building:export CSC_LINK="path/to/Developer_ID_Application.p12"export CSC_KEY_PASSWORD="your-password"# Windows: requires EV or standard code signing certificate# Set environment variables:export WIN_CSC_LINK="path/to/code-signing.pfx"export WIN_CSC_KEY_PASSWORD="your-password"# Build signed app
npx electron-builder --mac --win --publish never
✅ Use asar: true to package sources into a single archive
✅ Set compression: maximum in electron-builder config
✅ Exclude dev dependencies: "files" pattern should only include compiled output
✅ Use a bundler (Vite, webpack, esbuild) to tree-shake the renderer
✅ Audit node_modules shipped with the app — use electron-builder's files exclude patterns
✅ Consider @electron/rebuild for native modules instead of shipping prebuilt for all platforms
❌ Do NOT bundle the entire node_modules — only production dependencies
7. Developer Experience & Debugging
Development Setup with Hot Reload
// package.json scripts{"scripts":{"dev":"concurrently \"npm run dev:renderer\" \"npm run dev:main\"","dev:renderer":"vite","dev:main":"electron-vite dev","build":"electron-vite build","start":"electron ."}}
Recommended toolchain:
electron-vite or electron-forge with Vite plugin — modern, fast HMR for renderer
tsx or ts-node — for running TypeScript in main process during development
concurrently — run renderer dev server + Electron simultaneously
Debugging the Main Process
// .vscode/launch.json{"version":"0.2.0","configurations":[{"name":"Debug Main Process","type":"node","request":"launch","cwd":"${workspaceFolder}","runtimeExecutable":"${workspaceFolder}/node_modules/.bin/electron","args":[".","--remote-debugging-port=9223"],"sourceMaps":true,"outFiles":["${workspaceFolder}/out/**/*.js"],"env":{"NODE_ENV":"development"}}]}
Other debugging techniques:
// Enable DevTools only in developmentif (process.env.NODE_ENV === 'development') {
win.webContents.openDevTools({ mode: 'detach' });
}
// Inspect specific renderer processes from command line:// electron . --inspect=5858 --remote-debugging-port=9223
Testing Strategy
Unit testing (Vitest / Jest):
// tests/unit/store.test.tsimport { describe, it, expect, vi } from'vitest';
// Mock Electron modules for unit tests
vi.mock('electron', () => ({
app: { getPath: () =>'/tmp/test' },
}));
describe('Store', () => {
it('returns default values for missing keys', () => {
// Test store logic without Electron runtime
});
});
E2E testing (Playwright + Electron):
// tests/e2e/app.spec.tsimport { test, expect, _electron as electron } from'@playwright/test';
test('app launches and shows main window', async () => {
const app = await electron.launch({ args: ['.'] });
constwindow = await app.firstWindow();
// Wait for the app to fully loadawaitwindow.waitForLoadState('domcontentloaded');
const title = awaitwindow.title();
expect(title).toBe('My App');
// Take a screenshot for visual regressionawaitwindow.screenshot({ path: 'tests/screenshots/main-window.png' });
await app.close();
});
test('file open dialog works via IPC', async () => {
const app = await electron.launch({ args: ['.'] });
constwindow = await app.firstWindow();
// Test IPC by evaluating in the renderer contextconst version = awaitwindow.evaluate(async () => {
returnwindow.electronAPI.invoke('app:get-version');
});
expect(version).toBeTruthy();
await app.close();
});
Use @electron-development to handle <task>. Start from the copied upstream workflow, load only the files that change the outcome, and keep provenance visible in the answer.
Explanation: This is the safest starting point when the operator needs the imported workflow, but not the entire repository.
Example 2: Ask for a provenance-grounded review
Review @electron-development against metadata.json and ORIGIN.md, then explain which copied upstream files you would load first and why.
Explanation: Use this before review or troubleshooting when you need a precise, auditable explanation of origin and file selection.
Example 3: Narrow the copied support files before execution
Use @electron-development for <task>. Load only the copied references, examples, or scripts that change the outcome, and name the files explicitly before proceeding.
Explanation: This keeps the skill aligned with progressive disclosure instead of loading the whole copied package by default.
Example 4: Build a reviewer packet
Review @electron-development using the copied upstream files plus provenance, then summarize any gaps before merge.
Explanation: This is useful when the PR is waiting for human review and you want a repeatable audit packet.
Best Practices
Treat the generated public skill as a reviewable packaging layer around the upstream repository. The goal is to keep provenance explicit and load only the copied source material that materially improves execution.
✅ Always set contextIsolation: true and nodeIntegration: false
✅ Always use contextBridge in preload with an explicit channel whitelist
✅ Always validate IPC inputs in the main process — treat renderer as untrusted
✅ Always use ipcMain.handle() / ipcRenderer.invoke() for request/response IPC
✅ Always sanitize URLs before passing to shell.openExternal()
✅ Always code-sign your production builds
✅ Use Playwright with @playwright/test's Electron support for E2E tests
✅ Store user data in app.getPath('userData'), never in the app directory
❌ Never set nodeIntegration: true — this is the #1 Electron security vulnerability
❌ Never expose raw ipcRenderer or require() to the renderer context
❌ Never use remote module (deprecated and insecure)
❌ Never use ipcRenderer.sendSync() — it blocks the renderer event loop
❌ Never disable webSecurity in production
❌ Never load remote/untrusted content without a strict CSP and sandboxing
Troubleshooting
Problem: The operator skipped the imported context and answered too generically
Symptoms: The result ignores the upstream workflow in plugins/antigravity-awesome-skills-claude/skills/electron-development, fails to mention provenance, or does not use any copied source files at all.
Solution: Re-open metadata.json, ORIGIN.md, and the most relevant copied upstream files. Load only the files that materially change the answer, then restate the provenance before continuing.
Problem: The imported workflow feels incomplete during review
Symptoms: Reviewers can see the generated SKILL.md, but they cannot quickly tell which references, examples, or scripts matter for the current task.
Solution: Point at the exact copied references, examples, scripts, or assets that justify the path you took. If the gap is still real, record it in the PR instead of hiding it.
Problem: The task drifted into a different specialization
Symptoms: The imported skill starts in the right place, but the work turns into debugging, architecture, design, security, or release orchestration that a native skill handles better.
Solution: Use the related skills section to hand off deliberately. Keep the imported provenance visible so the next skill inherits the right context instead of starting blind.
Related Skills
@devops-deploy - Use when the work is better handled by that native specialization after this imported skill establishes context.
@devops-troubleshooter - Use when the work is better handled by that native specialization after this imported skill establishes context.
@differential-review - Use when the work is better handled by that native specialization after this imported skill establishes context.
@discord-automation - Use when the work is better handled by that native specialization after this imported skill establishes context.
Additional Resources
Use this support matrix and the linked files below as the operator packet for this imported skill. They should reflect real copied source material, not generic scaffolding.
Resource family
What it gives the reviewer
Example path
references
copied reference notes, guides, or background material from upstream
references/n/a
examples
worked examples or reusable prompts copied from upstream
examples/n/a
scripts
upstream helper scripts that change execution or validation
scripts/n/a
agents
routing or delegation notes that are genuinely part of the imported package
agents/n/a
assets
supporting assets or schemas copied from the source package
assets/n/a
Imported Reference Notes
Imported: Application Lifecycle Management
// src/main/main.tsimport { app, BrowserWindow } from'electron';
import { registerIpcHandlers } from'./ipc-handlers';
import { setupAutoUpdater } from'./updater';
import { store } from'./store';
letmainWindow: BrowserWindow | null = null;
app.whenReady().then(() => {
registerIpcHandlers();
mainWindow = createMainWindow();
// Restore window boundsconst bounds = store.get('windowBounds');
if (bounds) mainWindow.setBounds(bounds);
// Save window bounds on close
mainWindow.on('close', () => {
if (mainWindow) store.set('windowBounds', mainWindow.getBounds());
});
// Auto-update (only in production)if (app.isPackaged) {
setupAutoUpdater(mainWindow);
}
// macOS: re-create window when dock icon is clicked
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
mainWindow = createMainWindow();
}
});
});
// Quit when all windows are closed (except on macOS)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Security: prevent additional renderers from being created
app.on('web-contents-created', (_event, contents) => {
contents.on('will-attach-webview', (event) => {
event.preventDefault(); // Block <webview> tags
});
});
Imported: Common Issue Diagnostics
White Screen on Launch
Symptoms: App starts but renderer shows a blank/white page
Root causes: Incorrect loadFile/loadURL path, build output missing, CSP blocking scripts
Solutions: Verify the path passed to win.loadFile() or win.loadURL() exists relative to the packaged app. Check DevTools console for CSP violations. In development, ensure the Vite/webpack dev server is running before Electron starts.
IPC Messages Not Received
Symptoms: invoke() hangs or send() has no effect
Root causes: Channel name mismatch, preload not loaded, contextBridge not exposing the channel
Solutions: Verify channel names match exactly between preload, main, and renderer. Confirm preload path is correct in webPreferences. Check that the channel is in the whitelist array.
Native Module Crashes
Symptoms: App crashes on startup with MODULE_NOT_FOUND or invalid ELF headerRoot causes: Native module compiled for wrong Electron/Node ABI version
Solutions: Run npx @electron/rebuild after installing native modules. Ensure electron-builder is configured with the correct Electron version for rebuilding.
App Not Updating
Symptoms: autoUpdater.checkForUpdates() returns nothing or errors
Root causes: Missing publish config, unsigned app (macOS), incorrect GitHub release assets
Solutions: Verify publish section in electron-builder.yml. On macOS, app must be code-signed and notarized. Ensure the GitHub release contains the -mac.zip and latest-mac.yml (or equivalent Windows files).
Large Bundle Size (>200MB)
Symptoms: Built application is excessively large
Root causes: Dev dependencies bundled, no tree-shaking, duplicate Electron binaries
Solutions: Audit files patterns in electron-builder.yml. Use a bundler (Vite/esbuild) for the renderer. Check that devDependencies are not in dependencies. Use compression: maximum.
Imported: Limitations
Electron bundles Chromium + Node.js, resulting in a minimum ~150MB app size — this is a fundamental trade-off of the framework
Not suitable for apps where minimal install size is critical (consider Tauri instead)
Single-window apps are simpler to architect; multi-window state synchronization requires careful IPC design
Auto-update on Linux requires distributing via Snap, Flatpak, or custom mechanisms — electron-updater has limited Linux support
macOS notarization requires an Apple Developer account ($99/year) and is mandatory for distribution outside the Mac App Store
Debugging main process issues requires VS Code or Chrome DevTools via --inspect flag — there is no integrated debugger in Electron itself