Workflows

Reactive session and adapter reference

Session states and commands, the useInstancePreviews contract, and the WorkflowObserver interface and builder kit for custom adapters.

Early access

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. reason is model-ahead (the document needs a newer engine; upgrade @sanity/workflow-engine) or shape-violation (the stored document has the wrong shape; investigate it). Show that remediation instead of a spinner. ready is never true while invalid is 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 evaluation may 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

    false while the session is still synchronizing the instance, watched documents, and guards. A missing evaluation is a loading state only while evaluationError is undefined. Switching instance IDs clears the previous evaluation while the new instance synchronizes. true with an evaluation means the interface can render stages, activities, fields, and action verdicts.

  • evaluation

    WorkflowEvaluation | undefined

    The latest successful evaluation. undefined until the first one resolves, and reset when the instance ID changes. A later failure keeps the last value; check evaluationError before treating it as current.

  • guards

    readonly MutationGuardDoc[] | undefined

    The live guard list. undefined before the first successful guard read, and also when the guard stream is invalid, so check invalid and error before 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 filter failed for this actor and stage visit. Do not render it, not even as a disabled control. insight explains the filter.

  • automation

    triggered === true (disabledReason.kind === 'cascade-fired')

    The action declares when and only the cascade fires it; fireAction rejects it. Narrate what it will do from whenInsight instead of rendering a button.

  • button

    otherwise

    A caller-driven action. Enable it when allowed is true. Otherwise disable it and show disabledReason, 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 fetchInstancePreviews and listenInstanceChanges.

  • filter

    Omit<InstancesQueryFilter, 'limit' | 'before' | 'ids'>

    Instance filters such as definition, stage, and includeCompleted. It cannot set limit, before, or ids, because the hook derives them.

  • pageSize

    number

    Rows per page. Defaults to 500.

  • 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

    undefined until the first page lands, then newest-started first.

  • loading

    boolean

    true until the first page lands.

  • drained

    boolean

    Every matching page has landed, so counts over previews are 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-store invalid state.

    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 a null value, and an omitted key leaves the session waiting. Report ready only when every read has resolved. Instance, ancestor, and system.release documents read raw. Content documents pass through without validation. Build it with combineDocStores.

    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.guard documents, which the engine excludes from the observeDocs set. Subscribe one stream per resource and merge them with combineGuardStores; validate with validatedGuardsStore. Do not report a pending read as an empty list, and return the shared NO_GUARDS array 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 in loading, then resolves to {instances, unreadable}. Validate per row with validatedInstancesStore, so one refused row lands in unreadable without 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 with validatedPreviewPage.

    Parameters

    • query

      CompiledQuery

      From instancePreviewsQuery.

  • listenInstanceChanges({query, onEvent})(query, onEvent): () => void

    Subscribes to the instance-change feed from the engine's instanceChangesQuery and 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 startInstance without racing the Content Lake. Resolves once the write is committed. Delegate to the exported ensureDocumentExists(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 loading and resolve to ready, invalid, or error. A later successful emission clears either failure.
  • invalid means data arrived that the engine cannot interpret; error means no current value arrived. The instance and guard wrappers report a validation failure as the whole store's invalid state, while validatedInstancesStore validates each list row and returns {instances, unreadable} in a ready snapshot.
  • Keep resolved snapshots referentially stable between emissions, as useSyncExternalStore requires, including the shared NO_GUARDS identity for an empty guard list.
  • Normalize a nullish thrown value before putting it in error, so undefined always 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.

  • 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 loading until every resource is ready, dedupes and sorts by _id, and returns NO_GUARDS when empty.

  • 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 from initialValue. client needs fetch and createVersion.

  • 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.

  • Splits a dataset WorkflowResource into {projectId, dataset}. Throws for other resource types.

  • The datasets an instance's active guards can live in: the engine dataset plus each dataset the watch set names.

  • 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/observer implements every member on the App SDK stores. The same entry exports its leaf stores: sdkInstanceDocStore, sdkContentDocStore, sdkGuardStore, and sdkInstancesStore.
  • makeStudioObserver(sdk, {client, engineResource}) from @sanity/workflow-studio reuses makeSdkObserver and replaces ensureDocumentExists with a write through the Studio client.

Related

Visiting agent?

Was this page helpful?

Sanity logosanity.ioAll Systems Operational© Sanity 2026
Change site theme