Repository navigation
Adding a Block
Step-by-step guide to adding a block type to BlockFlow, and a new page ability (agent op) when a block needs to do something in a web page that no op covers yet. Read Block Internals first for the contract; this page is the recipe and the checklist.
Source: src/core/blocks/ (especially index.ts, setVariable.ts, pressKey.ts), src/core/page.ts, src/dom/agent.ts, tests/helpers/fakeHost.ts, scripts/guide.ts.
- Write
src/core/blocks/<name>.tsexporting aBlockDefinition<YourConfig>. - Import it in
src/core/blocks/index.ts, add it to theexport { … }list, and put it in the right group ofBLOCK_GROUPS(that sets its palette category and order). - Test it in
tests/core/*.test.tswithharness()andflow()fromtests/helpers/fakeHost.ts. -
npm run guide:sync, and checkdocs/guide/README.mdstill tells the truth. - Update the learning material (
docs/learning/07-blockflow-code-tour.mdexercises, perdocs/learning/MAINTAINING.md). -
npm run check.
The editor, the background worker and the Playwright exporter need no changes for a block to work: they all read the registry.
| It… | Implement | Model it on |
|---|---|---|
| transforms the data and passes it on |
run returning { ...input, … }
|
setVariable.ts, transform.ts |
| chooses between outputs |
ports + run returning routeTo(port, payload)
|
ifBlock.ts |
| loops |
ports: ['each', 'done'], await ctx.emit(…, 'each') per item, return routeTo('done', …), long timeoutSeconds
|
forEach.ts |
| acts on the run's tab |
inPage(ctx, input, request) + locatorField() + tabField, timeoutSeconds: PAGE_TIMEOUT_SECONDS
|
pressKey.ts, click.ts |
| calls something outside (HTTP, notifications, datasets) | a ctx.host.* method (add one to Host if needed, see below) |
notify.ts, httpRequest.ts |
| starts the flow on a schedule |
start (set timers), onTimer (emit), trigger (Run button) |
timer.ts, scheduleBlock.ts |
| starts the flow on a browser event |
start (log), trigger, pass-through run, plus a listener in background.ts calling runner.handleEvent()
|
pageVisited.ts |
| needs to wait later (delay) |
ctx.timers.set(name, …, payload) + onTimer → ctx.emit (the rest continues in a new run) |
timer.ts |
Rules from CLAUDE.md that apply to every block:
-
src/corehas no browser APIs or DOM types. Anything outside goes throughctx.host. - No
setTimeout/setIntervalfor workflow timing; usectx.timers+onTimer, orctx.host.sleep()for a short wait inside one step. - Remember things in
ctx.state, not in module variables (the worker restarts). - Payloads, timer data and state stay JSON-serialisable.
-
import typefor type-only imports, relative imports only.
A data block that turns "red, green, blue" into a list For Each can loop over. It is modelled on Set
Variable (templated text in, one new key out) and Data Table (an into setting). This exact code was run
against the real engine with FakeHost.
src/core/blocks/splitText.ts:
import { DATA_ACCENT } from './dataCommon';
import type { BlockDefinition } from '../types';
/** Split Text settings: the (templated) text, the separator, and the payload key for the list. */
export interface SplitTextConfig {
text: string;
separator: string;
into: string;
}
/** Split Text — turns "a, b, c" into a list, e.g. for For Each. Empty parts are dropped. */
export const splitTextBlock: BlockDefinition<SplitTextConfig> = {
type: 'split-text',
label: 'Split Text',
description: 'Split a text into a list, e.g. "a, b, c" for For Each.',
icon: '✂️',
accent: DATA_ACCENT,
defaultConfig: { text: '', separator: ',', into: 'items' },
fields: [
{ key: 'text', label: 'Text', kind: 'text', required: true, templated: true, placeholder: '{{value}}' },
{ key: 'separator', label: 'Separator', kind: 'text', placeholder: ',', help: 'Empty = one item per line.' },
{ key: 'into', label: 'Save the list as', kind: 'text', placeholder: 'items' },
],
summary: (config) => `split by "${config.separator || '\\n'}" → {{${config.into || 'items'}}}`,
outputs: [
{ key: 'items', description: 'The parts, trimmed, without empty ones (or the name you chose).' },
{ key: 'count', description: 'How many parts.' },
],
async run(ctx, input) {
const parts = ctx.config.text.split(ctx.config.separator || '\n').map((part) => part.trim()).filter(Boolean);
ctx.log('info', `Split into ${parts.length} part${parts.length === 1 ? '' : 's'}`);
return { ...input, [ctx.config.into.trim() || 'items']: parts, count: parts.length };
},
};Things worth noticing:
-
templated: trueontextmeans the engine renders{{tags}}against the input beforerun, and the editor offers{{…}}suggestions.separatorandintoare not templated: they are literal. -
required: trueis checked after rendering, so{{missing}}fails the step withSplit Text: Text is requiredandrunis never called. You do not re-check required fields inrun. -
defaultConfigmust have a value for every field key. Old workflows saved before you add a field get the default. -
summarygets the raw saved config (templates unrendered) and must never throw. -
Return
{ ...input, … }so$session(the run's tabs) and everything upstream keep flowing.
In src/core/blocks/index.ts: add import { splitTextBlock } from './splitText';, add splitTextBlock to
the export { … } list, and add it to the data group of BLOCK_GROUPS where it should appear in the
palette. Do not set category in the block; createDefaultRegistry() does that.
Block tests run the real WorkflowRunner against FakeHost (Node, no browser). flow() builds a
workflow from nodes and [from, to] / [from, to, port] edges; harness() wires a runner with the default
registry and collects logs and run records.
import { describe, expect, it } from 'vitest';
import { flow, harness } from '../helpers/fakeHost';
describe('Split Text', () => {
it('splits a templated value into a list For Each can use', async () => {
const h = harness(
flow(
[
{ id: 'v', type: 'set-variable', config: { name: 'tags', value: 'red, green,, blue' } },
{ id: 's', type: 'split-text', config: { text: '{{tags}}', into: 'colours' } },
{ id: 'each', type: 'for-each', config: { list: 'colours', as: 'colour' } },
{ id: 'log', type: 'log', config: { message: '{{index}}={{colour}}' } },
],
[['v', 's'], ['s', 'each'], ['each', 'log', 'each']],
),
);
const run = await h.runner.runOnce();
expect(run.status).toBe('passed');
expect(run.steps[1]?.output).toMatchObject({ colours: ['red', 'green', 'blue'], count: 3 });
expect(h.messages('info')).toEqual(expect.arrayContaining(['0=red', '1=green', '2=blue']));
});
it('fails clearly when the text renders empty', async () => {
const h = harness(flow([{ id: 's', type: 'split-text', config: { text: '{{missing}}' } }], []));
const run = await h.runner.runOnce();
expect(run.status).toBe('failed');
expect(run.error).toContain('Text is required');
});
});Useful FakeHost / harness knobs (full list in Testing):
| Need | Use |
|---|---|
| Run the workflow once (Run button) |
await h.runner.runOnce() → RunRecord
|
| Switch it on, then fire a timer |
await h.runner.start(); await h.fire('tick') (first timer whose name starts with tick) |
| Simulate a worker restart | const fresh = h.restart(); await fresh.handleTimer(key) |
| Control page-agent answers |
h.host.agent = async (tabId, request) => ({ … }) (throw to fail); inspect h.host.actions
|
| Control HTTP |
h.host.httpHandler = async () => ({ status, ok, body }); inspect h.host.requests
|
| Move the clock |
h.host.advance(ms); h.host.now() is fixed at 2026-01-01 otherwise |
| Logs |
h.messages('info'), h.logs
|
Page blocks need an Open Tab before them in the test ({ type: 'open-url', config: { url: 'https://shop.test' } })
or $session in the input; see the chain() helper in tests/core/pageBlocks.test.ts.
-
npm run guide:syncregeneratesdocs/guide/blocks.md,blocks.jsonand the workflow JSON schema from the registry.npm run guide:check(part ofnpm run check) fails until you do. - Check
docs/guide/README.md: if the block is a start block, add it to the "Starting a workflow" table; if it changes how something is best done, fix the relevant section. Example workflows indocs/guide/examples/*.blockflow.jsonare validated bytests/core/guideExamples.test.ts. -
README.mdlists every block in "The idea" table and states the block count; update both. - Learning material:
docs/learning/MAINTAINING.mdmaps "New block type" to the exercises at the end ofdocs/learning/07-blockflow-code-tour.md(remove an exercise if you just built it). If the block teaches a new extension concept, extend the lesson that covers it and runnode docs/learning/tools/sync-examples.mjs. - Optional: a Playwright mapping in
src/core/playwright.ts(statement()switch; unmapped blocks export as// <label>: no Playwright equivalent, skipped.), a recorder mapping insrc/core/recording.ts, a template insrc/entrypoints/editor/templates.ts.
If the block needs something from the browser that Host does not offer (clipboard, cookies API…):
- Add the method to
Hostinsrc/core/types.ts(plain data in and out). - Implement it in
createExtensionHost()insrc/browser/host.ts(or a newsrc/browser/*.tsmodule it calls). Add any permission towxt.config.ts; optional ones can be offered with the block'spermissions(only'debugger'and'userScripts'are typed today). - Add a fake to
FakeHostintests/helpers/fakeHost.tsthat records calls, so tests can assert them. - Then write the block. See Browser Host.
Blocks never touch the DOM. They send an AgentRequest (src/core/page.ts) through
ctx.host.page.act(tabId, request, timeoutMs); the browser side injects the page agent
(src/dom/agent.ts) and asks it again and again until it answers done/error or the time runs out. See
Page Protocol and Page Agent.
Example: a focus op ("put the cursor in this field" without typing), in the order CLAUDE.md asks for.
Add a member to the AgentRequest union. Keep it plain JSON (it travels through scripting.executeScript):
/** Focus an element (waits until it is visible and enabled). */
| { op: 'focus'; locator: string }TypeScript now reports the agent's switch (request.op) as not returning on every path, which is your
to-do list.
Write the jsdom test in tests/dom/agent.test.ts (it uses the real agent on document):
it('focus puts focus on the element', async () => {
page('<input id="a"><input id="b">');
expect(await run({ op: 'focus', locator: '#b' })).toMatchObject({ status: 'done' });
expect(document.activeElement?.id).toBe('b');
});Then add the case next to the other actions:
case 'focus': {
const element = one(request.locator); // strict: 0 matches = Pending, 2+ = Fatal
ready(element, { enabled: true }); // throws Pending until visible, enabled, stable
focus(element);
return { focused: describeElement(element) };
}How the agent answers:
| In the op | Agent answer | Driver (src/browser/pageDriver.ts) does |
|---|---|---|
| return an object | {status: 'done', result} |
resolves act() with result
|
throw new Pending(reason) |
{status: 'pending', reason} |
asks again (every ≤ 2 s) until the timeout, then Timed out after Ns: <reason>
|
throw new Fatal(message) / locator syntax error |
{status: 'error', message} |
rejects at once, no retry |
Results must be JSON-friendly, and Chrome sorts object keys in executeScript results; return
{columns, values} when key order matters (see tableToObjects). The same agent also runs on fetched HTML
without layout (Host.html.act), where geometry checks are skipped; jsdom tests behave like that too.
- If the op is a user action that real (debugger) input should perform, add it to
ACTIONSinsrc/browser/pageDriver.tsand toactWithRealInput()(and thelocateop'spurpose). Otherwisestep.realInputis ignored for it, which is correct for reads. -
frame=locators work for free: the agent enters same-origin frames itself, and for a cross-origin one answers{status: 'frame'}so the driver re-runs the request inside that frame. - Also note that an action op whose page navigates away mid-call is reported as
{navigated: true}only for ops inACTIONS.
async run(ctx, input) {
await inPage(ctx, input, { op: 'focus', locator: ctx.config.locator });
return input;
}with fields: [locatorField(), tabField], accent: PAGE_ACCENT, timeoutSeconds: PAGE_TIMEOUT_SECONDS,
and a defaultConfig with tab: 'main'. inPage finds the tab with requireSessionTab and passes
pageWaitMs(ctx) and realInput. Test it with h.host.agent and h.host.actions as in
tests/core/pageBlocks.test.ts.
-
src/core/blocks/<name>.ts:BlockDefinition<Config>with TSDoc on the config and the block - unique, final
type(stored in saved workflows; never rename later) - every field key has a value in
defaultConfig;templatedonly on string fields meant for{{…}} -
runreturns{ ...input, … },routeTo(…), ornulldeliberately; errors are user-readable - timing via
ctx.timers/ctx.host.sleep, memory viactx.state, all values JSON - registered in
index.ts: import,export { … },BLOCK_GROUPS - tests with
harness()/FakeHost(and a jsdom agent test for a new op) - new page op:
page.ts→agent.ts(+ test) →pageDriver.tsACTIONSif it is an action - new Host method:
types.ts,src/browser/host.ts,FakeHost, permissions inwxt.config.ts -
npm run guide:sync;docs/guide/README.mdandREADME.md(block table and count) still correct - learning material updated per
docs/learning/MAINTAINING.md -
npm run checkpasses
-
Block Internals: the contract,
ctx, fields and every existing block - Page Protocol and Page Agent
-
Testing:
FakeHost,harness(), jsdom and e2e tests -
Tooling and Scripts:
guide:sync,learn:sync,npm run check -
Browser Host: implementing a new
Hostmethod - Learning lesson 7: BlockFlow code tour
Generated from docs/wiki in the repo by npm run wiki:publish. Edit the repo files, not this wiki.
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