Jobs
src/main/jobs/ runs every user action on files as a persisted job: extract tracks, translate a subtitle, mux subtitles into an MKV, or the whole pipeline. Pure Node apart from the IPC handlers; composed in create-job-module.ts.
jobs:create ──► resolveJobSpec (Zod + path guard + resolved preset snapshot) ──► jobs row (queued)JobManager (FIFO, concurrency = settings 'jobs.concurrency', default 2) └─ JobRunner.run(spec, artifacts, workDir) userData/cache/jobs/<id>/ resume at the first step whose artifact does not verify probe → extract → preflight → translate → write → mux (subset per kind) └─ status, step, progress, artifacts, result, error persisted at every transitionjobs:progress (throttled 250 ms; state transitions immediately)During the translate step progress.translation carries done/total/cached, chunk { completed, count, inFlight } and the timeline map of the episode (cached, translated, failed and in-flight ranges, plus the lane cuts; see llm.md). While every lane waits on OpenRouter (rate limit, lane cooldown after a 429, backoff), progress.waiting { reason, untilMs } is set; it is cleared when the request goes out and never kept in a terminal state. See rate-limits.md.
Kinds
kind |
Input | Steps | Output |
|---|---|---|---|
extract |
MKV + track ids | probe → extract → write | <base>.<lang|und>.<ext> (naming: 'player', default with one track; same language twice → <base>.<lang>.<n>.<ext>) or <base>.<trackId>.<lang|und>.<ext> (naming: 'track', default with several tracks) |
translate |
.srt / .ass / .ssa / .vtt |
translate → write | <base>.<targetLang>.<ext> |
mux |
MKV + 1..32 subtitles (language, name, default) | probe → validate → mux | <base>.<lang>.mkv |
pipeline |
MKV + track id | probe → extract → preflight → translate → [write] → [mux] | by outputMode (see below): <base>.<targetLang>.mkv, <base>.<targetLang>.<ext>, or both |
Pipeline output mode (options.outputMode)
outputMode |
Steps after translate |
Result |
|---|---|---|
mux (default) |
mux |
<base>.<targetLang>.mkv |
subtitle |
write |
<base>.<targetLang>.<ext> next to the video (or in outputDir); the MKV is never read again, no remux free-space check |
both |
write → mux |
both files |
- The subtitle name is
<video base>.<BCP-47 language>.<ext>(Episode.mkv→Episode.pt-BR.ass), the convention players use to auto-load external subtitles.JobResult.subtitlecarries its path (also the first entry ofoutputs). - Compatibility:
options.alsoWriteSubtitle(old requests) is deprecated: whenoutputModeis absent,true→both,false/absent →mux; an explicitoutputModewins. New specs storeoutputMode; specs persisted before it (onlyalsoWriteSubtitle) keep working:planForreads them throughpipelineOutputMode, so queued/failed jobs resume with the same steps. The renderer’s default staysmux(the last choice is remembered in Settings by the UI). jobs:retry/cancel need no special case:writeis never reused from a previous attempt, andsubtitlemode has no step that touches the MKV. Cancel removes the.partialand leaves the source and any finished output alone.- Name collisions (
extract,translate,pipelinesubtitle):(2),(3)… by default;options.overwrite: truereplaces the existing file (atomic rename), except when the target is the job’s own source file. The remuxed.mkvalways gets a unique name. extractnaming:options.naming(player|track); defaultplayerwith a single track,trackwith several (batch:options.extractNaming, applied per item). Specs persisted withoutnamingbehave astrack.
Steps (steps/*.step.ts) are shared by every kind (plan.ts):
- probe:
mkvmerge -J→ subtitle tracks (media/mkv-probe.ts). Supported:S_TEXT/UTF8,S_TEXT/ASCII,S_TEXT/ASS,S_TEXT/SSA,S_TEXT/WEBVTT. PGS/VobSub/DVB (image-based, would need OCR, out of scope) and other text codecs without a parser (no-parser, e.g. USF) are listed but rejected. Track language:language_ietf, else ISO 639-2 → BCP-47 table (media/languages.ts);und= unknown. - extract: one
mkvextractpass for all requested tracks into the work dir. - preflight: token/cost estimate and coverage; may stop the job in
awaiting-confirmation(seepreflight.md). - translate: decode → parse →
translateDocument(seellm.md) →serializeRepaired→ UTF-8 (BOM if the source had one).sourceLang: job option, else filename suffix (ep01.en.srt), else the track language. - validate (mux): each subtitle must parse; nothing is repaired. Failure →
INVALID_SUBTITLEbefore touching the MKV. - write: publishes work-dir files into the output dir (unique name, atomic copy).
- mux:
mkvmergekeeps every original track and attachment (fonts); the new track gets--language,--track-name(<Language> (BakaSub)in the pipeline) and the default flag; withsetDefaultthe original subtitle tracks lose theirs;keepOriginalSubtitles: false→--no-subtitles.
Outputs never corrupt anything
- The source is never overwritten. Name collisions get
(2),(3)… (unlessoverwriteis requested for a subtitle output). - Every final file is written as
.<name>.bakasub-partial.<ext>in the destination directory and renamed only on success (atomic on the same filesystem); failures and cancellation delete it. - Free space is checked before mux (
source + subtitles × 1.05,DISK_FULL) and before extraction (100 MB in the work dir).
mkvtoolnix (media/mkvtoolnix*.ts)
- Binaries come from the verified sidecars (
SidecarManager.resolve,SIDECAR_MISSINGif not installed) and run throughProcessRunner(abort → SIGTERM → SIGKILL after 3 s; no timeout, big files take long). --gui-mode:#GUI#progress NN%→ step progress,#GUI#warning→ job warnings,#GUI#error→ error message.ProcessRunnergainedonStdoutLinefor this.- Exit codes:
0ok,1= finished with warnings (success →completed-with-warnings),2error (MEDIA_TOOL_FAILED). - Not yet validated against the real binaries (no mkvtoolnix on the dev machine at the time): the
mkvmerge -Jfields read (codec_id,language,language_ietf,track_name,default_track,forced_track,num_index_entries) and the--gui-modeposition formkvextractmust be checked once the sidecars are installed.
States
queued → running(step) → [awaiting-confirmation] → completed | completed-with-warnings ↘ failed | cancelled | interruptedawaiting-confirmation: the preflight is waiting for the user (preflight.md); not running, the slot is free, survives restarts;jobs:confirmre-queues it,jobs:canceldiscards it.completed-with-warnings: translation left lines untranslated (result.failedLines:cueId,reason, and the sourceexcerpt+location(line, start/end ms) built withanalyzeCoverage, so the UI lists which lines stayed in the original language) or mkvtoolnix reported warnings (result.warnings). The term consistency report (result.consistency, seellm.md) is informational and never changes the status;jobs:dismiss-consistencyonly setsresult.consistencyDismissedon a terminal job that has one.failed:error = { code, message }(AppErrorcode, orINTERNALfor bugs) andstep= where it stopped. The work dir is kept.cancelled(user) deletes the work dir;interrupted(shutdown or crash) keeps it. On boot,runningrows becomeinterrupted.result.usagekeeps the LLM cost even for cancelled/failed jobs.
Retry, cancel, remove
jobs:retry(failed / cancelled / interrupted): back toqueued,attempt + 1. The runner resumes at the first step whose artifact does not verify (artifacts.ts: probe info, extracted and translated files with size + sha256); everything from there on is redone. Outputs (write,mux) are always redone. Translation is cheap anyway thanks to the Job Memory.jobs:cancel: queued →cancelleddirectly; running → abort (LLM request and backoff, child processes); a translation already paid for is still written to the cache.jobs:remove: terminal jobs only; deletes the row and the work dir.jobs:clear-completed: the queue’s “Clear finished”. Deletes everycompleted,completed-with-warningsandcancelledjob in oneDELETE … WHERE id IN (…), then their work dirs (a dir that fails to go is collected later as an orphan). Failed and interrupted jobs stay, since they still need a decision.- Presets: the job stores a resolved snapshot of the preset (
spec.preset, model and target language already decided, seepresets.md), so editing the preset or updating the built-ins does not change a queued job or its retry; deleting a preset used by a non-terminal job →PRESET_IN_USE.
Shutdown and housekeeping
- The
jobsdisposer is registered last (runs first): abort every job, wait up to 5 s, mark leftoversinterrupted; then sidecars, Job Memory and the database close. - Boot: work dirs without a job row, and dirs of terminal jobs finished more than 7 days ago, are deleted.
isBusy()(any job running) blocks the Job Memory prune.
Paths and security
Paths only come from the native dialogs (dialog:open-files, dialog:choose-output-dir) or drag & drop (window.api.files.pathFor(file) = webUtils.getPathForFile). Main revalidates every path in jobs:create / media:probe (media/path-guard.ts): absolute, resolved symlinks, regular file, extension allowlist (.mkv / .srt .ass .ssa) checked on both the given and the real path, readable, subtitles ≤ 50 MB; output dirs must be writable directories. Errors: INVALID_PATH with a stable reason (relative, not-found, not-a-file, extension, too-large, not-writable…).
Batch mode (src/main/batch/)
A batch groups independent jobs created together; it executes nothing itself. Kinds: extract, translate, pipeline, mux (one mux job per MKV, with its paired subtitles). Every kind has a screen: Translate (translate / pipeline, “Several files or a folder”), Extract and Mux (“Select several files”); see renderer.md.
dialog:open-folder | dialog:open-files (multiple) | drag & drop └─ batches:plan scan (folder or files) → probe MKVs (4 in parallel) → automatic selection └─ UI shows the plan; the user adjusts tracks / drops files └─ batches:create resolve + validate EVERY item, then one transaction: batch + all jobs (queued)- Scan (
scan-files.ts): folder from the native dialog, optional recursion, natural order (ep2beforeep10), root files before subfolders, hidden entries skipped, symlinked directories not followed, at most 2,000 files and 10 levels (truncatedin the plan). Every file goes through the same path guard as single jobs; loose files the guard rejects come back inplan.rejectedwith the reason. - Automatic track selection (
track-selection.ts):pipeline: one track, by preferred source language (settingtracks.preferredSourceLangs, default['en'], list order,en-USmatchesen) → ASS/SSA before SRT → not forced → name not matchingsign|song|karaoke|lyric→ most events → lowest id.extract: every supported text track.- Files without a usable track stay in the plan with
skipped(no-subtitle-track,no-supported-track,probe-failed+error).
- Create (
batch-service.ts): all items are resolved (resolveJobSpec, 4 in parallel) before anything is written; one bad item rejects the whole batch (INVALID_INPUT, messageitem N: …, always the first failing item in plan order).translate/pipelinetake batch defaultspresetId,model,targetLang,notes(each falls back to Settings:translation.defaultPresetId/defaultModel/defaultTargetLang; missing →MODEL_NOT_SET/TARGET_LANG_NOT_SET). - Works (
groups): the unit of context of a translate batch.groups[](BatchGroup:name?,media?TMDB ref,presetId?,model?,targetLang?,notes?) anditems[].group(index), withitems[].season/episodefor series. A group’s settings replace the batch defaults for its files (notes too: an empty string means no notes);mediacomes only from the group, so files without a group, or in a group withoutmedia, carry no media context. The TMDB lookup goes through the sameMediaLookupSourceas single jobs (a lookup failure is logged and the job runs without it). Unknown group index orgroupson anextractbatch →INVALID_INPUT. The groups are kept in the batch’soptionsJSON. - Mux batches (
kind: 'mux',mux-pairing.ts):batches:planscans MKVs and subtitles (.srt .ass .ssa .vtt) from a folder or loose files, without probing, and returnsBatchMuxPlan:items[]={ video, subtitles[] }(1..32, natural order, each withlanguageandmatchedBy),unmatchedVideos,unmatchedSubtitles,rejected,truncated. Pairing is deterministic (no edit-distance guessing):- Same folder and same base name, case-insensitive, ignoring language/flag suffixes on the subtitle (
X.mkv↔X.pt-BR.srt,X.en.forced.ass,X.srt). ASubs/orSubtitles/folder next to the video counts as the video’s folder. - Otherwise, same folder and same season/episode taken from the file names with the release-name parser of the media context (
S01E05,1x05, or absolute anime numberingShow - 28). - More than one candidate video (two files with the same base name or the same episode) is ambiguous: never resolved here, the subtitle goes to
unmatchedSubtitlesfor the UI to place. A subtitle beyond the 32nd of a video also lands there.
- Language comes from the filename suffix (
.pt-BR,.en),undwithout one; the user edits it beforecreate.undis a valid language for the mux job. batches:createtakesitems: { video, subtitles: { path, language, name?, default? }[] }[]plus the batch-leveloptions(setDefault,keepOriginalSubtitles;alsoWriteSubtitle,outputModeandextractNamingare ignored). Every item is resolved before the transaction (sameresolveJobSpecas the single mux job); a bad item, a repeated video, an item of the wrong shape for the kind, orgroups→INVALID_INPUT(item N: …). Subtitle parsing is validated in the job (validatestep,INVALID_SUBTITLE), as in the single mux. Preset/model/language/notes/media settings do not apply.- Output
<base>.<lang>.mkv(first subtitle’s language) next to the source, mirrored underoutputDirfor a folder batch; collisions get(2). FIFO, cancel and remove behave as in the other kinds.
- Same folder and same base name, case-insensitive, ignoring language/flag suffixes on the subtitle (
- Output options (
batches:createoptions):outputMode(pipeline, defaultmux;alsoWriteSubtitleis the deprecated alias),extractNaming(extract),overwrite(extract/translate/pipelinesubtitles); all forwarded to every item’s job. - Output: without
outputDir, next to each source. WithoutputDirand a folder batch, the relative structure is mirrored (subfolders created on demand); items must be inside the batch folder. Loose-file batches withoutputDirare flat; name collisions get(2). - Order: jobs keep the plan order in the FIFO queue (staggered
created_at). - State:
Batch.countsper job status,total,state: active | finished. - Cancel: queued jobs first (so the queue cannot pick the next item of the same batch), then running ones.
- Remove: only when no job is active; removes the jobs (and their work dirs) and the batch.
Pending
- Image-based subtitles (PGS/VobSub/DVB) are out of scope (OCR dropped).