main-ipc
Skill9 starsChanged 5 days agoMITView on GitHub
IPC patterns between the Electron main process and the renderer (typed contract in src/shared/types/<domain>.ts, runtime channel spec in src/shared/ipcSpec.ts, ipcMain handlers in src/main/ipc, generated contextBridge in src/preload, consumption in the store). Use when creating or reviewing any capability that crosses main ↔ renderer, a new IPC channel, or an event sent from main to the window.
In this repository17 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- app-testingSkill
- claude-panelSkill
- commands-settingsSkill
- containersSkill
- debuggerSkill
- files-git-searchSkill
- i18nSkill
- lspSkill
- main-processesSkill
- packaging-releaseSkill
- renderer-componentsSkill
- renderer-editorSkill
- renderer-storeSkill
- renderer-stylesSkill
- renderer-terminalSkill
- workspacesSkill
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
Every new capability crosses 4 steps, in this order: contract → spec entry → handler → usage.
- Very specific: line 23
Add data types and the method to the domain file's <Domain>Api interface (types/git.ts → GitApi).
- Very specific: line 70
Not in the spec (assembled by hand in preload/index.ts because they are not channels): platform, isPackaged, homeDir, locale (from …
- Very specific: line 95
Never call ipcMain.handle/on or wc.send('…') directly: use handle / on from ipc/typed.ts and send(wc, channel, …payload) from …
- Distinctive: line 201
Never change an existing channel between shapes without migrating every caller in the same change.
- Very specific: line 226
Never load remote content in the window.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Main ↔ Renderer IPC
The renderer runs with contextIsolation: true, sandbox: true and nodeIntegration: false. Everything that needs Node
goes through window.api, typed as WalphApi in src/shared/types/index.ts (composed of each domain's <Domain>Api). Never relax these options.
Rules
- Every new capability crosses 4 steps, in this order: contract → spec entry → handler → usage. The preload is never edited by hand: it is generated from the spec.
- Channel names are
domain:action(fs:readDir,git:stage,terminal:data). - The preload only forwards calls (
buildApi(ipcSpec, ipcRenderer)). Zero logic. - Errors are thrown in main with a translated message (
throw new UserError(t().<domain>.<key>(…)),i18nskill) and shown in the UI withattempt(fn, { format })(renderer/src/attempt.ts, built onnotify(errorMessage(err))). - Non-trivial logic (parsers, mappers) lives in a pure module next to the handler, with tests.
1. Contract — src/shared/types/<domain>.ts
Add data types and the method to the domain file's <Domain>Api interface (types/git.ts → GitApi); types/index.ts
re-exports every type and composes WalphApi, so imports stay @shared/types. A new domain = new file + a member in
WalphApi + a re-export in index.ts. Document units and conventions in comments
(absolute path, 1-based line, UTF-16 offset…).
export interface GitBranch {
name: string
/** true for the branch currently checked out */
current: boolean
remote: boolean
}
// types/git.ts
export interface GitApi {
branches(root: string): Promise<GitBranch[]>
}
// types/index.ts
export interface WalphApi {
git: GitApi
}2. Spec entry — src/shared/ipcSpec.ts
ipcSpec is the ONE runtime description of the IPC: it mirrors the WalphApi tree (git: { branches: invoke('git:branches') })
and each method declares its kind and channel. Kinds: invoke(channel) (renderer → main with a reply; the contract
method returns a Promise), send(channel) (renderer → main, fire-and-forget; returns void) and event(channel)
(main → renderer; the contract method is onXxx(cb) returning the unsubscribe). Channel names are domain:action and may
differ from the method name (window.run → window:action, showContextMenu → *:contextMenu, onChange →
*:changed): the spec just records them.
// shared/ipcSpec.ts
git: { branches: invoke('git:branches'), cancelClone: send('git:cancelClone'), onCloneProgress: event('git:cloneProgress') }Everything else is derived, nothing is retyped:
IpcSpec(mapped type overWalphApi) is the shape the spec must satisfy (satisfies IpcSpec): a contract method missing from the spec, an extra entry, or the wrong kind for the signature (invokeon a method that returnsvoid,sendon anonXxx…) failspnpm typecheck.src/shared/ipc.tsderivesIpcInvoke({ args, result }),IpcSend(args) andIpcEvents(listener args) from the spec + the<Domain>Apisignatures, plusIPC_CHANNELS(invoke/send/eventlists, used bymain/ipc/registry.test.ts). Handlers get them throughhandle/on(ipc/typed.ts) andsend(window/send.ts). Handler args stayunknown(validate withassert*/parse*); the helpers only check channel name, arity and return type.- Not in the spec (assembled by hand in
preload/index.tsbecause they are not channels):platform,isPackaged,homeDir,locale(fromprocess/argv) andfiles.pathForFile(webUtils). Another member like these needs the name added toPreloadOnlyinipcSpec.tsand the code in the preload. ipcSpec.test.tsfails on a channel declared twice or not shapeddomain:action.ipcSpec.tsimports noelectron.
3. Handler — src/main/ipc/<domain>.ts
One file per domain exporting register<Domain>Handlers(), called from src/main/index.ts. The file is wiring
only: channel names, argument validation and delegation. State, services and processes live in src/main/<domain>/
(git/ops/*.ts, settings/service.ts, recent/store.ts, terminal/create.ts, window/closeController.ts…) so they
are testable without ipcMain. Domain modules import each other directly (settings/state, never ipc/settings);
nothing outside ipc/**, index.ts and menu.ts imports ipc/*, and an ipc/<domain>.ts imports no sibling
ipc/*.ts except ./typed (no-restricted-imports in eslint.config.mjs, tests exempt). What two domains share
(claude/registry.ts, lsp/registry.ts…) lives in the domain; a domain that pushes an event to a view imports send
from window/send.ts, never from ipc/.
import { handle, on } from './typed' // typed wrappers over ipcMain.handle / ipcMain.on
import { send } from '../window/send' // typed webContents.send (IpcEvents)
export function registerGitHandlers(): void {
handle('git:branches', (e, root: unknown) => branches(ownRoot(e.sender, root)))
}Never call ipcMain.handle/on or wc.send('…') directly: use handle / on from ipc/typed.ts and send(wc, channel, …payload) from
window/send.ts (handle/on call ipcMain underneath and send calls wc.send, so tests that mock electron keep working).
| Pattern | Use for | main | spec (preload is generated) |
| Request/response | Anything that returns a value or can fail | handle | invoke('d:a') |
| Fire-and-forget | High-frequency input (terminal keystrokes, resize) | on | send('d:a') |
| Event main → renderer | Streams (pty output, watcher changes) | send(e.sender, channel, …) | event('d:a') |
- Send events to the requesting
webContents(e.sender), never broadcast to every window.sendalready returns early on a destroyed view: never wrap it inif (!wc.isDestroyed())(keep a guard only when it also protects other work, such as reading per-view state). - Per-view resources (pty, watchers, LSP servers, git/docker processes) are released with
onViewReset(sender, '<key>', cb)fromwindow/viewLifecycle.ts(fires ondid-navigate,render-process-goneanddestroyed; idempotent per key;viewEpoch(wc)lets an async handler detect a reset in the middle). Anything that only dies with the view (a per-view map entry, an unsubscribe, a last flush) usesonViewDestroyed(wc, '<key>', cb)from the same module: runs once ondestroyedonly (not on reload or renderer crash), idempotent per key, errors isolated. Never writewc.once('destroyed', …)by hand. - Listener sets of the main process (
onSettingsChange,onRecentChange,onWorkspaceEvent…) arecreateEmitter<[Args]>('scope')fromutil/emitter.ts:onreturns the unsubscribe andemitisolates listener errors. Never keep anew Set<(…) => void>()of callbacks by hand. - Main logs through
createLog('scope')fromlog.ts(warn/error);consoleis lint-banned insrc/mainoutsidelog.tsand tests. - Native dialogs go through
window/nativeUi.ts:showMessageBoxFor,showOpenDialogFor,showSaveDialogFor,confirmDestructive(Enter/Esc cancel),pickFolder,popupChoice; neverdialog.show*orwindowOfin a handler. A dialog on behalf of a view without a window is not shown (resolves as cancelled); onlywcnull (app-level, macOS without a window) shows a parentless dialog.
4. Bridge — generated, src/preload/buildApi.ts
buildApi(ipcSpec, ipcRenderer) walks the spec and turns each entry into ipcRenderer.invoke / send / on (the
event wrapper drops the Electron event, passes only the payload and returns the unsubscribe). preload/index.ts spreads
its result, adds the hand-made members above and calls contextBridge.exposeInMainWorld. Nothing to write here for a new
capability. It forwards ALL arguments (no fixed arity): never pass an API method point-free (onClick={api.x}), the
SyntheticEvent would cross IPC. The preload imports only electron, ./buildApi and @shared (types, plus the @shared/ipcSpec runtime
value): the lint rule is in eslint.config.mjs, and electron-vite bundles the shared code into out/preload/index.js,
whose only require must stay electron (a sandboxed preload cannot require anything else). buildApi.ts takes the
ipc object as a parameter (RendererIpc) so buildApi.test.ts can use a fake.
5. Usage — renderer
Calls live in actions exported from the modules beside store.ts (gitActions.ts, tabActions.ts…) (or in the component that owns the feature), always handling errors:
// ✅ CORRECT
export async function loadBranches(): Promise<void> {
const { root } = get()
if (!root) return
try {
const branches = await api.git.branches(root)
if (get().root === root) set({ branches }) // workspace may have changed meanwhile
} catch (err) {
notify(`Git: ${errorMessage(err)}`)
}
}
// ❌ WRONG — unhandled rejection, no user feedback, stale write after workspace switch
useEffect(() => { window.api.git.branches(root).then((b) => setBranches(b)) }, [])Event subscriptions inside useEffect must return the unsubscribe in the cleanup.
Validating untrusted values
Anything from the renderer, disk, a language server or the Claude SDK is unknown until checked. Use the shared guards
(@shared/guards), never a local copy: isRecord (plain object, arrays and null rejected), isNonEmptyString,
isFiniteNumber (no NaN/Infinity). Single-line display text from those sources goes through @shared/controlChars
(flattenControl, stripControl, stripAnsi, hasControl); a regex with control characters is never written inline
(no-control-regex is disabled only inside that module).
Arguments: absolute paths are validated with isAbsolutePathInput (silent drop) or parseAbsolutePath(value, message?)
(fs/validate.ts; NUL check, returns resolved), the rest with the combinators in validate/args.ts (int, oneOf,
bool, record), which throw the translated message the caller passes. Never write
typeof x !== 'string' || !isAbsolute(x) or Number.isInteger checks inline.
Error convention
Four shapes coexist on purpose. Pick by what the renderer must do with the failure:
| Shape | When | Example |
throw new UserError(t().<domain>.<key>) (default) | The operation failed and the user only needs to read why. The renderer shows it with attempt (notify(errorMessage(err))) and never parses the text. | git.commit, fs.rename, docker.list |
Result union { ok: true; … } | { ok: false; reason?; message/error } | The failure is an expected state the UI renders or branches on (not a toast), or the renderer needs a code. Put the code in a literal union field (reason), never make the renderer match the message. | DockerInfo (reason: 'notInstalled' | 'daemonDown' | 'error'), CloneUrlCheck |
null / [] | "Nothing to answer" is normal, not an error: no server/capability, user cancelled a dialog, stale request superseded. | lsp.hover, cli.install (cancelled), fs.showContextMenu |
boolean ack | A request/response protocol where false means "main refused, keep your pending UI" and the renderer must recover state. Document what false means on the contract. | claude.respond |
Rules:
UserError(src/main/errors.ts) is the only error class whose message is meant for the user: every translated message (validators invalidate/args.ts,fs/validate.ts, domain errors,GitCommandError,DockerError,AlreadyExistsError,ServerResponseError…) is aUserError; a plainnew Error(t()…)is a bug. Any error that can cross IPC and carries text for the user (classified git/docker output, amessage()callback) must be aUserErrortoo. Lint enforces the common case:no-restricted-syntaxineslint.config.mjs(USER_ERROR_SYNTAX,src/main/**outside tests) rejectsnew Error(...)whose arguments callt(); text held in a variable is on you. ItsnamestaysErroron purpose (Electron serializes${name}: ${message}and the renderer'serrorMessage(lib/errors.ts) strips that prefix).- The error boundary is
handleinipc/typed.ts: aUserErrorcrosses as is; anything else (a rawENOENT, a bug) is logged withlog.error(channel, err)and replaced byUserError(t().common.unexpectedError(message)). A rejected promise is rewritten in place and the handler's own promise is returned: never chain (.catch/await) in the boundary, the extra tick makes events the handler sent arrive before the reply, and the renderer relies on reply first (e.g. a Claude question card focus). So raw fs errors must be translated before they leave the handler:describeFsError(err, path)(fs/describeFsError.ts: ENOENT/EEXIST/ENOTEMPTY/EACCES/EPERM/ENOTDIR/EISDIR, unknown codes keep the message) for reads, listings and creation,describeWriteErrorfor writes (aUserErrorpasses through both; unknown writes errno becomefiles.errors.writeFailedwith the original detail, never a raw error;shell.trashItemgoes throughfs/trashPath.ts). The renderer never inspects the text or the error name; when it needs a code use a result union. - Main may throw a coded error internally (e.g.
DockerErrorwithinfo), but it crosses IPC only as a message (Electron serializes onlymessage). If the renderer needs the code, convert to a result union at the handler. - Never change an existing channel between shapes without migrating every caller in the same change.
- Fire-and-forget channels (
IpcSend) don't report errors: invalid input is ignored (validated, then dropped).
Which folder a channel acts on
- Channels that mutate or read inside the view folder with no folder argument (
fs:createFile,fs:rename, the Claude conversation…) take the folder from main:requireViewRoot(e.sender, message?)(window/ownRoot.ts; throws aUserError, default "no folder open", the domain passes its own translated message). Never trust or echo a root from the renderer there. - Channels where the renderer names a
root(git, search, settingssetWorkspace, Claude writes that must not land in a folder the view just left) accept it only throughassertOwnRoot(wc, root, message)/ownRoot(same view folder, returns main's spelling,UserErrorotherwise). A request that sends no folder usesrequireViewRoot;getSenderRoot(windows.ts) is only for thebeforeunloadmessages that arrive while the view is closing.
Security
- Trusted sender:
handlerejects (andondrops, with alog.warn) any message whoseevent.senderFrameis not themainFrameof a workspace view. Every workspaceWebContentsViewis registered bycreateWorkspaceView(trustSenderinwindow/trustedSenders.ts) before it loads the renderer, so its preload's first message is trusted; there is no other webContents in the app that talks to main (no settings/about window, no<webview>).senderFrameisnullafter a navigation or a dead frame: untrusted. Tests that call handlers throughtesting/fakeIpc.tsget trusted events automatically; to test the rejection build the event by hand (ipc/typed.test.ts). - Names coming from the UI (create/rename) go through
assertValidName(no/,\,.,..). - Deleting always uses
shell.trashItem(reversible) — neverfs.rm. shell.openExternalonly forhttp:,https:andmailto:URLs (parsed withnew URL).- Never load remote content in the window. The CSP lives in
src/renderer/index.html. fs:writeFileis gated per view (assertWritable,fs/writeAccess.ts). It writes a path only if it is (1) inside the view folder (resolveInsideRoot, so a symlink or a dangling link that leaves the folder does not count) or (2) a file main itself read for that view:fs:readTextregisters the path after a successful read, and every file tab loads through it. The list is aPathAllowlist(fs/pathAllowlist.ts) per view (createViewPathAllowlist,window/viewPathAllowlist.ts): keyed bypathKey(shared/pathCompare.ts), pinned to the canonical path (canonicalPathinfs/paths.ts: nearest existing ancestor byrealpath, dangling links followed), so a link re-pointed after the read is rejected (writeTargetChanged); no TTL, capped at 10 000 entries, dropped on view reset and on a folder change (onWindowRootChange). A rejected path throwsfiles.errors.writeNotAllowed. Rules for new code: a native dialog that picks a path the editor will save to (a future Save As) callsallowWrite(wc, path)in main right after the dialog; a channel that hands a path to the renderer to open in a tab needs no registration (the tab'sreadTextdoes it); the renderer can never register a path itself (readFile/readImagedo not). Known limit: the renderer chooses what toreadText, so a compromised renderer can still overwrite any existing text file it can read (not create new files, write binaries or write unreadable ones); a compromised renderer already hasterminal:create. Claude edits never use this channel (the CLI writes after the permission card).session:loadreads the session file of any folder on purpose, without thematchOwnRootcheck thatsession:saveapplies: it is read-only, the argument is only hashed into a file name under<userData>/sessions/(no path escapes) and the content goes throughsanitizeSession. The renderer asks for it while entering a workspace, concurrently with the folder registration, so requiring ownership there would only add a race.- External processes: see the
main-processesskill.
Checklist
- Type in
shared/types/<domain>.ts, entry inshared/ipcSpec.ts, handler registered (and itsregister*Handlersinregistry.test.tsif new),pnpm typecheckgreen - Errors reach the user with a translated message (
t(), all three languages), in the shape of the "Error convention" table - Per-window resources released when the window closes
- Inputs from the renderer validated in main (a write channel outside the view folder goes through
assertWritable) - Pure logic extracted and tested
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

