This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
Background Worker
The background entrypoint is the only place workflows run. It wires the engine to the real browser
Host, registers every browser event listener, and turns those events (alarms, storage changes, messages,
navigations, menu clicks) into calls on a fresh WorkflowRunner. Read this page before changing what
starts a run, adding a listener, or debugging "my workflow did not fire".
Source: background.ts, offscreen/index.html, offscreen/main.ts
The design reasons (why nothing lives in memory, why start() is not re-run on wake-up) are in
Architecture: Surviving the background worker sleeping.
Runtime shape per browser
| Browser | Background kind (generated manifest) | Consequences |
|---|---|---|
| Chrome / Edge / Brave | MV3 service_worker |
No DOM (DOMParser, URL.createObjectURL missing), stopped after ~30 s idle. HTML parsing goes to the offscreen document. |
| Firefox | MV3 background.scripts (event page) |
Has a DOM; no offscreen permission requested (wxt.config.ts). Can still be suspended when idle. |
| Safari | MV3 build from npm run build:safari |
Never run end to end (README "What has been verified"). Treat behaviour as unknown. |
Start-up, in order
Everything in defineBackground(() => { … }) runs on every worker start (browser start, install,
and every wake-up after Chrome stopped the worker), not just once.
| Step | Code | Why |
|---|---|---|
| 0 | initialiseDebuggerSessions(), then initialiseRoutes() (not awaited; errors logged) |
Debugger event/detach listeners, multiplexed by tab (Browser Host: cdp.ts); remove Route's declarativeNetRequest session rules left by runs of a previous worker (reserved ids 1 000 000–1 099 999). |
| 1 | createBrowserScheduler(key => onAlarm(key)) |
Real HybridScheduler; short timers firing from memory go down the same path as alarms. |
| 2 | createExtensionHost(scheduler) |
The real Host (Browser Host). |
| 3 | createDefaultRegistry() |
All built-in blocks. |
| 4 | liveRuns, cancelRequests |
In-memory: runs going on in this worker, and run ids the user asked to stop. |
| 4b | runWorkflow, cancelRun, createBridgeHandlers(…), createBridgeConnection(…) |
The M4 bridge (below); nothing connects yet. |
| 5 | updateRuns(markInterrupted(…)) |
Any run still running in bf:runs that this worker does not own can never finish: mark it interrupted. |
| 6 | clearStalePrompts(), clearStaleDebugPauses() |
Manual Steps listed in bf:prompts, and debug pauses in storage.session bf:debug-pause, by a dead worker can no longer be answered. |
| 7 | Register all listeners (below), synchronously | MV3 rule: listeners added later miss the event that woke the worker. |
| 8 | scheduler.restoreAll() (between the alarm and onStartup listeners) |
Recreate alarms the browser dropped, re-arm short in-memory timers. |
| 9 | syncBridge() (after the permissions listeners) |
Reopen the native port when outside control is on. It must come after const report is defined: called earlier it throws (TDZ) and the whole worker stops at start. |
Step 5 runs with
liveRunsempty. That is safe becauseupdateRunsandsaveRunshare one write queue instores.ts: the mark-interrupted write is queued before the event that woke the worker can save its first run, so a brand-new run is never marked interrupted.
The runner factory
const newRunner = (workflow: Workflow) => new WorkflowRunner({
workflow, registry, host,
log: (entry) => void appendLog(entry), // bf:logs
onRun, // liveRuns bookkeeping + saveRun → bf:runs
isCancelled: (runId) => cancelRequests.has(runId),
});
A new runner is built for every event. Runners hold nothing that must survive between events; see
Core Engine for start, runOnce, handleTimer, handleEvent.
onRun(run) is called on every run update: a running run is added to liveRuns; any other status removes it
from liveRuns and cancelRequests. Then saveRun(run) coalesces it into bf:runs
(Storage Keys).
Internal helpers
| Function | What it does | Called from |
|---|---|---|
startWorkflow(id) |
Loads workflows; if id is enabled, newRunner(wf).start() (which first clears that workflow's timers). |
storage.onChanged |
stopWorkflow(id) |
scheduler.clearPrefix(workflowTimerPrefix(id)), then adds every live non-manual run of that workflow to cancelRequests. Runs started with the Run button keep going. |
storage.onChanged |
startAllEnabled() |
start() on every enabled workflow. |
onStartup, onInstalled |
onAlarm(name) |
parseTimerKey(name); ignores keys that are not ours; clears the timer if its workflow is gone or disabled; else newRunner(wf).handleTimer(name). |
alarm listener, and the scheduler's fire for short timers |
eventRoots(type) |
Every node of type with no incoming edge, in every enabled workflow. |
Page Visited, Context Menu |
onPageVisited(tabId, url, kind) |
Skips non-http(s) URLs and tabs in ownTabs. For each page-visited root whose config.url pattern matches (urlMatches; kind: 'route' only if config.when === 'any'), runs handleEvent(nodeId, withSessionTab({url, title, tabId}, 'main', tabId)). |
webNavigation.onCompleted, onHistoryStateUpdated |
syncContextMenus() |
Serialised through menuSync: contextMenus.removeAll(), then one item per context-menu root of an enabled workflow. Id bf-menu::<workflowId>::<nodeId>, title config.title or the workflow name, contexts config.contexts (all/page/selection/link/image). |
onStartup, onInstalled, workflow changes that start or stop something |
onMenuClicked(id, info, tabId) |
Parses the item id, runs handleEvent(nodeId, {url, selection, link, src, tabId}), with $session.tabs.main set when there is a tab. |
contextMenus.onClicked |
openEditor() |
Focuses an existing editor.html tab (and its window) or opens one. |
action.onClicked |
report(what) |
console.error('[BlockFlow] <what> failed', error). Every listener's promise ends in it. |
everywhere |
Listeners
All registered synchronously at the top level of defineBackground.
| Event | Handler | Notes |
|---|---|---|
alarms.onAlarm |
scheduler.handleAlarm(name); if that returns true (only a short timer's heartbeat) stop, else onAlarm(name) |
See Scheduling and Timers. |
runtime.onStartup |
startAllEnabled(), syncContextMenus() |
Browser start (profile load). Not fired on a plain worker wake-up. |
runtime.onInstalled |
On reason === 'install' with no workflows: saveWorkflows(sampleWorkflows()). Then migrateStoredWorkflows() (rewrites bf:workflows once when a workflow has an older schemaVersion, see Core Modules: migrate), startAllEnabled(), syncContextMenus() |
Also fires on extension update and on reload in developer mode. |
webNavigation.onCompleted |
onPageVisited(tabId, url, 'load'), top frame only (frameId === 0) |
Page Visited trigger. |
webNavigation.onHistoryStateUpdated |
onPageVisited(tabId, url, 'route'), top frame only |
SPA route changes; only for when: any. |
webNavigation.onCreatedNavigationTarget |
recordPopup(tabId, sourceTabId), onRecordedPopup(tabId, sourceTabId, url) |
For Wait for Popup, and so the recorder follows popups. Not tabs.onCreated: its openerTabId is empty for popup windows and names the active tab for links opened from a background tab. |
tabs.onUpdated |
onRecordedTabUpdated(tabId, change) when change.url or status === 'complete' |
Recorder: adds navigated steps and re-injects the recorder after a load. |
contextMenus.onClicked |
onMenuClicked(...) |
Context Menu trigger. |
storage.onChanged (area local, key bf:settings) |
syncBridge() |
"Allow outside control" switched on or off. |
permissions.onAdded / onRemoved |
syncBridge() |
nativeMessaging granted or revoked. |
storage.onChanged (area local, key bf:workflows) |
diffWorkflows(migrated old, migrated new) (so the one-time schema rewrite restarts nothing) → stopWorkflow for stop; for removed (deleted, on or off) also scheduler.clearPrefix of its timers and clearWorkflowState (its bf:state:<id>::* keys); then startWorkflow(id, true) for start (plain start blocks run) and startWorkflow(id, false) for restart (triggers re-armed only); syncContextMenus() if any list is non-empty |
The editor never messages the worker to start or stop: saving is enough. Position/name edits produce an empty diff. |
notifications.onButtonClicked |
Manual Step: button 0 = Continue (answerPrompt(runId, true)), button 1 = Fail |
Only for notification ids bf-prompt:<runId>. |
notifications.onClicked |
Manual Step: Continue | Firefox has no notification buttons, so a click means Continue. |
action.onClicked |
openEditor() |
Toolbar button. No popup is defined. |
runtime.onMessage |
Dispatch on message.type (below) |
Never sends a response; results come back through storage or a separate message. |
Runtime messages handled
Full payloads in Message Protocol.
type |
Action |
|---|---|
bf:start-pick |
startPicking(sender.tab?.id, url, mode, urlFrom); the sender's tab is remembered as the editor tab. |
bf:picked |
finishPicking(message, {tabId, frameId, tabUrl}) from sender |
bf:pick-cancelled |
cancelPicking(sender.tab?.id) |
bf:pick-error |
from a picker in a page: cancelPicking(sender.tab.id) (the editor shows the message itself) |
bf:picker-sync / bf:recorder-sync |
relayPickerSync / relayRecorderSync: passed on to every frame of the sender's tab |
bf:run-workflow |
newRunner(migrateWorkflow(message.workflow)).runOnce(message.options): runs the workflow as sent (the canvas, possibly unsaved), enabled or not. options (M5): trace, debug: { pauseOnError? }, startAt: { nodeId, input } (Run from here). |
bf:stop-run |
cancelRun(runId): cancelRequests.add(runId), answerPrompt(runId, false) and answerDebug(runId, 'stop') (a run waiting on a Manual Step or paused by the debugger stops right away). The bridge's stop and timeoutSeconds use the same function. |
bf:answer-prompt |
answerPrompt(runId, ok) |
bf:accept-baseline |
M5.3: acceptBaseline(comparisonId) (visual.ts), then broadcasts bf:baseline-accepted (with error when the comparison or its picture is gone). |
bf:debug-answer |
M5.2: continue / step → answerDebug(runId, action); stop → cancelRun(runId) (as Stop). |
bf:run-suite |
Runs the saved suite with runSuite; workflowIds (M5.5 "Re-run failed") becomes only. Answers with bf:suite-progress / bf:suite-result broadcasts. |
bf:start-recording / bf:stop-recording / bf:recorded |
startRecording / stopRecording / recordStep(step, sender.tab?.id) |
| anything else | ignored (bf:pick-result is for the editor; bf:parse-html fails isExtensionMessage). |
How workflows start and stop
| Situation | What happens |
|---|---|
| Install (first time) | Samples saved → storage.onChanged starts the enabled ones, and onInstalled calls startAllEnabled(). Both call start(), which clears timers first, so the second call replaces the first's timers. |
| Browser start | onStartup → startAllEnabled(). Timers also come back through restoreAll(). |
| Worker wakes up (alarm, message, navigation) | Nothing is restarted. Only the event's handler runs, on a fresh runner. |
| Editor saves a workflow | diffWorkflows: newly enabled or behaviour-changed → start(); disabled or deleted → stopWorkflow(); deleted → its timers and block state are removed too. |
| Run button | bf:run-workflow → runOnce() with trigger manual; schedules nothing. |
| Stop button | bf:stop-run → run id in cancelRequests; the engine checks isCancelled between steps. A paused debug run is answered stop. |
| Debug pause (M5.2) | Host.debug.pause (debugChannel.ts) waits in this worker; the run's scheduler.hold and the channel's polling keep the worker awake meanwhile. |
| Timer due | onAlarm → handleTimer(key); disabled/deleted workflow → timer cleared. |
| Page Visited / Context Menu | handleEvent(nodeId, payload) with the tab as $session.tabs.main. |
The bridge (outside control, M4)
function runWorkflow(workflow, options: RunWorkflowOptions = {}): Promise<RunRecord>
// = new WorkflowRunner({ workflow: migrateWorkflow(workflow), registry, host: withRunOverlay(host, options),
// log, onRun: run => { onRun(run); options.onRun?.(run) }, isCancelled }).runOnce()
runWorkflow is the Run button's path with two extras for outside callers: secrets overlay the stored ones
for that run only (never written; the engine masks them like stored ones) and workflows are unsaved
workflows its Run Workflow blocks may call. The bridge's run and suite.run use it (and so may the
bf:run-suite case). Runs it starts are ordinary runs: in liveRuns, bf:runs, stoppable with the Stop button.
syncBridge() (serialised on a promise chain) reads bf:settings and permissions.contains({permissions: ['nativeMessaging']}), sets the handlers' isEnabled flag and calls bridge.enable() or bridge.disable().
While enabled the open native port keeps the worker alive; see
Browser Host: bridge.ts for the port's
states, reconnects and the methods, and Bridge for the native host.
Run lifecycle, from the worker's side
- A runner method creates a
RunRecord(status: 'running') and reports it viaonRun→ added toliveRuns, written tobf:runs. - Each step update calls
onRunagain;saveRunmerges updates that arrive while a write is in flight into one write. - Log lines go to
bf:logsthroughappendLog(serialised, capped at 300). - On finish/fail/cancel
onRunremoves the run fromliveRunsandcancelRequests. - If the worker dies first, the next worker start marks the run
interrupted(markInterrupted).
The editor follows all of this by watching bf:runs and bf:logs (see Editor).
The offscreen document
Chrome's service worker has no DOM, but Extract List / Extract Table on fetched HTML need DOMParser.
Host.html.act (actOnHtml in htmlParse.ts) therefore:
- parses in place when
DOMParserexists (Firefox's event page); - otherwise calls
ensureOffscreen():offscreen.createDocument({ url: '/offscreen.html', reasons: ['DOM_PARSER'] })ifoffscreen.hasDocument()is false (parallel callers share one creation; a "single offscreen" error from a race is ignored), thenruntime.sendMessage({ type: 'bf:parse-html', html, baseUrl, request }).
offscreen/main.ts answers only bf:parse-html: it calls
runOnHtml(html, baseUrl, request) (parse with a <base href>, run the page agent on the
parsed document with budgetMs: 0) and replies { ok: true, result } or { ok: false, error }, returning
true to answer asynchronously. The document is never closed; it stays until the browser drops it.
Background: Architecture: Data and scraping.
Gotchas
- Add listeners at the top level only, synchronously, inside
defineBackground. Never inside anawaitor a helper called later. - No
setTimeoutfor workflow timing here; use the scheduler. In-step polling insrc/browseris fine. - Do not cache workflows in memory. Every handler reloads them with
loadWorkflows(). liveRunsis per worker. A Stop for a run owned by a worker that died does nothing (the run is already marked interrupted on the next start).onMenuClickeddoes not re-checkworkflow.enabled; it relies on menus existing only for enabled workflows.
See also
- Scheduling and Timers:
HybridScheduler, alarms, heartbeat. - Browser Host: every
src/browsermodule the worker uses. - Message Protocol, Storage Keys.
- Core Engine: what the runner does with these calls.
- Picker and Recorder: the page side of picking and recording.
Using BlockFlow
- What is BlockFlow
- Installing
- Getting Started
- Concepts
- Using the Editor
- Workflows as Scripts
- Recipes
- Capabilities and Limitations
- Troubleshooting
- Roadmap
Reference
Internals: engine
Internals: browser
Outside access (M4)
Internals: page and editor
Project
Generated from docs/wiki in the repo by npm run wiki:publish. Edit the repo files, not this wiki.