> For AI agents: the complete Sanity documentation index is available at [https://www.sanity.io/docs/llms.txt](https://www.sanity.io/docs/llms.txt).

# Reactive session and adapter reference

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

> [!WARNING]
> Early access
> Workflows is in early access, built in public. Read [How early access works](https://www.sanity.io/docs/workflows/prerelease) before you rely on it.



This page lists the contracts of the reactive session in `@sanity/workflows-ui/react` and of the store adapters that supply its data: 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](https://www.sanity.io/docs/workflows/reactive-session). For the generated API docs, see [`@sanity/workflows-ui/react` on reference.sanity.io](https://reference.sanity.io/_sanity/workflow-react/).

## Session

`useWorkflowSession` returns a `WorkflowSession`. Adapters re-export it bound to their observer: `@sanity/workflows-ui/sdk` and `@sanity/workflows-ui/studio` take `{engine, instanceId}`. The core hook in `@sanity/workflows-ui/react` also takes `observer`. [UI components](https://www.sanity.io/docs/workflows/ui-components) lists the full return type.

### Session states

Check these session fields in this order before rendering. `invalid`, `error`, and `evaluationError` are independent fields. Each is always present, and is `undefined` when there's nothing to report. `ready` is a boolean.

#### Properties

**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/workflows) 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

#### Properties

**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. A target with a row key edits one row of an array field. A key that no longer names exactly one stored row rejects with ContractViolationError and writes nothing. 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. Previews of different row keys of one field stage side by side. A row key the held list no longer has stages nothing.

**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/workflows` returns the rendering below. See [Evaluation insights](https://www.sanity.io/docs/workflows/evaluation-insights) for the explanation contract.

#### Properties

**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 engine fires it, during a cascade; 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/workflows-ui/react` holds every instance in the partition, completed ones included, as a live, progressively loaded set. To narrow the list, filter the returned previews in your component. It takes an engine and a store observer: `@sanity/workflows-ui/studio` wraps it as `useWorkflowInstancePreviews` with the Studio observer, and an App SDK application builds an observer with `makeSdkObserver` from `@sanity/workflows-ui/sdk/observer`. [Instance list hooks](https://www.sanity.io/docs/workflows/ui-components) has a worked example.

Call it inside a React component, with an `engine` and an `observer` in scope:

```typescript
import {useInstancePreviews} from '@sanity/workflows-ui/react'

const {previews, loading, drained, unreadable, error} = useInstancePreviews({
  engine,
  observer,
})
```

### Arguments

#### Properties

**engine** (Engine, required)

The engine whose partition the list reads.

**observer** (WorkflowObserver, required)

The adapter observer. It supplies fetchInstancePreviews and listenInstanceChanges.

**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

#### Properties

**previews** (readonly WorkflowInstancePreview[] | undefined)

undefined until the first page lands or a fetch fails, then newest-started first. After a failed first fetch it is an empty array, so check error first.

**loading** (boolean)

true until the first page lands or a fetch fails.

**drained** (boolean)

Every page in the partition 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 handles paging and refresh. It loads every page of previews in the partition, fetching pages until one comes back short, and from the start 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 loads every page again so additions, edits, and deletions missed during the gap all land.

## Adapter contract

`@sanity/workflows-ui/react` is store-agnostic. An adapter connects it to a reactive document store by implementing `WorkflowObserver` from `@sanity/workflows-ui/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](https://www.sanity.io/docs/workflows/studio-plugin) or [the App SDK](https://www.sanity.io/docs/workflows/app-sdk) must supply the session's data. Pass the completed observer to the hooks from `@sanity/workflows-ui/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

```typescript
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/workflows-ui/react/observer`:

#### Properties

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

**datasetResourceId(resource)** (DatasetResourceId)

Splits a dataset WorkflowResource into {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.

**useKeyed(deps, create)** (T)

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/workflows-ui/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/workflows-ui/studio` reuses `makeSdkObserver` and replaces `ensureDocumentExists` with a write through the Studio client.

## Related

- [`@sanity/workflows-ui/react` on reference.sanity.io](https://reference.sanity.io/_sanity/workflow-react/): generated API docs for every export.
- [The reactive session](https://www.sanity.io/docs/workflows/reactive-session): how the session stays current and why its verdicts are advisory.
- [Build a workflow interface with the App SDK](https://www.sanity.io/docs/workflows/app-sdk): build an application with the shipped adapter.
- [Engine reference](https://www.sanity.io/docs/workflows/engine): the engine methods the session and adapters call.

> [!NOTE]
> Visiting agent?
> Workflows has MCP tools that let an agent inspect, operate, author, validate, and deploy workflows. An agent host embeds these tools. Ask the person you work for whether your host [includes the Workflows tools](https://www.sanity.io/docs/workflows/mcp).



