Reactive session and adapter reference
Session states and commands, the useInstancePreviews contract, and the WorkflowObserver interface and builder kit for custom adapters.
Early access
Workflows is in early access, built in public. Read How early access works before you rely on it.
This page lists the contracts of the reactive session in @sanity/workflow-react and of the store adapters that drive it: session states, session commands, the instance-preview hook, and the WorkflowObserver interface a custom adapter implements. For how the session works, see The reactive session. For the generated API docs, see `@sanity/workflow-react` on reference.sanity.io.
Session
useWorkflowSession returns a WorkflowSession. Adapters re-export it bound to their observer: @sanity/workflow-sdk and @sanity/workflow-studio take {engine, instanceId, grantsFromPath?}. The core hook in @sanity/workflow-react also takes observer. UI components lists the full return type.
Session states
Check these session fields in this order before rendering. invalid, error, and evaluationError are independent optional fields; ready is a boolean.
invalid
InvalidDoc | undefined
An engine-owned document, the instance or a guard, failed read validation.
reasonismodel-ahead(the document needs a newer engine; upgrade@sanity/workflow-engine) orshape-violation(the stored document has the wrong shape; investigate it). Show that remediation instead of a spinner.readyis nevertruewhileinvalidis set. Clears when a later emission validates.error
unknown | undefined
An observer read failed. The session is not ready until that stream recovers, and the state clears when it does. The last
evaluationmay still be present, so do not render it as current.evaluationError
unknown | undefined
The last evaluation attempt failed. Render it before treating a missing evaluation as loading. Clears after a successful attempt or when the instance ID changes. It does not change
ready.ready
boolean
falsewhile the session is still synchronizing the instance, watched documents, and guards. A missing evaluation is a loading state only whileevaluationErrorisundefined. Switching instance IDs clears the previous evaluation while the new instance synchronizes.truewith anevaluationmeans the interface can render stages, activities, fields, and action verdicts.evaluation
WorkflowEvaluation | undefined
The latest successful evaluation.
undefineduntil the first one resolves, and reset when the instance ID changes. A later failure keeps the last value; checkevaluationErrorbefore treating it as current.guards
readonly MutationGuardDoc[] | undefined
The live guard list.
undefinedbefore the first successful guard read, and also when the guard stream is invalid, so checkinvalidanderrorbefore rendering a spinner.
Session commands
tick
() => Promise<OperationResult>
Reevaluates the instance against the held content and commits any cascade through the engine.
fireAction
(args: {activity, action, params?}) => Promise<OperationResult>
Fires one caller-driven action and commits through the engine.
editField
(args: {field | target, mode?, value?}) => Promise<OperationResult>
Commits one edit of a declared editable field: a history entry, a guard refresh, and transition evaluation, written under a revision check. Call it at a deliberate boundary (blur, Enter, Save) for free text; pickers can commit on change. When it settles it drops that target's previews: success shows the reloaded value, failure reverts.
previewField
(args: {field | target, mode?, value?}) => void
Stages an in-memory preview. The next evaluation projects the previewed value and the advisory verdicts derived from it. Stage, activity statuses, and history stay committed. Never persisted.
discardFieldPreview
(fieldOrTarget?) => void
Drops the staged previews for one field or target, or all of them when called without an argument. The next evaluation returns to the committed value.
After a command settles, the session evaluates the committed result immediately instead of waiting for the observer to echo the write.
Action rendering
Each action in evaluation.currentStage.activities[].actions carries its verdict. actionRendering(action) from @sanity/workflow-engine returns the rendering below. See Evaluation insights for the explanation contract.
absent
disabledReason.kind === 'filter-failed'
The action's
filterfailed for this actor and stage visit. Do not render it, not even as a disabled control.insightexplains the filter.automation
triggered === true (disabledReason.kind === 'cascade-fired')
The action declares
whenand only the cascade fires it;fireActionrejects it. Narrate what it will do fromwhenInsightinstead of rendering a button.button
otherwise
A caller-driven action. Enable it when
allowedistrue. Otherwise disable it and showdisabledReason, which names the first gate that failed.
Instance previews
A preview is a reduced instance row (WorkflowInstancePreview) for list and dashboard surfaces: current stage, list-relevant fields, open activities, and lifecycle timestamps, without the definition snapshot or the audit history. useInstancePreviews in @sanity/workflow-react holds a live, progressively loaded set of them. It takes an engine and a store observer: @sanity/workflow-studio wraps it as useWorkflowInstancePreviews with the Studio observer, and an App SDK application builds an observer with makeSdkObserver from @sanity/workflow-sdk/observer. Instance list hooks has a worked example.
import {useInstancePreviews} from '@sanity/workflow-react'
const {previews, loading, drained, unreadable, error} = useInstancePreviews({
engine,
observer,
filter: {includeCompleted: true},
pageSize: 500,
})Arguments
Requiredengine
Engine
The engine whose partition the list reads.
Requiredobserver
WorkflowObserver
The adapter observer. It supplies
fetchInstancePreviewsandlistenInstanceChanges.filter
Omit<InstancesQueryFilter, 'limit' | 'before' | 'ids'>
Instance filters such as
definition,stage, andincludeCompleted. It cannot setlimit,before, orids, because the hook derives them.pageSize
number
Rows per page. Defaults to
500.interPageDelayMs
number
Pause between pages. Defaults to
0. A delay only helps when watching pages arrive one at a time in a development harness; leave it unset in production.
Return value: InstancePreviewList
previews
readonly WorkflowInstancePreview[] | undefined
undefineduntil the first page lands, then newest-started first.loading
boolean
trueuntil the first page lands.drained
boolean
Every matching page has landed, so counts over
previewsare totals. Before that, a count is a minimum.unreadable
readonly InvalidDoc[]
Rows this engine cannot read, flagged rather than silently dropped. Render them explicitly.
error
string | undefined
Set when a fetch failed. Pages that already landed are kept. Render it explicitly.
The hook owns paging and refresh. It drains the partition page by page, then listens to the instance-change feed and refetches each changed row by ID. When the feed reconnects after a failure it emits a reset, and the hook drains the partition again so additions, edits, and deletions missed during the gap all land.
Adapter contract
@sanity/workflow-react is store-agnostic. An adapter connects it to a reactive document store by implementing WorkflowObserver from @sanity/workflow-react/observer: four useSyncExternalStore-shaped reads, two instance-preview methods, and one write. Build another adapter only when a host or data layer other than Sanity Studio or the App SDK must drive the session. Pass the completed observer to the hooks from @sanity/workflow-react.
WorkflowObserver
Every member is required. TypeScript reports a missing member at compile time, and an incomplete JavaScript adapter fails when the hook that needs it runs.
observeInstance(instanceId)(instanceId): DocStore<WorkflowInstance | null>
The instance document. Wrap the raw store in
validatedInstanceStore, which reports model-gate and shape failures as the whole-storeinvalidstate.Parameters
instanceId
string
The instance document ID.
observeDocs(documents, perspective)(documents, perspective): DocStore<ReadonlyMap<string, SanityDocument | null>>
Every document the instance's conditions read, under the supplied perspective. Key each entry by the requested document's full
globalDocumentId; a resolved missing document has anullvalue, and an omitted key leaves the session waiting. Reportreadyonly when every read has resolved. Instance, ancestor, andsystem.releasedocuments read raw. Content documents pass through without validation. Build it withcombineDocStores.Parameters
documents
SubscriptionDocument[]
The watch set from the engine.
perspective
WorkflowPerspective | undefined
The read perspective for content documents.
observeGuards({instanceId, resources, sharedIds?})(instanceId, resources, sharedIds): DocStore<readonly MutationGuardDoc[]>
The instance's live
temp.system.guarddocuments, which the engine excludes from theobserveDocsset. Subscribe one stream per resource and merge them withcombineGuardStores; validate withvalidatedGuardsStore. Do not report a pending read as an empty list, and return the sharedNO_GUARDSarray for a resolved-empty snapshot.Parameters
instanceId
string
The instance whose guards to watch.
resources
readonly DatasetResourceId[]
The engine dataset plus each dataset an observed subject lives in, from
guardResourcesFor.sharedIds
readonly string[]
The IDs of every co-mounted session, so the adapter can run one set-shaped query per resource. Must include
instanceId; an adapter rejects the call otherwise. The returned stream still holds only this instance's guards.
observeInstances(query)(query): DocStore<ObservedInstances>
A live instance-list read against the engine's workflow resource, using a query from the engine's
instancesQuery. Starts inloading, then resolves to{instances, unreadable}. Validate per row withvalidatedInstancesStore, so one refused row lands inunreadablewithout failing the list.Parameters
query
CompiledQuery
From
instancesQuery.
fetchInstancePreviews(query)(query): Promise<readonly unknown[]>
One-shot fetch of one preview page from the engine's
instancePreviewsQuery. Returns raw rows; the hook parses them withvalidatedPreviewPage.Parameters
query
CompiledQuery
From
instancePreviewsQuery.
listenInstanceChanges({query, onEvent})(query, onEvent): () => void
Subscribes to the instance-change feed from the engine's
instanceChangesQueryand returns the unsubscribe function. Hold one upstream listener per feed however many consumers subscribe. A listener error never throws: reconnect with backoff, then emit{transition: 'reset'}after the connection is restored so consumers refetch pages that may have changed during the gap.Parameters
query
CompiledQuery
From
instanceChangesQuery.onEvent
(event: InstanceChangeEvent) => void
Receives
{id, transition: 'appear' | 'update' | 'disappear'}or{transition: 'reset'}.
ensureDocumentExists(args)(args.documentId, args.type, args.releaseId, args.initialValue): Promise<void>
The adapter's one write: makes a subject document exist where the engine's field hydration reads it, so a start flow can call it and then
startInstancewithout racing the Content Lake. Resolves once the write is committed. Delegate to the exportedensureDocumentExists(client, args).Parameters
args.documentId
string
Bare (published) document ID.
args.type
string
The document
_type, used when a new representation is created.args.releaseId
string
Set when the start targets a Content Release.
args.initialValue
Record<string, unknown>
Content for a new document. Content Lake-owned keys are stripped.
DocStore and ObserverState
type ObserverState<T> =
| {status: 'loading'}
| {status: 'ready'; value: T}
| {status: 'invalid'; invalid: InvalidDoc}
| {status: 'error'; error: ObserverError}
interface DocStore<T> {
subscribe: (onChange: () => void) => () => void
getSnapshot: () => ObserverState<T>
}Rules every store follows:
- Start in
loadingand resolve toready,invalid, orerror. A later successful emission clears either failure. invalidmeans data arrived that the engine cannot interpret;errormeans no current value arrived. The instance and guard wrappers report a validation failure as the whole store'sinvalidstate, whilevalidatedInstancesStorevalidates each list row and returns{instances, unreadable}in areadysnapshot.- Keep resolved snapshots referentially stable between emissions, as
useSyncExternalStorerequires, including the sharedNO_GUARDSidentity for an empty guard list. - Normalize a nullish thrown value before putting it in
error, soundefinedalways means no error.
Builder kit exports
Import these from @sanity/workflow-react/observer:
validatedInstanceStore(store)
DocStore<WorkflowInstance | null>
Validates the instance stream (model gate, then shape parse).
validatedGuardsStore(store)
DocStore<readonly MutationGuardDoc[]>
Validates a merged guard list as a whole: one malformed guard fails the list. An empty list passes through by reference.
validatedInstancesStore(store)
DocStore<ObservedInstances>
Validates an instance list per row into
{instances, unreadable}.validatedPreviewPage(rows)
{previews, unreadable}
Parses one fetched preview page per row.
mapSnapshot(store, map)
DocStore<Out>
Derives a memoized snapshot from a store's ready value; a thrown error becomes
invalid.combineDocStores(entries)
DocStore<ReadonlyMap<string, SanityDocument | null>>
Combines per-document stores into one map keyed by each entry's
key.combineGuardStores(stores)
DocStore<readonly MutationGuardDoc[]>
Merges per-resource guard stores. Stays
loadinguntil every resource is ready, dedupes and sorts by_id, and returnsNO_GUARDSwhen empty.ensureDocumentExists(client, args)
Promise<void>
The shared implementation behind
WorkflowObserver.ensureDocumentExists. It writes nothing when a visible representation exists; it creates the release version from a draft when the start is release-bound and only a draft exists; otherwise it creates the draft or version frominitialValue.clientneedsfetchandcreateVersion.classifyRef(ref, mounted)
'mounted-dataset' | 'foreign-resource'
Whether a watched reference can be read through the store mounted on
mounted. Never read a foreign reference from the mounted store.datasetResourceId(resource)
DatasetResourceId
Splits a dataset
WorkflowResourceinto{projectId, dataset}. Throws for other resource types.guardResourcesFor(engineResource, documents)
DatasetResourceId[]
The datasets an instance's active guards can live in: the engine dataset plus each dataset the watch set names.
sameDataset(a, b)
boolean
Whether two dataset resources address the same project and dataset.
A memo rebuilt only when a dependency changes by identity. Use it to keep store identities stable across renders.
NO_GUARDS
readonly MutationGuardDoc[]
The shared resolved-empty guard list.
isInvalidDoc(value)
value is InvalidDoc
Type guard for an
InvalidDoc.
The subpath also exports the types WorkflowObserver, DocStore, ObserverState, ObserverError, ObservedDoc, ObservedInstance, ObservedInstances, ObservedGuards, InstanceChangeEvent, InvalidDoc, DatasetResourceId, RefRoute, EnsureDocumentClient, EnsureDocumentExistsArgs, CompiledQuery, and MutationGuardDoc.
Reference implementations
Two shipped observers implement this contract. Read them in your installed packages as worked examples:
makeSdkObserver(sdk, {engineResource})from@sanity/workflow-sdk/observerimplements every member on the App SDK stores. The same entry exports its leaf stores:sdkInstanceDocStore,sdkContentDocStore,sdkGuardStore, andsdkInstancesStore.makeStudioObserver(sdk, {client, engineResource})from@sanity/workflow-studioreusesmakeSdkObserverand replacesensureDocumentExistswith a write through the Studio client.
Related
- `@sanity/workflow-react` on reference.sanity.io: generated API docs for every export.
- The reactive session: how the session stays current and why its verdicts are advisory.
- Build a workflow interface with the App SDK: build an application with the shipped adapter.
- Engine reference: the engine methods the session and adapters call.
Visiting agent?
Workflows includes an MCP server for inspecting, operating, authoring, validating, and deploying workflows. Ask your human to set up the MCP server.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?