Skip to content

IPC lifecycle

Source of truth: src/shared/ipc-contract.ts. It must not import zod or electron, because the preload runs sandboxed and may only require('electron').

Window hardening

src/main/window/create-main-window.ts: contextIsolation: true, nodeIntegration: false, sandbox: true, webSecurity: true. will-navigate is blocked (except the dev server origin) and window.open only forwards http(s) URLs to shell.openExternal.

Request/response (invoke)

React hook ──► window.api.<domain>.<method>() (preload, typed by BakaSubApi)
──► ipcRenderer.invoke(channel, payload) (channel checked against INVOKE_CHANNELS)
──► ipcMain.handle ── createHandler
1. isTrustedSender(event.senderFrame.url) dev: ELECTRON_RENDERER_URL prefix, prod: file://
2. options.input.safeParse(raw) Zod; INVALID_INPUT on failure
3. options.handle(payload, event)
4. envelope: { ok: true, data } | { ok: false, error: { code, message } }
──► unwrap() in the renderer throws IpcCallError ──► TanStack Query error state
  • AppError (see src/main/errors.ts) is mapped to its stable code; any other exception becomes INTERNAL and is logged with the ipc scope.
  • The renderer never receives the Electron event object nor ipcRenderer.

Push events (main → renderer)

emitToRenderers(channel, payload) (src/main/ipc/events.ts) sends to every live window. The preload exposes window.api.events.on(channel, listener), which validates the channel against EVENT_CHANNELS and returns an unsubscribe function. Channels: sidecars:progress, app:update-state, jobs:progress, logs:entry and app:navigate (a click on a native notification, see notifications.md).

Adding a channel

  1. Add the entry to IpcInvokeContract (or IpcEventContract) and to the matching allowlist array.
  2. Add the method to BakaSubApi and wire it in src/preload/index.ts.
  3. Create or extend a file in src/main/ipc/handlers/ calling createHandler(channel, { input?, handle }), and register it in src/main/ipc/register.ts.
  4. Consume it from a hook in src/renderer/src/hooks/ using unwrap().

Current channels

Channel Request Response
app:get-info none AppInfo
app:check-update none AppUpdateInfo
sidecars:check none SidecarReport
sidecars:install { tools: string[] } SidecarInstallResult
sidecars:cancel none { cancelled: boolean }
memory:stats none MemoryStats
memory:prune { olderThanDays: 1 | 3 | 7 | 30 | 'all' } MemoryPruneResult (deleted + stats after the prune)
settings:set-api-key { apiKey: string } (8–512 printable ASCII, trimmed) ApiKeyStatus (write-only: the key is never returned; checked in GET /key first: LLM_AUTH, NETWORK)
settings:clear-api-key none ApiKeyStatus
settings:get none PublicSettings (only public keys; see database.md)
settings:update Partial<PublicSettings> PublicSettings; INVALID_INPUT, SETTINGS_CONFLICT, PRESET_NOT_FOUND
settings:reset { keys: (keyof PublicSettings)[] } PublicSettings (factory defaults for those keys, same rules as settings:update)
logs:tail / logs:watch / logs:open-folder / logs:export / logs:report see logging.md
settings:set-tmdb-key / settings:clear-tmdb-key / settings:tmdb-key-status, media:identify / media:search / media:lookup, app:open-external see media-context.md
settings:api-key-status none ApiKeyStatus ({ present, protection: 'os' | 'none' })
presets:list / presets:create / presets:update / presets:duplicate / presets:delete PresetInput / { id, preset } / { id, name? } / { id } Preset[] / Preset / { deleted: true } (built-ins are read-only)
presets:export { ids } { path | null, count } (native save dialog)
presets:import { onConflict?: 'rename' | 'skip' } PresetImportResult (native open dialog; imported, skipped)
models:free-quota — FreeQuotaStatus (free-model daily quota, GET /key cached 30 s; see rate-limits.md)
models:list { force?: boolean } ModelList (catalog, 24 h cache, offline flag)
media:probe { path } (revalidated) MediaProbe (subtitle tracks, attachments)
dialog:open-files { kind: 'media' | 'subtitle' | 'any', multiple? } { paths } (validated; [] if cancelled)
dialog:choose-output-dir none { path | null }
jobs:create JobCreateRequest (see jobs.md); pipeline options.outputMode: 'mux' | 'subtitle' | 'both', extract options.naming, options.overwrite Job (queued; runs asynchronously)
jobs:list / jobs:get none / { id } Job[] / Job
jobs:cancel / jobs:retry { id } Job
jobs:remove { id } { removed: true } (terminal jobs only)
jobs:clear-completed — { removed: string[] } (completed, completed-with-warnings, cancelled)
jobs:confirm { id } Job (awaiting-confirmation → queued)
jobs:dismiss-consistency { id } Job (terminal job with result.consistency; sets result.consistencyDismissed, preset untouched)
files:inspect { path } (revalidated: absolute, .srt/.ass/.ssa/.vtt, ≤ 50 MB) SubtitleInspection: file, format, encoding { name, confidence: certain|high|medium|low, score, bom, eol }, diagnostics { items, totals, truncated }, coverage: CoverageReport. No job, no LLM cost (see parsing.md)
jobs:preflight { id } { estimate, coverage: CoverageReport, prompt?: PromptSummary } | null (typed mirror in the contract)
dialog:open-folder none { path | null } (batch source folder)
batches:plan BatchPlanRequest (kind, folder or files); kind: 'mux' → BatchMuxPlanRequest BatchPlan (items, tracks, selection, skipped, rejected); BatchMuxPlan for mux (items: { video, subtitles[] }, unmatchedVideos, unmatchedSubtitles, rejected, truncated)
batches:create BatchCreateRequest (same options.outputMode / extractNaming / overwrite as jobs; items, groups = works with their media and settings; mux items = { video, subtitles[] }, no groups) Batch (atomic: batch + all jobs)
batches:list / batches:get / batches:jobs none / { id } / { id } Batch[] / Batch / Job[]
batches:cancel / batches:remove { id } Batch / { removed: true }
batches:confirm { id } Batch (confirms every waiting job)
event jobs:progress n/a JobProgressEvent ({ id, status, progress }, 250 ms throttle)
event logs:entry n/a LogEntry[] (batches every 250 ms, only while logs:watch is on)
event app:update-state n/a AppUpdateStatus (every updater transition; downloading throttled to 250 ms)
event sidecars:progress n/a SidecarProgress
event app:navigate n/a NavigationTarget (job, batch or Settings → About; the window is already shown and focused)

Error codes

NETWORK, INVALID_MANIFEST, CHECKSUM_MISMATCH, EXTRACT_FAILED, PROBE_FAILED, PROCESS_TIMEOUT, UNSUPPORTED_PLATFORM, SIDECAR_BUSY, SIDECAR_MISSING, UNKNOWN_TOOL, CANCELLED, MEMORY_BUSY (prune while a job is running), LLM_AUTH, LLM_CREDITS, LLM_BAD_REQUEST, LLM_UNAVAILABLE, LLM_UNKNOWN_MODEL, LLM_TOO_MANY_FAILURES (translation layer, see llm.md), INVALID_PATH, DISK_FULL, INVALID_INPUT, INVALID_SUBTITLE, MEDIA_TOOL_FAILED, PRESET_NOT_FOUND, PRESET_NAME_TAKEN, PRESET_IN_USE, PRESET_READ_ONLY, MODEL_NOT_SET, TARGET_LANG_NOT_SET, SETTINGS_CONFLICT, TMDB_AUTH, TMDB_KEY_MISSING, URL_NOT_ALLOWED, UPDATE_UNSUPPORTED, UPDATE_NOT_READY, UPDATE_JOBS_ACTIVE (auto-update, see below), INVALID_PRESET_FILE, JOB_NOT_FOUND, JOB_INVALID_STATE, BATCH_NOT_FOUND (jobs, see jobs.md), plus FORBIDDEN, INVALID_INPUT, INTERNAL from createHandler.

Auto-update contract (frozen)

Types live in src/shared/ipc-contract.ts; the service is src/main/services/app-updater.ts.

States (AppUpdateState): idle | checking | available | not-available | downloading | downloaded | error | unsupported.

interface AppUpdateStatus {
state: AppUpdateState
current: string
latest?: string // from `available` on
publishedAt?: string // ISO 8601
notes?: string // GitHub release body as HTML, max 20k chars; UNTRUSTED, sanitize before rendering
size?: number // bytes
progress?: { percent; transferred; total; bytesPerSecond } // only `downloading`
error?: { code; message } // only `error`; code is `NETWORK` (offline: true) or `INTERNAL`
offline?: boolean
fallbackUrl?: string // only `unsupported`; passes `isAllowedExternalUrl`
}

Transitions: idle → checking → available | not-available | error; available → downloading → downloaded | error; downloading → available on cancel; error is not terminal (a new check works). unsupported is permanent for the process (dev build, Linux outside an AppImage, macOS) and never touches the network or logs an error.

Rules the UI can rely on:

  • Nothing is downloaded without app:download-update and nothing is installed without app:install-update. quitAndInstall exists only inside app:install-update; a normal quit never installs.
  • app:check-update is a no-op in downloading/downloaded/unsupported (returns the current info) and coalesces concurrent calls.
  • app:install-update with running jobs: UPDATE_JOBS_ACTIVE unless confirmJobs: true. With confirmation the Main aborts jobs (marked interrupted, re-queued on the next boot), disposes sidecars/Job Memory/DB through the ShutdownCoordinator, then installs and relaunches.
  • A silent automatic check runs once ~30 s after boot when updates.autoCheck (default true) is on. It only emits app:update-state; it never downloads.
  • AppUpdateInfo (from app:check-update) keeps its old fields (current, latest, updateAvailable, publishedAt, offline) and adds optional notes, size, state, fallbackUrl, error.