Typed client integration
The App Contract is the only supported normal communication boundary between a frontend and a Wrapflow App. It fixes resource names, fields, operations, auth, error codes, and compatibility independently of transport URLs.
Uploaded UI bundle
The default MCP path can host a plain HTML/CSS/JavaScript bundle beside the App
backend. Send complete files with ship_app.ui.files or patch the current
frontend revision with upload_app_ui. Read
describe {appId, kind:"ui"} first and use its exact Contract resource names.
Start the named subscription before any await, with loading text already in the HTML.
Each callback is a full authorized result: replace the list, never append; repeated
snapshots must not duplicate rows. Keep pending edits when a snapshot arrives.
Use the subscribed row's _wf_record_id as recordId for every patch or delete,
and _wf_version as expectedVersion when the command uses version checks.
For creates, deletes and publishes, disable the affected submit control and show
“Saving…” until confirmed; only then clear the form or show success. For reversible
check-offs, status changes and renames, update immediately and visibly undo on a
definite refusal. Keep unrelated controls usable. On an uncertain response, show
“Save not confirmed”, preserve the input/edit and offer CommandRetryError.retry()
with the same idempotency key; never undo or send a fresh action as a retry.
Once the command confirms, the save is done: show “Saved” and clear the form before
the list is refreshed, and never await that refresh before re-enabling the submit.
Re-enable controls in finally. If the refresh read fails, say “Saved, refreshing
the list failed” with a retry for the read; never call it “Not saved”.
Command options accept onStatus(state): saving, saved, or failed with
the original error in state.error. The same observer reports retry attempts.
The example uses a menu view and placeOrder / markReady commands. Replace
these with the exact resources and callable identifiers from describe kind:"ui".
Attach onPlaceOrder(input, button) to your create form; it returns true only
after confirmation, including after Retry. Its promise stays pending while the
person decides whether to retry. The checkboxes demonstrate a reversible check-off.
<p id="menu-status" role="status">Loading menu…</p>
<div id="menu"></div>
<script type="module">
import { WrapflowApp, placeOrder, markReady, subscribe } from '/_wrapflow/client.mjs'
const $ = id => document.getElementById(id), list = $('menu'), status = $('menu-status')
const edits = new Map(), feedback = new Map()
function messageFor(key) {
if (!feedback.has(key)) {
const message = document.createElement('p'); message.setAttribute('role', 'status')
feedback.set(key, message)
}
return feedback.get(key)
}
const showError = (error) => { status.textContent = error.message }
let rows = []
function render(items) {
rows = items
list.replaceChildren(...items.map(item => {
const id = item._wf_record_id, row = document.createElement('div'), label = document.createElement('label'), check = document.createElement('input')
check.type = 'checkbox'; check.checked = (edits.get(id) ?? item.status) === 'ready'
check.disabled = edits.has(id)
check.onchange = () => onMarkReady(item, check)
label.append(check, item.customer_name); row.append(label, messageFor(id)); return row
}))
for (const message of feedback.values()) {
if (!message.isConnected && message.textContent) list.append(message)
}
}
const watchMenu = () => subscribe('menu', {}, ({ items }) => {
render(items); status.textContent = items.length ? '' : 'No items yet.'
}, { onError: showError })
let unsubscribe = watchMenu()
window.addEventListener('pagehide', () => unsubscribe())
window.addEventListener('pageshow', (event) => { if (event.persisted) unsubscribe = watchMenu() })
async function save(button, action, confirmed = () => {}, undo = () => {}, key = button) {
if (button.disabled) return false
button.disabled = true
const message = messageFor(key)
if (!message.isConnected) button.after(message)
const onStatus = state => {
message.textContent = state.status === 'saving' ? 'Saving…' : state.status === 'saved' ? 'Saved.' : 'Not saved: ' + state.error.message
}
try {
let result
for (;;) {
try {
result = await action(onStatus); break
} catch (error) {
const uncertain = error.outcome === 'unknown' || error.code === 'command_in_progress' || error.details?.outcome === 'uncertain'
if (!uncertain) {
undo(); message.textContent = 'Not saved: ' + error.message; return false
}
const retry = document.createElement('button'); retry.type = 'button'; retry.textContent = 'Retry'
message.replaceChildren('Save not confirmed: ' + error.message + ' ', retry)
await new Promise(resolve => { retry.onclick = () => { retry.disabled = true; resolve() } })
action = () => error.retry()
}
}
confirmed(result)
return true
} finally {
button.disabled = false
}
}
function onPlaceOrder(input, button) {
return save(button, onStatus => placeOrder(input, { idempotencyKey: crypto.randomUUID(), onStatus }))
}
function onMarkReady(item, check) {
const id = item._wf_record_id, next = check.checked ? 'ready' : 'pending'
return save(check, onStatus => {
edits.set(id, next); render(rows)
return markReady({ status: next }, {
recordId: item._wf_record_id, expectedVersion: item._wf_version,
idempotencyKey: crypto.randomUUID(), onStatus,
})
}, result => {
edits.delete(id)
render(rows.map(row => row._wf_record_id === id && row._wf_version < result.version
? { ...row, status: next, _wf_version: result.version } : row))
}, () => { edits.delete(id); render(rows) }, id)
}
</script>
The bundle may include relative CSS, JavaScript, JSON, images, and fonts.
Use a system font stack or bundle licensed WOFF2 files with relative URLs. Do
not load stylesheets or fonts from Google Fonts: that sends visitors' addresses
to Google. Wrapflow serves Instrument Serif, Spline Sans and Spline Sans Mono
at fonts.css; download the stylesheet,
its referenced WOFF2 files and the corresponding SIL Open Font Licenses into
your bundle to use those families without a visitor making a cross-origin
font request. Preserve the licences with the files.
Wrapflow's draft and live hosts serve /_wrapflow/client.mjs on the same
origin. Do not put an account token in the UI and do not hand-write API fetches.
Bundle libraries locally: remote scripts are blocked even with their host in
egressHosts. Remote network calls and passive resources need their host in
egressHosts; the CSP, size limits, and the external lane an upload needs
are summarized under Frontend choices in SKILL.md.
Exercise reads, writes, reloads, and saved state with look and declared
browser checks before requesting owner review.
Photo and document inputs
Import WrapflowApp from /_wrapflow/client.mjs, then connect with
const client = await WrapflowApp.connect(). Find the action's declared file
field in client.contract.commands; its fileResource names the uploader.
Call client.files(field.fileResource).upload(file) with the browser File,
then pass only the returned fileKey as that field's value to
client.command(command.resource).execute(input, {idempotencyKey}).
A look step can choose the file with
{action:"fill", target:"Label photo", value:"data:image/jpeg;base64,<original-file-base64>"}.
Supply actual bytes, then click the page's submit button, inspect the parsed
fields, and reload to check persistence. The input attaches one file up to
512 KB and runs the page's input/change handlers. Only a representative real
photo establishes recognition accuracy; a fixture establishes byte transport.
Saved scenarios use placeholder AI, and a scheduled draft run holds writes.
Separately hosted multi-file apps
Use this path when presentation needs a framework or a mature UI library such as a chart, map, rich editor, calendar, complex data grid, or diagram. The frontend project owns its framework, libraries, assets, build, and hosting. Wrapflow hosts its App backend and supplies the Contract boundary; it does not host this separately deployed frontend.
Install an exact reviewed version of the small wrapflow-app runtime, then
generate the App-specific adapter. Install the separate @wrapflow/cli package only
on machines that need the wf CLI or owner SDK. Replace the version
placeholders below with versions reviewed from current registry metadata and
advisories:
npm install --save-exact --ignore-scripts 'wrapflow-app@<reviewed-version>'
npm install --save-dev --save-exact --ignore-scripts '@wrapflow/cli@<reviewed-version>' # only when this project also runs `wf`
# For local Wrapflow development instead:
npm install /absolute/path/to/wrapflow/cli
node ./node_modules/@wrapflow/cli/wf.mjs app integration client <app-id> --file src/wrapflow.generated.ts
Do not shorten those commands to npm install wrapflow-app or
npm install --save-dev @wrapflow/cli; both resolve mutable default tags. Do not ask
npx to resolve the wf binary; invoke the exact installed package path shown
above so a missing dependency cannot fall through to the unrelated registry
package named wf.
Use the registry's dist.integrity to verify npm package integrity. The
downloads manifest lists the
package versions and the downloadable skill archive's SHA-256. Do not copy
runtime source into the app or replace the typed client with hand-written fetch
calls.
Keep the generated file in source control. It imports the browser-safe
wrapflow-app runtime and exposes only resources and operations present in the
App contract.
import { AppClient } from './wrapflow.generated'
async function main() {
const app = await AppClient.connect({
baseUrl: 'https://client-requests.wrapflow.app',
getToken: async () => auth.currentAppUserJwt(),
})
const page = await app.requests.query({ limit: 50 })
await app.requests.create(
{ title: 'Update billing address', details: 'Use the new Stockholm office.', priority: 'normal', due_date: '2026-07-31' },
{ idempotencyKey: crypto.randomUUID() },
)
await app.assign_request.execute(
{ owner: 'ops@example.com' },
{
recordId: page.items[0]._wf_record_id,
idempotencyKey: crypto.randomUUID(),
},
)
}
void main()
When a command carries a calendar guard, its Contract entry also lists
transport.availableSlots, exposed on the client as
app.command('<name>').availableSlots({ scopeValue, date, timeZone, stepMinutes? }).
scopeValue is the value the command's scope field takes for the resource
being booked, date is the visitor's local day (YYYY-MM-DD) in timeZone
(an IANA zone), and stepMinutes is optional slot spacing. The result is
{ slots: [{ startEpoch, endEpoch }] } of Unix-millisecond instants; a patch
command also accepts recordId of the booking being moved. The lookup is
read-only — it holds nothing, and the same rule is rechecked by the server
when the command writes.
Keep startup awaits inside an async entry function in plain Vite projects. This
builds with Vite's default production target; do not raise the browser target
merely to allow top-level await during AppClient initialization.
For location directories, store finders, or dispatch queues, declare numeric coordinate fields with collection indexes: ['lat', 'lng'] and pass nearby on an entity or non-aggregate view query:
const page = await app.view('nearby_stores').query({
nearby: {
latitudeField: 'lat',
longitudeField: 'lng',
latitude: 59.3293,
longitude: 18.0686,
radius: 10,
unit: 'kilometers', // 'meters' (default) | 'kilometers' | 'miles' (max 2,000 km)
},
limit: 25,
})
// Rows arrive sorted by distance asc, then _wf_record_id asc, with _wf_distance and _wf_distance_unit.
Pass page.nextCursor as cursor alongside the same nearby object for later pages. nearby cannot be combined with orderBy, recordId, aggregate, count: true, or CSV export, and refuses unindexed coordinate columns with collection_nearby_index_required.
Adapt connection lifetime to the framework:
- React: connect once in a provider or query client layer; keep request state in the project's existing server-state library.
- Angular: provide the connected client from an injectable service; convert promises to Observables only at the application boundary.
- Vue: connect from a plugin/composable and preserve the project's state model.
- Server-rendered frameworks: create per-request clients when visitor auth is request-scoped. Do not leak one user's token through a module singleton.
Do not invent methods from examples. Read the generated adapter and contract; resource names and allowed operations are App-specific.
Lists other people can change
When a screen lists records that somebody else can create or edit — a shared
booking, a queue, a roster, a handoff — subscribe so the list updates without a
reload. The generated adapter and the wrapflow-app runtime expose
subscribe(entity, onChange), which returns an unsubscribe function:
const unsubscribe = app.subscribe('bookings', () => void loadBookings(), {
onRefetch: () => void loadBookings(),
})
// Call it when the view unmounts.
unsubscribe()
The callback receives { entity, recordId, version } — a change notice only,
never record data — so always refetch through the normal typed query. The
caller's scope and any member-limited view still apply, so a subscription never
widens what a person can read. The connection reconnects by itself, and
onRefetch also fires when the window regains focus while the stream is down,
so a list that missed notices while offline still catches up. Subscribe only to
entities whose contract declares a query.
This package API carries change notices; perform the initial typed query too.
The hosted named subscribe(view, params, render, {onError}) above instead
delivers the initial full result and refreshes it after changes. In either case,
replace the list with each result and show read failures in the page.
Use app.view(name).query(params) for one-off reads. Clock-filtered views
(for example, today’s records) cannot subscribe: query initially and every
60 seconds, stopping on pagehide and restarting on persisted pageshow.
Save feedback in a framework
Use the same states as the uploaded example: pending, confirmed, refused or
uncertain. Disable the affected submit while it is pending. Creates, deletes
and publishes show “Saving…” until confirmation; clear inputs only on success.
Reversible check-offs, status changes and renames update immediately and undo
visibly on a definite refusal. In the package client, execute supports
optimistic: {apply, reconcile, rollback} for those reversible edits.
An uncertain outcome keeps the input/edit; offer the same action's retry with
its original idempotency key rather than sending another action.
A framework list replaces its rows after a read, including after reconnects;
it never appends a full result. Preserve pending edits across those snapshots.
Use the subscribed row's _wf_record_id for every patch or delete, plus
_wf_version for commands that check expectedVersion.
Selecting frontend libraries safely
Use the project's normal package manager and make the decision from current registry and advisory data. Wrapflow must not create a curated allowlist, library catalog, proxy package, or home-grown replacement.
- Review publisher/repository provenance, maintainer and ecosystem reputation, maintenance history, package contents, license, advisories, and install scripts for the exact version.
- Quarantine every package in the resolved graph for seven days by default,
including transitive dependencies. When supported, generate or update the
lock against a registry publish-time cutoff (npm:
--before=<cutoff-at-least-seven-days-old>), then verify the committed lock against current publish timestamps. If package age cannot be verified, fail closed unless a human documents an explicit exception after review. - Pin direct dependencies exactly. Do not use
latest, mutable tags, caret or tilde ranges; commit the lockfile to fix the transitive graph. - Disable lifecycle scripts during installation by default. Enable a required script only after reviewing the exact package version and the script it runs.
- Run the package manager's audit/advisory check, then type-check, test, build, and browser-test the real project. Repeat the review for upgrades.
Plain JavaScript in an external project
A separately hosted plain-JavaScript project may use the reviewed, exactly
pinned wrapflow-app package directly. This package-based example belongs in
that project's source tree and build. An uploaded UI bundle instead uses the
same-origin /_wrapflow/client.mjs example above; neither form is valid inside
the scriptless hosted-single-file presentation:
import { WrapflowApp } from 'wrapflow-app'
async function main() {
const app = await WrapflowApp.connect({
baseUrl: 'https://client-requests.wrapflow.app',
})
app.assertContract('wfc_...')
const list = document.querySelector('#requests')
const page = await app.entity('requests').query({ limit: 50 })
list.replaceChildren(...page.items.map((item) => {
const row = document.createElement('li')
row.textContent = `${item.title} — ${item.status}`
return row
}))
}
void main()
Prefer the generated TypeScript adapter when the project supports TypeScript;
it removes undeclared resources and operations from the callable surface. In
either form, keep raw fetch calls out of the integration so auth, versioning,
media types, and stable error behavior cannot drift from the Contract.
Scriptless hosted-single-file convenience
This lane is separate from an uploaded UI bundle. New Wrapflow-hosted v5 source
is one complete, scriptless semantic HTML
document with inline CSS. A fragment is rejected. Do not install, import, or
load a client, write JavaScript, or add event handlers. The trusted parent shell
loads the exact manifest-pinned client and Contract compiler and operates only
the declared semantic hooks. The child frame sandbox is exactly
allow-scripts allow-same-origin; allow-scripts exists only so WebKit runs
callbacks installed by that trusted parent, not as authored-code permission.
Persistence and serve-time policy reject scripts, handlers, and executable
URLs, and the presentation CSP has exact
script-src 'none'; script-src-attr 'none' directives. Form, modal, popup,
download, pointer-lock, storage-access, and top-navigation sandbox capabilities
remain omitted.
The source document below illustrates query, record projection, create, and selected-record command hooks. Replace every resource and field with the exact names in the App Contract; do not infer them from display labels:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Client requests</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; margin: 2rem; }
article { padding: 0.75rem 0; border-bottom: 1px solid #ddd; }
</style>
</head>
<body>
<main data-wrapflow-app="root">
<h1>Client requests</h1>
<button type="button" data-wrapflow-action="entity-query:requests">
Refresh requests
</button>
<output hidden data-wrapflow-result="entity-query:requests"></output>
<div data-wrapflow-record-list="entity:requests"></div>
<template data-wrapflow-record-template="entity:requests">
<article>
<strong data-wrapflow-record-field="entity:requests:title"></strong>
<span data-wrapflow-record-field="entity:requests:status"></span>
<button type="button" data-wrapflow-record-select>Select request</button>
</article>
</template>
<label>
New request title
<input data-wrapflow-field="command:add_request:title">
</label>
<button type="button" data-wrapflow-action="command:add_request">
Add request
</button>
<output hidden data-wrapflow-result="command:add_request"></output>
<label>
Owner
<input type="email" data-wrapflow-field="command:assign_request:owner">
</label>
<button type="button" data-wrapflow-action="command:assign_request">
Assign selected request
</button>
<output hidden data-wrapflow-result="command:assign_request"></output>
</main>
</body>
</html>
Hosted document policy
Direct hosted-HTML saves were removed: PUT /api/apps/:id/frontend refuses
with 409 hosted_frontend_requires_project, and update_app_frontend /
wf app save no longer exist. A hosted App's interface is saved as its
TypeScript project or rebuilt by Chat. The rules below still bound every
served declarative document:
- Complete document. A
<!doctype html>plus both<html>and</html>are required. Wrapflow binds the exact server-ownedwrapflow-contractmeta tag after authoring; do not invent or alter its value. It never invents the surrounding document, so a fragment fails. - No presentation code. Every
<script>element, inline event handler, executable URL, form, frame, embedded document, popup, worker, or other model-authored executable/network authority is rejected. There is no allowed client script tag or inline-script exception in new hosted source. - Exact semantic actions. Each exposed
entity-query,command,workflow,checkout, orauthenticationaction uses an accessible native control with one matching initially emptydata-wrapflow-resultregion. Required caller inputs use exactdata-wrapflow-fieldnames from the Contract. The compiler, not the document, owns invocation and result updates. - Declarative records. Query projection uses one matching
data-wrapflow-record-list="entity:RESOURCE"andtemplate[data-wrapflow-record-template="entity:RESOURCE"]. Record fields and selection controls stay inside that template. Hooks name Contract operations and projection slots; they are not a widget or styling taxonomy. - No arbitrary resources or navigation.
<link>,srcset, remote URLs, nested browsing contexts, downloads, and general navigation are rejected. Links may target document fragments. Only exact immutable generated App image paths may appear in supported image/CSS URL positions. - One document of at most 512 KB.
Hosted discovery exposes:
/_wrapflow/contract.json— canonical contract/_wrapflow/openapi.json— OpenAPI 3.1 view/_wrapflow/client.js— manifest-pinned runtime loaded only by the trusted parent shell/_wrapflow/presentation— exact scriptless child document/_wrapflow/compiler/<checksum>.js— exact Contract compiler loaded only by the trusted parent shell/_wrapflow/client.ts— generated adapter for the live release
Hosted v2/v4 manifests are frozen compatibility authority for exact releases
that are already live; they cannot be newly released, reactivated, or treated
as the v5 boundary. Republish from the current draft to create a reviewed v5
release. External v3 remains the JavaScript/framework lane. Only v3 and v5 can
cross a new release or activation boundary. Marketplace accepts only assetless
hosted v5; publishing v2/v4 returns marketplace_republish_required.
This lane is for a simple self-contained document, not third-party packages or framework bundles. Do not hand-build mature UI primitives to remain hosted. If the product needs them, preserve the same Contract resources in an external App-owned frontend instead.
Compatibility and errors
The generated adapter pins a compatibilityHash. Regenerate it after a backend
schema, operation, policy, or route change. A frontend-only release may keep the
same hash.
import { WrapflowAppError } from 'wrapflow-app'
try {
await app.requests.patch(recordId, changes, { expectedVersion })
} catch (error) {
if (error instanceof WrapflowAppError && error.code === 'version_conflict') {
// Re-query, reconcile, and retry only with the user's intent preserved.
} else {
throw error
}
}
Test code paths using stable code values. Treat message as display/debug
text, not control flow.
Integration verification
At minimum:
- Type-check the generated adapter in the real project.
- Run the project's build and unit tests.
- Exercise one allowed read and one allowed mutation or workflow call.
- Confirm an unsupported operation is absent or rejected.
- Confirm identity is required where declared.
- Trigger a validation error and branch on its stable code.
- Trigger stale record or frontend revision handling where applicable.
- Browser-test empty, loading, success, retry, offline, and mobile behavior.