Skip to content

Workflows as Scripts

akib35 edited this page Nov 6, 2026 · 4 revisions

Workflows as Scripts

For people who would rather write a workflow as text than drag blocks, and for anyone asking an LLM (Claude, ChatGPT, a coding agent) to write one. Every workflow in BlockFlow is a JSON file; this page explains that file, how to get it in and out of the extension, and how it compares to a Playwright script.

The canonical reference is the usage guide. This page summarises it and adds the practical parts: a prompt template, the edit-run-fix loop, and a Playwright mapping.

The file format

A workflow file is usually called something.blockflow.json. It holds one or more workflows, each a list of blocks (nodes) and connections (edges). This one opens a search page, types a query, presses Enter and checks that results appear:

{
  "format": "blockflow-workflows",
  "version": 1,
  "workflows": [
    {
      "schemaVersion": 1,
      "id": "search-test",
      "name": "Search shows results",
      "enabled": false,
      "nodes": [
        { "id": "open", "type": "open-url", "position": { "x": 0, "y": 0 },
          "config": { "url": "https://example.com/search", "where": "window" } },
        { "id": "query", "type": "fill", "position": { "x": 260, "y": 0 },
          "config": { "locator": "role=searchbox", "value": "blue shoes" } },
        { "id": "submit", "type": "press-key", "position": { "x": 520, "y": 0 },
          "config": { "key": "Enter", "locator": "role=searchbox" } },
        { "id": "results", "type": "assert", "position": { "x": 780, "y": 0 },
          "config": { "subject": "count", "locator": ".result", "operator": "greater", "expected": "0" } }
      ],
      "edges": [
        { "id": "e1", "source": "open", "target": "query" },
        { "id": "e2", "source": "query", "target": "submit" },
        { "id": "e3", "source": "submit", "target": "results" }
      ]
    }
  ]
}

What each part means:

Part Meaning
format, version Always "blockflow-workflows" and 1. A single workflow object without this wrapper also imports.
id Any unique string. Import replaces it with a fresh id (references between workflows in the same file, from Run Workflow, are kept).
enabled Ignored on import: imported workflows always arrive off.
nodes[].type The block type, e.g. open-url, click, assert. Must exist in the block reference.
nodes[].config The block's settings. Keys come from the block reference; missing keys take the default.
nodes[].position Where the block sits on the canvas. About 260 px apart left to right reads well.
nodes[].step Optional per-block settings: timeoutSeconds, retries, onError, screenshot, disabled, note, realInput. See step settings.
edges Connections. sourcePort picks an output on blocks that have several: "true"/"false" on If, "each"/"done" on loops, "error" when the source has "step": { "onError": "port" }.

A block with no incoming edge is a start block. The first block here, Open Tab, runs once when you press ▶ Run. To run on a schedule, start with a timer or schedule block instead (see Concepts).

Data flows along edges as a JSON object. A block's settings can use earlier data with {{name}}, secrets with {{secret.name}}, and expressions with {{ price * 1.1 }}. Details: data and templates.

Reference files (generated from the code)

These are generated by npm run guide:sync from the block definitions, so they are always in step with the extension. Give them to an LLM rather than retyping them.

File Use it for
blocks.md Every block: type, every config key with type and default, outputs, default timeout. Human-readable.
blocks.json The same, machine-readable.
workflow.schema.json JSON Schema of an import file, with every block's config. Use it in an editor (VS Code: "$schema") or a validator.
examples/ Eight importable workflows. A test checks that each imports without errors.
llms.txt The short index an AI tool should read first.

The schema checks shapes and allowed values. It does not reject unknown config keys (they are silently ignored by BlockFlow too), so a typo like "locater" passes both. Check key names against blocks.md.

Rules an AI tool must follow

The full list is in the guide: Rules for AI tools. In short:

  1. Output the export format above.
  2. Use only block types and config keys from blocks.md.
  3. Every page block (Click, Fill, Assert on the page, Extract List…) needs an Open Tab earlier on the same path, with the same tab name (default main).
  4. Connect with edges; use sourcePort only on blocks with several outputs.
  5. Prefer readable locators: role=button[name="Sign in"], label=Email, text=Welcome, testid=…. Actions are strict: a locator that matches two elements fails. See locators.
  6. Never put passwords or tokens in the file. Use {{secret.name}} and tell the user which secrets to create.
  7. Do not add waits "just in case": every action already waits for its element.
  8. Check results with Assert (tests) or If + Notify (monitoring).
  9. Template values are strings. Compare numbers with greater, less and friends.

A prompt template

Copy this, fill in the bracketed parts, and attach (or paste) docs/guide/README.md and docs/guide/blocks.md. Models do best with both files in context.

You are writing a BlockFlow workflow file. BlockFlow is a browser extension that runs
automations made of blocks inside my own browser. Attached are its usage guide
(README.md) and its block reference (blocks.md). Follow the guide's
"Rules for AI tools" section exactly.

Task: [what the workflow should do, step by step, e.g. "Log in to https://app.example.com/login
with my email me@example.com, open Settings, and check that the heading says 'Account'"]

Page details I know: [labels, button texts, test ids, URLs. Say "unknown" if you don't know]
How it should start: [by hand with Run / every N minutes / daily at 09:00 / when I visit a URL]
What should happen on failure: [fail the run / send a notification / continue]

Output:
1. One JSON file in the "blockflow-workflows" export format, nothing else in the code block.
   Use only block types and config keys from blocks.md.
2. A list of secrets I must create (name and what goes in it).
3. A list of locators you guessed, so I can check them with Pick on page.

Tips that make the first try more likely to work:

  • Give the model real labels and button texts from the page. Locators it has to guess are the most common reason a generated workflow fails.
  • Ask for one workflow at a time, short, ending in Asserts. Add branches once the straight path passes.
  • If the model writes "locater", "selector" on a Click, or a type that does not exist, the file will still import but the setting is ignored or the block is flagged. Compare against blocks.md.

Import and export

Import (sidebar top, or the All workflows page): pick one or more .blockflow.json files. Each workflow gets a fresh id, a unique name ("Login test 2" if the name is taken) and arrives off, so an import can never start something by surprise or overwrite a workflow.

Export: hover a workflow in the sidebar → export, or select several on All workflows → Export. You get <name>.blockflow.json (several workflows: blockflow-workflows.blockflow.json). Exported workflows are always marked off. Secrets are never part of the file, only their {{secret.name}} references.

+ New ▾ offers the files in examples/ as templates.

Import keeps each block's step settings and each connection's sourcePort. It refuses a file whose connections point at block ids that don't exist, or that uses the same block id twice, and the error names the id.

How errors show up

There are two stages.

1. Reading the file. If the file cannot be read at all, nothing is imported and a notice says why:

Notice Cause
Import failed: This file is not valid JSON. Syntax error: trailing comma, comments, unquoted key.
Import failed: This file does not look like a BlockFlow workflow. A workflow without nodes and edges arrays.
Import failed: A block in this file is malformed. A node without a string id or type.
Import failed: No workflows found in this file. "workflows": [].
Import failed: Two blocks in "<name>" have the id "<id>". Node ids must be unique within a workflow.
Import failed: A connection in "<name>" points at "<id>", which is not a block id. An edge's source or target names no node.
Import failed: A connection in "<name>" is malformed (it needs "source" and "target"). An edge without string source/target.

2. Checking the workflow. After import the editor validates the workflow (the same check runs all the time while you edit):

  • The header shows N problems, ▶ Run is disabled ("Fix the problems first") and turning the workflow on is refused with the list of reasons.
  • Blocks with problems get a badge; click the block to see the messages in its settings panel.
Message Fix
Unknown block type "x" Use a type from blocks.md.
<Setting> is required Add the config key.
<Setting> must be a valid http(s) URL Full URL with https://, or a {{template}}.
<Setting> has an invalid choice Use one of the listed values for that key.
<Setting> must be a number / must be at least … Numbers as JSON numbers ("5" is also accepted).
<Setting>: … (expression error) A broken {{ … }} expression.
Schedule cannot take input from another block Schedule is the one block that only works at the start. Remove its incoming edge.
Nothing can start this workflow: every block has an input. Remove a connection so one block has no input.
This block can never run: no start block leads to it (warning) Connect it, or delete it.
The "x" output is not in use, so its connection never runs (warning) sourcePort names an output the block does not have (e.g. error without onError: "port").
This workflow contains a loop. A run stops after 1000 blocks. (warning) Usually a mistake; use For Each / Repeat instead.

Some checks only happen when the block runs, because they depend on other settings or on data: Assert without a locator on an element check (Element is required for this check), Wait For text mode without text, a page block with no Open Tab before it (No tab named "main" in this run. Put an Open Tab block (tab name "main") before this block.), a bad locator (Invalid role locator: …). These appear as a failed step in the run. See Troubleshooting.

Iterating: run, read, fix

  1. Import the file and open it. Fix anything the editor flags.
  2. Press ▶ Run. Blocks light up ✓ / ✕ / ↪ as the run goes.
  3. Click the failed block: its settings panel shows the input and output of that run, and the error.
  4. Open Reports for the whole run: every step with status, duration, attempts, error, screenshot (taken on failure by default), and Export JSON for the full record.
  5. Fix the workflow (in the editor, or in the JSON and re-import) and run again.

To let an LLM fix its own workflow, give it the failing step's error text, or the exported JSON report, together with the workflow file. Two things to tell it:

  • The run record names blocks by the new ids created on import, not the ids in its file. Match steps by blockType and order, or export the workflow again (the export has the current ids).
  • Error texts are written for people but are specific: role=button[name="Save"] matches 2 elements (button#save, button.save-2). Make it more specific, or add ">> nth=0" for the first one. tells the model exactly what to change.

There is no API or CLI yet for a program to import, run and read results on its own; a person has to do the import and press Run. That loop is planned (see Roadmap).

Playwright to BlockFlow

BlockFlow's locators follow Playwright's, so a Playwright test usually translates step by step. Rows marked no equivalent yet have no block today; Run Script (your own JavaScript in the page, Chrome 135+) covers some of them.

Pages and navigation

Playwright BlockFlow
const page = await context.newPage(); await page.goto(url) Open Tab open-url (url, tab name, where, waitUntil)
page.goto(url) on an open page Navigate navigate, action: "goto"
page.goBack() / goForward() / reload() Navigate action: "back" / "forward" / "reload"
page.waitForEvent('popup') Click, then Wait for Popup wait-for-popup; later blocks use "tab": "popup"
page.close() Close Tab close-tab
page.frameLocator('#pay').getByLabel('Card') locator frame=#pay >> label=Card
page.setViewportSize, emulateMedia, geolocation, locale no equivalent yet
new browser context per test, storageState no equivalent yet (runs share your browser profile)

Locators

Playwright BlockFlow locator
getByRole('button', { name: 'Save' }) role=button[name="Save"] ([exact] for exact)
getByText('Sign in') / { exact: true } text=Sign in / text="Sign in"
getByLabel, getByPlaceholder, getByTestId, getByAltText, getByTitle label=, placeholder=, testid=, alt=, title=
locator('css'), locator('xpath=…') the CSS itself, xpath=…
a.locator(b), .first(), .last(), .nth(n) a >> b, >> nth=0, >> nth=-1, >> nth=n
filter({ hasText }), has, or, and, visible no equivalent yet

Actions

Playwright BlockFlow
locator.click() / dblclick() / click({ button: 'right' }) / hover() Click click, action: click / double / right / hover
click({ force: true }) Click force: true
click({ modifiers }), click({ position }), middle button no equivalent yet
locator.fill(value) Fill fill
locator.pressSequentially(text), keyboard.type Fill mode: "type"
several fills and a submit click Fill Form fill-form (fields, submit)
locator.selectOption(label) Select Option select-option (text or value; a|b for multi)
check() / uncheck() / setChecked() Check check, state
locator.press('Enter'), keyboard.press('Control+A') Press Key press-key (locator optional)
setInputFiles Upload File upload-file (one file, from text or a URL)
page.on('dialog', d => d.accept()) Dialogs dialogs, placed before the click that opens the dialog
scrollIntoViewIfNeeded(), mouse.wheel Scroll scroll (to: element, end, bottom, top)
page.evaluate(fn) Run Script run-script (Chrome 135+, needs the userScripts permission)
dragTo, focus, blur, clear, dispatchEvent no equivalent yet
isTrusted input (Playwright's input is always trusted) step setting "realInput": true (Chromium only)

Waiting

Playwright BlockFlow
auto-waiting before actions built in: visible, enabled, stable, not covered, exactly one match
locator.waitFor({ state }) Wait For wait-for, mode: visible / hidden / attached / detached / enabled
page.waitForURL(pattern) Wait For mode: "url" (contains, */** globs, /regex/)
page.waitForLoadState('load' | 'networkidle') Wait For mode: "load" / "networkidle"
page.waitForResponse(url) Wait For mode: "response", url, status (201, 2xx). Status only, no body
page.waitForRequest no equivalent yet
page.waitForEvent('download') no equivalent yet
page.waitForTimeout(ms) Timer after a block delays the flow (exported back as page.waitForTimeout)

Reading and assertions

Playwright BlockFlow
expect(l).toHaveText / toContainText Assert assert, subject: "text", operator: "equals" / "contains" (also matches, starts-with…)
toHaveValue Assert subject: "input"
toHaveAttribute(name, v) Assert subject: "attribute", name
toHaveClass Assert subject: "attribute", name: "class", operator: "contains"
toHaveCount Assert subject: "count"
toBeVisible / toBeHidden / toBeChecked / toBeEnabled / toBeDisabled Assert subject of the same name (unchecked for not checked)
expect(page).toHaveURL / toHaveTitle Assert subject: "url" / "title"
expect(value).toBe(x) Assert subject: "value", value: "{{key}}"
expect.soft Assert soft: true
toBeFocused, toHaveCSS, toBeEditable, toBeInViewport, toHaveScreenshot, ARIA snapshots no equivalent yet
textContent(), inputValue(), getAttribute(), count(), isVisible() Read Element read-element with tab (no url), read: text / value / attribute / has-class / exists / count
page.title(), meta tags, context.cookies(), localStorage Page Info page-info (read only; setting cookies: no equivalent yet)
page.screenshot() step setting "screenshot": "always" (visible tab only)

Network, data and test structure

Playwright BlockFlow
request.get/post(...) HTTP Request http-request
page.route (mock, block, modify) no equivalent yet
test.beforeEach login, shared helpers Run Workflow run-workflow calls another workflow in the same tab
parameterised tests Data Table → For Each (see Recipes)
test.retries per-block "step": { "retries": 2 }
try { … } catch "step": { "onError": "port" } and an edge with "sourcePort": "error"
page.pause() Manual Step manual-step
test.describe, projects, parallel workers, headless, CI no equivalent inside BlockFlow; export to Playwright for CI (below)

Export to Playwright

Sidebar row or All workflows → 🎭 Playwright downloads <name>.spec.ts, a Playwright test you run with npx playwright test. A workflow exported from the editor was run green this way in the Phase F end-to-end test (see README).

What it does:

  • One test() per exported workflow, using Playwright's page, context and request fixtures. Every start block is walked in turn and written as statements.
  • Locators are translated to getByRole, getByLabel, frameLocator, .nth() and so on. Element assertions use .first() like BlockFlow's reads.
  • Templates run through BlockFlow's own template and expression code: a setting with {{…}} becomes render("…", data), so {{key}}, {{$json.x}}, keys with dashes ({{order-id}}) and expressions ({{ price * 1.1 }}, {{ upper(name) }}) render exactly as in the extension. {{secret.name}} reads process.env.NAME (upper-cased); the header comment lists the environment variables needed.
  • At the end of the spec is the BlockFlow runtime: the real source of src/core/expression.ts, condition.ts, csv.ts, urlPattern.ts and template.ts, inlined at build time (src/core/playwrightRuntime.ts), so it cannot drift from the extension. Data blocks use it: Transform → evaluate(…), Filter → listAt + compare, Data Table → parseRows (JSON, or CSV with quotes and comma/semicolon/tab separators), Set Variable → render, For Each → listAt with item/index/total and count after, If → compare (every operator).
  • Assert retries like BlockFlow's: toHaveText/toContainText, toHaveValue, toHaveAttribute, toHaveCount, expect(page).toHaveURL/toHaveTitle (and not. / regex forms) where Playwright has a matcher; every other operator (greater, starts-with, empty…) becomes expect.poll(() => compare(…)).toBe(true). Soft asserts use expect.soft / expect.configure({ soft: true }).poll. An Assert on a data value is checked once, as in BlockFlow.
  • Wait For mode: "response" → waitForResponse(tab, pattern, status): a matching response of that tab from the last 10 s (usually triggered by the click before) or the next one, through page.waitForResponse; the pattern works like BlockFlow's (contains, */** globs, /regex/) and status accepts 201, 2xx, 200,201. data.response gets { url, status, method }.
  • Open Tab: where: "current" / "workflow" reuse the test's page; "new" / "window" open context.newPage().
  • Dialogs → one page.on('dialog') handler per page that answers with the latest Dialogs choice and records what was shown (read returns dialogs / lastDialog). Upload File → setInputFiles with a Buffer (text) or a file downloaded with request.get (URL). Wait for Popup → a page the site opened in the last 15 s, or context.waitForEvent('page'). Run Script → page.evaluate(async (data) => { …your code… }, data). A Timer after another block → page.waitForTimeout(ms).
  • Step settings: timeoutSeconds → { timeout } on the action or expect; retries → retry(n, …) around the step (1 s, 2 s, 4 s… like the engine); onError: "continue" → try/catch that logs; onError: "port" with an error edge → try/catch that runs the error branch with error / errorBlock in the data (the normal path continues only on success); disabled → a comment.
  • If becomes if/else; For Each, Repeat and Paginate become loops.
  • Run Workflow becomes a call to a generated function for the called workflow.
  • Helper functions (read, compare, extractList, extractTable, setField…) are appended so the test keeps BlockFlow's behaviour.

The e2e spec tests/e2e/specs/playwright-export.mjs runs three such workflows (data table + For Each logins, API response + dialogs + uploads, scraping + popups + error branch) in the extension, exports them from the editor and runs them green with npx playwright test.

Known limits (from src/core/playwright.ts):

Not exported, or exported differently What you get
Notify, Save to Dataset, Download a comment // BlockFlow-only: <Block> has no Playwright equivalent, skipped. Later steps that need their data will not get it.
Triggers (Timer or Schedule at the start, Page Visited, Context Menu, Watch Element) a comment; the test starts there.
Extract List from HTML (source: "html") a // BlockFlow-only: comment
Read Element previous / changed not available (no state between test runs)
realInput ignored (Playwright's input is always trusted)
screenshot step setting ignored (use Playwright's screenshot: 'only-on-failure' option)
Loops back to an earlier block a comment (loop back … not exported)
Data flow one mutable data object, so a branch that changes it also changes it for the blocks written after that branch (BlockFlow gives each branch its own copy)

Treat the export as a strong first draft: read it, run it once, fix what is marked BlockFlow-only.

See also

Clone this wiki locally