@sewdn/workflow-react
v0.1.1
Published
React bindings of the workflow client: a provider, hooks for queries, commands and changes on Effect's reactivity atoms, the UI ports of an application, and the copy catalogs.
Readme
@sewdn/workflow-react
React bindings of the workflow client (@sewdn/workflow-client): a provider, hooks for the runtime's reads, its
commands and its changes, the UI ports an application gives the workflow's screens, and the copy catalogs. Built on
Effect's reactivity atoms (effect/reactivity) and their React binding @effect/atom-react, both 4.1.4.
Spike: Effect atoms or TanStack Query
Checked on 2026-11-16 against the registry and the installed sources.
- What exists.
[email protected]shipseffect/reactivity:Atom,AtomRegistry,AsyncResult,Reactivity(invalidation by key),AtomRpc(atoms straight over an RPC group) andHydration. The React binding is@effect/atom-react, released in lockstep witheffect(versions 4.0.6 … 4.1.4,latest4.1.4; peerseffect ^4.1.4,react >=19 <20,scheduler >=0.25 <0.29). Its source is five small files:RegistryProvider,useAtomValue,useAtom,useAtomSet(with a promise mode),useAtomRefresh,useAtomMount,useAtomSuspense,useAtomSubscribe, hydration helpers. The older@effect-atom/atom-react(0.7.0) is for Effect 3 (effect ^3.22) and does not fit. TanStack Query:@tanstack/react-query5.107.1. - Bundle size, minified with
bun build --minify --target=browser, on top of what the page already loads for the client (effect's RPC client and server,ManagedRuntime,Stream,Schema, react-dom): atoms and their React binding add 35.3 kB (11.3 kB gzip); TanStack Query adds 43.9 kB (13.1 kB gzip). The atoms reuse theeffectalready on the page. - Suspense. Both have it:
useAtomSuspense(suspends whileInitial, optionally while refreshing; a failure is thrown to the error boundary) anduseSuspenseQuery. - Invalidation after a command and on
changes. Atoms:Reactivityinvalidates by key,Atom.withReactivityrefreshes an atom when its key is invalidated, and the subscription tochangesis itself an atom (aStream) that invalidates on every commit. TanStack:queryClient.invalidateQueriesfrom auseEffectover the async iterable. Equal in power; the atoms keep the subscription and the invalidation in one Effect program. - Typed errors. Atoms keep the error type in
AsyncResult<A, E>(here the client'sWorkflowClientError, whosecodenarrows itsparams). TanStack Query types errors through a globalRegisterdeclaration, one type for the whole application. - An application that already uses TanStack Query. It keeps its own
QueryClientfor its own data; the workflow's reads live in the provider's atom registry and refresh themselves onchanges, so the application never invalidates them. One thing it must not expect: the workflow's reads are not in its query cache (no shared devtools, noqueryClient.getQueryDataon them). Where it needs a workflow read inside its own query, it calls the promise facade (createWorkflowClient) in itsqueryFnand invalidates onuseChanges. AtomRpcwould put atoms directly on the RPC client, but itsServicebinds the protocol layer when the module is loaded; the provider takes a client at render time, so the atoms here are built per client over the facade.
Choice: Effect atoms (the brief's default). No blocker found: the binding exists for the pinned version, is the smaller of the two, and covers suspense, invalidation and typed errors.
The provider
import { createWorkflowClient } from "@sewdn/workflow-client";
import { WORKFLOW_COPY_EN, WorkflowProvider } from "@sewdn/workflow-react";
const client = createWorkflowClient({ ports, config }); // or a layer of the Effect client: client={layer}
<WorkflowProvider
client={client}
plugins={[]}
copy={WORKFLOW_COPY_EN}
actor={viewer}
ui={{ links, people, timeZone }}
>
<App />
</WorkflowProvider>;client: the facade (the host keeps and disposes it) or aLayer<WorkflowRpcClient>over any transport (the provider makes a facade from it and disposes it shortly after unmounting).plugins: the application'sWorkflowPlugin[], the same list the runtime is given (layerPlugins). The provider installs their engine parts on the page (installPlugins) and gives their UI parts to the components below.copy:WORKFLOW_COPY_EN,WORKFLOW_COPY_NL, or aWorkflowCopyof the application's own. The plugins' words join its catalog (withPluginCopy), souseCopy()words a plugin's refusal (plugin.refused) and a check's veto (command.vetoed) through the plugin's copy.actor: who acts when a command call names no one.ui:WorkflowUiPorts, each optional:links(stand-in: plain anchors),people(no stand-in:usePeoplethrows without it),documents(stand-in: none),timeZone(stand-in: the browser's),announce(stand-in: silent).
Each provider has its own atom registry and one subscription to the client's changes. Every commit (and the first
Subscribed, which covers commits made before the subscription stood) invalidates the reactivity key workflow,
and every read refreshes. Every command the provider gives invalidates it too when the call settles, success or
failure, so the read after a command does not wait for its change. A broken subscription is made again after a
second; a refused one (a server refuses changes to an external viewer) is not asked again: useLive() turns false
and reads refresh after own commands, on refresh, when the window regains focus and when the display clock
(ui.clock, useClock()) moves.
Hooks
| Hook | Gives |
| ------------------------------------------------------------------------------- | ----------------------------------------------------- |
| useWorld(options?), useSequence(options?), useRuns(query?, options?) | QueryState of the read |
| useRun(runId, options?), useOverview(…), usePhases(…) | QueryState, data undefined for no such run |
| useHistory(runId, options?), useTaskList(personId, options?) | QueryState of the lines / the person's work |
| useWorkflowQuery(ref, params, { viewer?, enabled? }) | QueryState of an engine query, gated, as the viewer |
| usePhaseTask, useStep, useStepOutlook, useFollowUps, useRunFollow | the run screens' engine queries, gated, as the viewer |
| useAdHocTasks, useAdHocTask, useGroups, useDefinitions, useVersions | the same |
| useReturnPreview(work), useRights(runId?) | a return's dry run; { can(capability), status } |
| useAsk() | (ref, params) => Promise: one fresh answer, now |
| useLive(), useClock() | whether changes streams; the display's clock |
| useCommand(name) | { execute, pending, executed, failure, reset } |
| usePluginCommand(plugin, name) | the same, typed by the plugin's command |
| usePluginQuery(plugin, name, params, { viewer?, enabled? }) | QueryState of the plugin's query, as the viewer |
| useChanges(listener?) | the last Change; the listener hears every one |
| useCopy() | refusal, finding, failure, history, trigger |
| usePlugins(), useActor() | the registered plugins, the provider's actor |
| useLinks(), usePeople(), useDocuments(), useTimeZone(), useAnnounce() | the UI ports, or their stand-ins |
Plugins
WorkflowPlugin<R> = { id, engine, runtime?, ui? }: the engine part (@sewdn/workflow-engine), the runtime part
(@sewdn/workflow-runtime, R the services its binding uses) and the UI part typed here, PluginUiPart: the
editor's inspectors (inspectors.triggers, inspectors.taskKinds), a run screen's taskViews and the forms'
controls, each keyed by the name of what it renders (the plugin's id is its own). A plugin package exports its parts
as subpaths (./engine, ./runtime, ./react), so a server never loads the UI.
A field control gets FieldControlProps: the field's pointer in the form's values (nested fields included, e.g.
/visits/1/site), the form's element id for it, label, description, required, value, onChange, schema,
enabled and errors. FieldControlFrame of @sewdn/workflow-forms draws the form's frame around it (label,
description, draft, revision, read-only text, the errors at the pointer): <FieldControlFrame {...props}
readOnlyText={…}>{(a11y) => <input {...a11y} />}</FieldControlFrame>.
WorkflowPluginsProvider (rendered by WorkflowProvider, usable alone where there is no client yet) installs the
engine parts and gives the list to usePlugins(), useTriggerInspector(ref), useTaskKindInspector(ref),
useTaskView(ref) and pluginControls(plugins), all by reference (<plugin>.<name>). Keep the list's identity
stable: a new list installs again.
QueryState<A> is { status: "loading" | "success" | "failure", data, failure, refreshing, refresh }; after a
failure data keeps the last answer. useCommand(name).execute(input, call?) never rejects: it resolves with
{ ok: true, executed } or { ok: false, failure }, where failure is the client's WorkflowClientError
(failure.kind === "refused" and failure.code narrow failure.params). call may give actor, commandId
(default: a fresh one per call; give the same id again to retry a call whose outcome is unknown), correlationId
and causationId.
Plugin data
A plugin's commands and queries are typed by its definition, the same object given to plugins and to the runtime:
const schedule = usePluginCommand(docketPlugin, "schedule");
const outcome = await schedule.execute({ meetingId, runId }); // { ok: true, executed } with executed.value.entryId
const meetings = usePluginQuery(docketPlugin, "meetings", { seriesId }); // QueryState of the query's resultusePluginCommand(plugin, name)behaves asuseCommand:execute(input, call?)never rejects, the actor defaults to the provider's, the command id to a fresh one. The input is checked by the command's schema before it is sent (client.invalid-request); a plugin's refusal isplugin.refused { command, ref, params }.usePluginQuery(plugin, name, params, options?)asks the query asoptions.viewer, by default the provider'sactor, so a runtime with a gate table (queryGates) answers what that person may see, and a query the gate closes fails withquery.not-found. Params made in render are compared by their JSON. Every commit refreshes it, as every read.- The engine's own hooks (
useWorld,useRuns, …) read the host-trusted typed reads, which no gate filters: a screen shown to external people reads throughuseWorkflowQueryor plugin queries, never through them. useWorkflowQuery(ref, params, options?)asks an engine query (workflow.runs,workflow.phases,workflow.commits, …ENGINE_QUERY_PARAMS) through the facade's gatedquery, asoptions.viewer(by default the provider's actor). Its params are typed byEngineQueryParams<R>and itsdatabyEngineQueryResult<R>of the runtime; a run that does not exist, or a query the gate closes, fails withquery.not-found.useDraft(versionId, options?)anduseDraftHistory(versionId, { after?, limit? }, options?)read a draft throughworkflow.draftandworkflow.draft-historyas the viewer: the version with the viewer's own undo and redo tops (data.undo.editis whatuseCommand("undoEdit")names), and the history oldest first, kept after the publish, whichuseCopy().draftLine(line, nameOf?)puts in words. A viewer without theworkflow.authorright getsquery.not-found. Every commit refreshes both, so another author's edit arrives as a new revision and line.- Every read hook takes
enabled(default true).enabled: falseholds the read back: it isloading, sends no request and is not refreshed by commits until it is enabled (a read that waits for a persona or a choice).
Failures and read states
failureFacts(failure) gives { code, field?, params } (the input field a refusal names). readState(query) gives
"loading", "not-found" (query.not-found: what does not exist, or what a gate keeps from the viewer), "error"
(any other failure with nothing to show) or undefined (data to show). useCopy().failure(failure) words any failure.
Links
useLinks() returns every member of WorkflowLinks: the application's, else a stock one over hash addresses
(stockHref: #/runs/<id>, #/tasks/ad-hoc/<id>, #/records/<plugin>/<type>/<id>, …) and page loads. Only Link
is required; a stock EntityLink or useOpenEntity uses the application's href when it gives one.
Testing
@sewdn/workflow-react/testing (tests and stories only): TestWorkflowProvider { genesis?, seed?, actor?, plugins?,
copy?, people?, ui?, config?, intercept?, onReady? } mounts a WorkflowProvider over a fresh runtime on the memory
adapter (the plugins' runtime parts are not bound). intercept holds a query loading or fails it (queries, by
reference), fails a command without sending it (commands, by name), or holds or refuses changes. Port fakes:
testPeople(persons), recordingLinks() (what was opened and navigated to), testClock(start).
Scripts
bun run typecheck
bun run test # vitest run (jsdom, React Testing Library)
bun run build # tsc -p tsconfig.build.json