Reusable UI components reference
Add assignment, date, member, and workflow-diagram controls to a custom Workflows interface.
Workflows provides reusable React components in two packages. @sanity/workflow-components contains assignment and date controls, timestamps, and status indicators. @sanity/workflow-diagram renders workflow stages and transitions. Both work in App SDK applications, Studio integrations, and other React hosts.
For every exported component, prop, and type, see the generated API reference for @sanity/workflow-components, @sanity/workflow-diagram, and @sanity/workflow-react.
These packages provide presentation, not an application framework. Your host supplies project members and workflow data, chooses which evaluated fields to render, and connects edits and actions through the reactive session.
Install the packages
Install the Workflows packages and the React, styled-components, and Sanity UI versions used by these examples:
npm install @sanity/workflow-components @sanity/workflow-diagram \
@sanity/workflow-engine @sanity/ui@^4.2.1 \
react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2pnpm add @sanity/workflow-components @sanity/workflow-diagram \
@sanity/workflow-engine @sanity/ui@^4.2.1 \
react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2yarn add @sanity/workflow-components @sanity/workflow-diagram \
@sanity/workflow-engine @sanity/ui@^4.2.1 \
react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2bun add @sanity/workflow-components @sanity/workflow-diagram \
@sanity/workflow-engine @sanity/ui@^4.2.1 \
react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2Keep all Workflows packages on one release. React, React DOM, and styled-components must each resolve to one shared copy in your application.
If your interface uses App SDK hooks, complete the App SDK installation before connecting these controls to live data.
Workflows components and diagrams use Sanity UI 4. Wrap your interface in its theme provider:
import {studioTheme, ThemeProvider} from '@sanity/ui'
<ThemeProvider theme={studioTheme}>
<WorkflowInterface />
</ThemeProvider>Components
Choose a component by the interaction your interface needs. Each table lists the props a host application sets for that component family.
Select people for personal assignments or select project roles to offer work to a group. If any person is assigned, role selections no longer put that task in other people’s lists. Store a role’s machine name, not its display title. Role aliases let people with another role qualify for an assignment without adding the task to their role group’s list.
Assignment badges
Use ActorBadge and ActorBadges to display stored user and role assignees. A badge never shows a raw user ID. A user the members list does not name reads as "Unknown user" with the ID in its tooltip, a robot token reads by its token label, and a robot without a label reads as "Automation". While members load, an unlisted user shows a name-sized placeholder; if loading failed, the user reads as "Couldn't load". Spread the useProjectMembers state into the vocabulary so it carries members, loading, and error, then add roles:
import {ActorBadges} from '@sanity/workflow-components'
<ActorBadges assignees={assignees} vocabulary={{...directory, roles}} />ActorBadge.assignee
Assignee
The user or role assignment to display.
ActorBadge.vocabulary
AssigneeVocabulary
Project members, loading and error state, role catalog, and optional robot-token members used to label the assignment.
ActorBadges.assignees
readonly Assignee[]
The assignments to display.
ActorBadges.vocabulary
AssigneeVocabulary
Project members, loading and error state, role catalog, and optional robot-token members used to label assignments.
Assignment stacks
Use AssigneeStack to display an assignment in a dense row. People appear as round avatars, roles as square avatars, and optional glyphs follow both. At most three slots are visible, including an overflow count. Your host supplies accessible labels and full names in surrounding or hover content.
import {AssigneeStack} from '@sanity/workflow-components'
<AssigneeStack members={assignedMembers} roles={assignedRoles} />members
readonly {id: string; displayName: string; imageUrl?: string; loginProvider?: string}[], optional
Resolved members to show as round avatars.
actors
readonly ActorDisplay[], optional
Resolved actors from
actorDisplayFor, stacked asActorAvatardraws them.roles
readonly MemberRole[]
Project roles shown as square avatars. The title supplies initials and the machine name supplies color. Your host supplies full-name tooltips and accessible labels.
glyphs
readonly {icon: ReactNode; key: string}[]
Optional trailing glyphs. They render after members and roles and remain visible when avatars overflow.
Actor names
Use the actor display to name whoever a stored actor or user ID belongs to. actorDisplayFor(directory, id) resolves the ID against the loaded members and optional robots to a person, robot, automation, unknown, unavailable, or pending display. ActorName renders one actor's face and name with a hover card, ActorNames renders several as inline text, and ActorFace, ActorAvatar, and ActorHintContent render the parts. The stored ID appears only in a single actor's hover card for an unknown, unavailable, robot, or automation actor.
import {ActorName, actorDisplayFor} from '@sanity/workflow-components'
<ActorName actor={actorDisplayFor(directory, actorId)} />actorDisplayFor reads a loaded member directory. To resolve one stored ID without loading the directory, for example in a script or a notification, App SDK applications can call sdkProjectUserDirectory(sdk, projectId).findById(id) from @sanity/workflow-sdk. The lookup never rejects; it returns one of three statuses:
status: 'resolved'
{status, user: SanityUser}
The ID belongs to a project member.
user.profile.displayNameis the name to show.status: 'missing'
{status}
The project has no user with this ID. Show it as an unknown user.
status: 'inaccessible'
{status, cause?}
The directory request failed or returned malformed data. Keep this distinct from a missing user, and let a later lookup retry.
import type {SanityInstance} from '@sanity/sdk'
import {sdkProjectUserDirectory} from '@sanity/workflow-sdk'
export async function actorLabel(
sdk: SanityInstance,
projectId: string,
actorId: string,
): Promise<string> {
const lookup = await sdkProjectUserDirectory(sdk, projectId).findById(actorId)
if (lookup.status === 'resolved') return lookup.user.profile.displayName
if (lookup.status === 'missing') return 'Unknown user'
return 'Could not load user'
}Member and role avatars
Use MemberAvatar for a project member and RoleAvatar for a project role. Missing member photos fall back to initials. Role avatars are square and use the role title when available. Your host supplies accessible labels and full-name tooltips for individual avatars and avatar groups.
import {MemberAvatar, MemberAvatarGroup} from '@sanity/workflow-components'
<MemberAvatar imageUrl={member.imageUrl} name={member.displayName} />
<MemberAvatarGroup members={members} />MemberAvatar.name
string
Display name used to derive initials. Supply an accessible label in the surrounding UI.
MemberAvatar.imageUrl
string | undefined
Optional profile image URL.
MemberAvatar.loginProvider
string | undefined
Optional sign-in provider badge. Google, GitHub, and saml-prefixed providers have marks; unrecognized providers render no badge.
MemberAvatar.size
AvatarSize | AvatarSize[] | undefined
Optional Sanity UI avatar size. Defaults to 0.
RoleAvatar.role
MemberRole
The project role to render. A direct host must wrap the avatar with its own tooltip and accessible name.
RoleAvatar.size
AvatarSize | AvatarSize[] | undefined
Optional Sanity UI avatar size.
MemberAvatarGroup.members
readonly MemberAvatarData[]
Member records with id, displayName, and optional imageUrl. MemberAvatarData is exported for consumers that supply these records.
MemberAvatarGroup.maxLength
number | undefined
Maximum stack length before overflow is collapsed. Defaults to 3.
Member picker
Use MemberPicker for choosing one project member.
import {MemberPicker} from '@sanity/workflow-components'
<MemberPicker
{...members}
onSelect={setMember}
selectedIds={selectedIds}
/>MemberPicker.members
readonly ProjectMember[]
Resolved project members available to select.
MemberPicker.loading
boolean
Shows the loading state.
MemberPicker.error
string | undefined
Shows the member-loading failure.
MemberPicker.selectedIds
ReadonlySet<string>
Account-global user IDs currently selected.
MemberPicker.onSelect
(member: ProjectMember | null) => void
Receives the selected member, or null for the unassigned row.
MemberPicker.unassignRow
boolean | undefined
Adds an unassigned row while the search is empty. Defaults to false.
Assignee picker
Use AssigneePicker for assignments that accept people and roles. Pass maxUsers={1} for a singular assignee field: selecting another person replaces the current person and keeps the selected roles. eligibleRoles limits new choices to people who qualify for those roles. Role rows show a count of eligible people.
This example starts with work offered to the editor role and allows one person to be selected. Replace editor with a role in your project. Supply directory from useProjectMembers(projectId) and, if present, roleAliases from the workflow definition returned by the engine. This example keeps selection in local React state; the field-editing examples on this page show how to commit it.
import {useState} from 'react'
import {
AssigneePicker,
type ProjectMembersState,
} from '@sanity/workflow-components'
import type {Assignee, WorkflowDefinition} from '@sanity/workflow-engine'
export function ReviewAssigneePicker({
directory,
roleAliases,
}: {
directory: ProjectMembersState
roleAliases?: WorkflowDefinition['roleAliases']
}) {
const [assignees, setAssignees] = useState<readonly Assignee[]>([
{type: 'role', role: 'editor'},
])
return (
<AssigneePicker
{...directory}
eligibleRoles={['editor']}
maxUsers={1}
onChange={setAssignees}
roleAliases={roleAliases}
value={assignees}
/>
)
}AssigneePicker.members
readonly ProjectMember[]
Resolved project members available to assign.
AssigneePicker.roles
readonly MemberRole[]
Project role catalog. An empty array falls back to roles held by loaded members.
AssigneePicker.loading
boolean
Shows the loading state.
AssigneePicker.error
string | undefined
Shows the member-loading failure.
AssigneePicker.value
readonly Assignee[]
Current user and role assignees.
AssigneePicker.onChange
(value: readonly Assignee[]) => void
Receives the complete next assignee value.
AssigneePicker.eligibleRoles
readonly string[] | undefined
Required project role names for new assignment choices. Existing selections remain visible and removable. Omit to offer all available people and roles.
AssigneePicker.roleAliases
RoleAliases | undefined
The definition’s normalized role aliases. They widen which people satisfy eligibleRoles and contribute to role-member counts; they do not change literal inbox ownership.
AssigneePicker.maxUsers
number | undefined
Set to 1 to replace the selected person while preserving selected roles. Omit to allow multiple people. Other numeric values do not limit selection.
Pickers place the current user first, then sort other people by display name. Search matches names, email addresses, role names, and role titles. Hovering a person shows their email, identity-provider badge, current-user status, and project roles. Use eligibleRoles and roleAliases to constrain new assignment choices. Continue to respect the evaluated field and action verdicts when committing changes.
A non-empty role catalog controls the offered roles, including roles with no holders. If the catalog is empty or unavailable, the picker uses member-held roles. A role already stored in the value remains visible and removable.
Date controls
Use DatePicker for selection only. ClearableDatePicker adds an explicit clear action.
import {ClearableDatePicker, DatePicker} from '@sanity/workflow-components'
<DatePicker onSelect={setDate} value={date} />
<ClearableDatePicker
clearLabel="Clear due date"
onClear={() => setDueDate(undefined)}
onPick={setDueDate}
value={dueDate}
/>DatePicker.value
Date | undefined
The selected value.
DatePicker.selectTime
boolean | undefined
Shows time controls when true. Defaults to false.
DatePicker.onSelect
(next: Date) => void
Receives each selected date.
ClearableDatePicker.value
Date | undefined
The selected value.
ClearableDatePicker.selectTime
boolean | undefined
Shows time controls when true. Defaults to false.
Label for the clear action.
ClearableDatePicker.onPick
(next: Date) => void
Receives a selected date.
ClearableDatePicker.onClear
() => void
Runs when the value is cleared.
Progress
Use ProgressBar to display a progress field. It does not edit the field.
import {ProgressBar} from '@sanity/workflow-components'
<ProgressBar label="Content import" value={62.5} />ProgressBar.value
number | null
Completion from 0 to 100. null renders an empty meter.
ProgressBar.label
string | undefined
Optional accessible name. Defaults to Progress.
clampProgress(value)
number
Clamps a number to the 0–100 display range.
progressCaption(value)
string
Formats a clamped value as a whole-number percentage.
Timestamps and workflow status
Use these components to show when work started and whether it has finished:
AgoStampdisplays a compact age and an absolute local timestamp on hover. Pass an ISO timestamp and update the caller-ownednowvalue; the component starts no timer. Invalid timestamps display a dash, and future timestamps display “just now.”ActivityStatusIcondisplays active, done, failed, or skipped activity status. Unknown values use a muted empty icon. Include a text label when the icon is the only status indicator.StartIncompleteBadgemarks a workflow whose start has not finished.
Pass an activity’s status, the workflow’s start timestamp, and its incomplete-start state from your host. This example renders them under the Sanity UI theme provider configured for the interface:
import {Flex, Text} from '@sanity/ui'
import {
ActivityStatusIcon,
AgoStamp,
StartIncompleteBadge,
} from '@sanity/workflow-components'
export function WorkflowStatus({
activityStatus,
startedAt,
startIncomplete,
now,
}: {
activityStatus: string
startedAt: string
startIncomplete: boolean
now: Date
}) {
return (
<Flex align="center" gap={3}>
<ActivityStatusIcon status={activityStatus} />
<Text>{activityStatus}</Text>
<AgoStamp at={startedAt} now={now} />
{startIncomplete && <StartIncompleteBadge />}
</Flex>
)
}To reuse whole tables inside Studio, see Embed tables in a custom Studio tool.
Supply project members
Member-aware components consume ProjectMembersState, which contains members, the project role catalog, and loading state. App SDK applications load it with useProjectMembers(projectId) from @sanity/workflow-sdk. If the role catalog cannot be read, the state carries an empty catalog and pickers offer the roles the loaded people hold. The result also lists the project’s robot-token members in robots; members lists people only, so a picker never offers a token. Pass the whole result as the badge vocabulary or the actorDisplayFor directory so an actor stamped by an API token reads by its token label.
A resolved ProjectMember.id is the account-global sanityUserId stored in user assignments. If the profile cannot supply that ID, the row retains its project membership ID. The engine rejects new assignments that still use an unresolved project ID.
ProjectMember.id
string
Account-global sanityUserId when resolved; otherwise the project membership ID. The engine rejects unresolved project IDs in new assignments.
Name shown by member controls.
ProjectMember.email
string | undefined
Optional email used by member search.
ProjectMember.imageUrl
string | undefined
Optional profile image URL.
ProjectMember.loginProvider
string | undefined
Optional sign-in provider used for display only.
providerTitle(provider)
string | undefined
Returns Google, GitHub, or SAML/SSO for recognized login-provider values; returns undefined for unknown values.
ProjectMember.isCurrentUser
boolean | undefined
Whether this row represents the person whose token loaded the project directory.
ProjectMember.roles
readonly MemberRole[]
Project roles held by the member. Each record carries the stored machine name and an optional display title.
MemberRole.name
string
Machine role name stored in assignee values and compared by the engine.
MemberRole.title
string | undefined
Project display title. Presentation falls back to the machine name when absent.
roleLabel(role)
string
Returns a role's display title or its machine name.
memberRoleFor(vocabulary, name)
MemberRole
Resolves a stored role name through the project catalog, then member-held roles.
Resolves a stored role name and returns its display label.
RoleVocabulary
Pick<ProjectMembersState, 'members' | 'roles'>
The member and role-catalog input used by role resolvers and assignee badges.
ProjectMembersState.members
readonly ProjectMember[]
Resolved project members.
ProjectMembersState.roles
readonly MemberRole[]
Project role catalog used by assignment controls.
ProjectMembersState.loading
boolean
Whether members are loading.
ProjectMembersState.error
string | undefined
Member-loading failure to display.
assignmentMatch(members, identity)(members, identity): AssignmentMatch: 'user' | 'role' | undefined
Reports whether the supplied identity holds the assignment directly or through a literal project role. Any direct user member takes precedence over every role route. Role aliases do not affect this match.
Parameters
members
readonly Assignee[]
The complete user-and-role assignment list.
identity
AssignmentIdentity
An object with the account-global userId and literal project roles.
roleMemberCount(args)(args.members, args.requiredRoles, args.roleAliases): number
Counts distinct people who can fulfill any supplied role. It includes literal and alias-based eligibility and deduplicates by account-global user ID.
Parameters
args.members
readonly ProjectMember[]
The loaded project member directory.
args.requiredRoles
readonly string[]
The project role names whose eligible people should be counted.
args.roleAliases
RoleAliases | undefined
The workflow definition’s normalized role aliases. Pass undefined when no aliases apply.
memberCountLabel(count): string
Formats a count as 0 members, 1 member, or 2 members.
Parameters
count
number
The number of distinct people.
Role titles are presentation data. An assignee value continues to store the machine role name, so changing a project role's title does not change persisted workflow data.
Headless integrations can import loadProjectRolesOrNone and ProjectRole from @sanity/workflow-sdk/project-users. The read needs sanity-project-roles: read and is cached per client and project. An unavailable catalog returns [] until the page reloads.
Pass the resolved state to any member-aware component. The component renders loading and error states from the same object.
This example loads the directory with useProjectMembers and passes it to a picker and badges, keeping the selection in local state:
import {Card, Stack, Text} from '@sanity/ui'
import {ActorBadges, AssigneePicker} from '@sanity/workflow-components'
import type {Assignee} from '@sanity/workflow-engine'
import {useProjectMembers} from '@sanity/workflow-sdk'
import {useState} from 'react'
export function ProjectMemberExample({projectId}: {projectId: string}) {
const memberState = useProjectMembers(projectId)
const [selected, setSelected] = useState<readonly Assignee[]>([])
return (
<Card aria-labelledby="assignment-heading" as="section" border padding={4} radius={3}>
<Stack gap={3}>
<Stack gap={2}>
<Text id="assignment-heading" size={2} weight="semibold">
Assign team members
</Text>
<Text muted size={1}>
Choose the project members or roles responsible for this work.
</Text>
</Stack>
<AssigneePicker {...memberState} onChange={setSelected} value={selected} />
{selected.length > 0 ? (
<Stack gap={2}>
<Text muted size={1} weight="medium">
Assigned to
</Text>
<ActorBadges assignees={selected} vocabulary={memberState} />
</Stack>
) : null}
</Stack>
</Card>
)
}Connect editable fields
Editable controls render values from session.evaluation.editableFields. Commit changes through session.editField so the engine preserves workflow history and consistency. The App SDK guide shows the complete pattern.
To store an assignment on the instance, the definition needs an assignees field with editable: true. Configure workflow fields shows the field type. This picker commits each change through the session and surfaces a rejected commit:
import {Card, Text} from '@sanity/ui'
import {AssigneePicker, type ProjectMembersState} from '@sanity/workflow-components'
import {errorMessage, type Assignee, type EditableFieldEvaluation} from '@sanity/workflow-engine'
import type {WorkflowSession} from '@sanity/workflow-sdk'
import {useState} from 'react'
type AssignmentField = EditableFieldEvaluation & {
type: 'assignees'
value: readonly Assignee[]
}
export function AssignmentPicker({
field,
members,
session,
}: {
field: AssignmentField
members: ProjectMembersState
session: Pick<WorkflowSession, 'editField'>
}) {
const [failure, setFailure] = useState<string>()
const change = async (next: readonly Assignee[]) => {
setFailure(undefined)
try {
await session.editField({field, mode: 'set', value: next})
} catch (cause) {
setFailure(errorMessage(cause))
}
}
return (
<>
<AssigneePicker {...members} onChange={change} value={field.value} />
{failure ? (
<Card padding={3} role="alert" tone="critical">
<Text>Could not update assignment: {failure}</Text>
</Card>
) : null}
</>
)
}Render a control for each editable field the evaluation returns. The wrappers belong to the application, not the component package. Add a branch for each other field type your interface edits:
import type {ProjectMembersState} from '@sanity/workflow-components'
import type {Assignee, EditableFieldEvaluation, WorkflowEvaluation} from '@sanity/workflow-engine'
import type {WorkflowSession} from '@sanity/workflow-sdk'
import {AssignmentPicker} from './AssignmentPicker'
type AssignmentField = EditableFieldEvaluation & {
type: 'assignees'
value: readonly Assignee[]
}
function isAssignmentField(field: EditableFieldEvaluation): field is AssignmentField {
return field.type === 'assignees' && Array.isArray(field.value)
}
export function WorkflowEditableFields({
evaluation,
members,
session,
}: {
evaluation: WorkflowEvaluation
members: ProjectMembersState
session: Pick<WorkflowSession, 'editField'>
}) {
return evaluation.editableFields.map((field) => {
const key = `${field.scope}:${field.activity ?? ''}:${field.name}`
if (isAssignmentField(field)) {
return <AssignmentPicker field={field} key={key} members={members} session={session} />
}
return null
})
}Render an enabled editor only when the evaluated field is editable. Surface rejected commits instead of assuming an optimistic edit succeeded.
Component input mapping
In an App SDK application, the props in the examples on this page come from these sources:
engine
Engine
Returned by
useWorkflowEnginefrom@sanity/workflow-sdk.instanceId
string
Selected from a row returned by the instance-list hooks, or supplied by application routing.
session
WorkflowSession
Returned by
useWorkflowSessionfor the selected instance.evaluation
WorkflowEvaluation
Read from
session.evaluationafter the session is ready.activity
ActivityEvaluation
One entry from
evaluation.currentStage.activities.action
ActionEvaluation
One entry from
activity.actions.field
EditableFieldEvaluation
One entry from
evaluation.editableFields.memberState
ProjectMembersState
Members, role catalog, and loading state returned by
useProjectMembers.fire
function
An application callback that awaits
session.fireActionand surfaces a rejected commit.projectId
string
The project ID from the application's
SanityAppconfiguration.onBack / onSelect
function
Application-owned navigation callbacks, such as an instance list that opens a detail view.
Render the workflow diagram
Pass the session’s WorkflowEvaluation to WorkflowDiagram. The pinned definition describes the graph, currentStage marks the active node, history draws the visited path, and evaluation supplies live explanations.
import {Card, Stack, Text} from '@sanity/ui'
import {WorkflowDiagram} from '@sanity/workflow-diagram'
import type {WorkflowEvaluation} from '@sanity/workflow-engine'
export function WorkflowDiagramRecipe({evaluation}: {evaluation: WorkflowEvaluation}) {
return (
<Card border padding={4} radius={3}>
<Stack gap={4}>
<Stack gap={2}>
<Text size={2} weight="semibold">
Workflow diagram
</Text>
<Text muted size={1}>
Current stage and visited path
</Text>
</Stack>
<WorkflowDiagram
currentStage={evaluation.instance.currentStage}
definition={evaluation.definition}
evaluation={evaluation}
explain
history={evaluation.instance.history}
key={evaluation.instance._id}
/>
</Stack>
</Card>
)
}definition
WorkflowDefinition
Complete workflow definition to render.
currentStage
string | undefined
Stage to highlight as current.
history
readonly HistoryEntry[] | undefined
Tones visited stages and traversed transitions.
gatedTransitions
readonly string[] | undefined
Transition names that should show a locked marker.
local
LocalView | undefined
Limits the graph to context around the current stage.
static
boolean | undefined
Disables pan, zoom, and zoom controls.
devMode
boolean | undefined
Shows machine names and raw conditions.
explain
boolean | undefined
Shows human-readable gate explanations.
evaluation
WorkflowEvaluation | undefined
Adds live verdicts when explain is enabled.
height
number | string | undefined
Canvas height, defaulting to 360. Without fill, a numeric height is a pixel ceiling and smaller graphs shrink the canvas. CSS strings and heights with fill enabled are used as supplied.
fill
boolean
Fill the parent’s width and use height as supplied. The initial fit centers the graph without enlarging it beyond 1:1. Defaults to false.
initialView
'fit' | 'actual-size', optional
How the diagram opens. The default
'fit'scales the whole workflow down to the canvas and never enlarges it beyond 1:1.'actual-size'opens at 1:1 and centers the current stage (or the initial stage) along any axis where the workflow overflows. Applied on mount only. Astaticdiagram always opens with'fit'.
The diagram uses color, line style, and opacity to distinguish run state. The current stage carries the accent color. Completed stages carry checkmarks. Traversed transitions are solid, while transitions not taken are dashed. Unvisited stages that can no longer be reached from the current stage fade with their transitions.
Hovering a stage restores its immediate neighborhood and animates dashed outgoing transitions toward their targets. Hovering a transition animates that transition. The animation is disabled when the user prefers reduced motion.
Diagram theming
WS_CARD_TOKENS maps diagram colors to the surrounding Sanity UI card. Use --ws-path to customize the traversed path.
If a wrapper using WS_CARD_TOKENS needs explicit typography, set --ws-font and --ws-font-weight on it or derive them from useTheme_v2().font.text.
Key the diagram by instance ID to reset the viewport when opening a different workflow. Ordinary updates preserve the reader’s pan and zoom.
Enable explain to show gate explanations. Pass the live evaluation to add current verdicts.
Instance list hooks
A session covers one instance. Use these hooks to discover which instances to show. useWorkflowInstances and useDocumentWorkflows come from @sanity/workflow-sdk and supply the store observer for you. useInstancePreviews comes from @sanity/workflow-react and takes an observer argument.
useWorkflowInstances({engine, filter?})
WorkflowInstanceList
A live, filterable list of full instances. Use it when the surface needs instance detail for a bounded set.
filternarrows bystage,definition, and more. WithoutincludeCompleted: true, it returns in-flight instances only.useDocumentWorkflows({engine, document})
WorkflowInstanceList
The in-flight instances that reference one document. Use it for a document banner.
documentis a global document reference URI.useInstancePreviews({engine, observer, filter?, pageSize?})
InstancePreviewList
A progressively hydrated list of reduced rows. Use it for an inbox, board, or dashboard that should not load every full instance.
WorkflowInstanceList.instances
readonly WorkflowInstance[] | undefined
Set only for a ready snapshot.
WorkflowInstanceList.loading
boolean
True while the snapshot is pending. An empty
instanceswithloading: falseand no error is a confirmed empty result.WorkflowInstanceList.unreadable
readonly InvalidDoc[]
Workflow documents this engine cannot read, skipped from
instancesand flagged here.WorkflowInstanceList.error
unknown
Set when the live read failed. Clears when the stream recovers.
This example counts the instances in review and the instances that reference one article:
import type {Engine} from '@sanity/workflow-engine'
import {useDocumentWorkflows, useWorkflowInstances} from '@sanity/workflow-sdk'
export function ReviewCounts({engine}: {engine: Engine}) {
// Every in-flight instance currently in stage `review`, live.
const inReview = useWorkflowInstances({engine, filter: {stage: 'review'}})
// The instances that involve this document, live. GDR URIs only.
const forDocument = useDocumentWorkflows({
engine,
document: 'dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID',
})
if (inReview.loading || forDocument.loading) return <p>Loading…</p>
return (
<p>
{inReview.instances?.length ?? 0} in review, {forDocument.instances?.length ?? 0} for this
article
</p>
)
}Build the observer for useInstancePreviews with makeSdkObserver:
import {useSanityInstance} from '@sanity/sdk-react'
import type {Engine} from '@sanity/workflow-engine'
import {useInstancePreviews} from '@sanity/workflow-react'
import {datasetResourceId} from '@sanity/workflow-react/observer'
import {makeSdkObserver} from '@sanity/workflow-sdk/observer'
import {useMemo} from 'react'
export function WorkflowDashboard({engine}: {engine: Engine}) {
const sdk = useSanityInstance()
const observer = useMemo(
() => makeSdkObserver(sdk, {engineResource: datasetResourceId(engine.workflowResource)}),
[sdk, engine],
)
const {previews, drained, unreadable, error} = useInstancePreviews({
engine,
observer,
filter: {includeCompleted: true},
})
if (error) return <p>Could not load workflows: {error}</p>
if (!previews) return <p>Loading workflows…</p>
return (
<>
<p>
{previews.length} workflows{drained ? '' : ' so far'}
</p>
{unreadable.length > 0 && <p>{unreadable.length} could not be read.</p>}
<ul>
{previews.map((preview) => (
<li key={preview._id}>
{preview.definition}: {preview.currentStage}
</li>
))}
</ul>
</>
)
}previews is undefined until the first page lands, and drained tells you whether a count over the list is a total or a minimum. A row carries no definition snapshot, so title what you render from the deployed catalog and fall back to raw names. See Instance previews for the paging and reconnect semantics.
Reactive session return contract
The hook takes engine and instanceId. Pass grantsFromPath as well when the definition's conditions use $can. It returns the current reactive state and the commands that preview or commit changes:
evaluation
WorkflowEvaluation | undefined
The latest WorkflowEvaluation that resolved successfully. It is undefined before the first success and resets when the instance ID changes. A later failed attempt leaves the last successful value in place.
ready
boolean
True after the instance, watched documents, and guards have synchronized. It is false while the session is invalid or a live read has failed. An evaluation failure does not change it.
invalid
InvalidDoc | undefined
Describes an engine-owned document that failed validation. Show remediation instead of continuing to render workflow controls.
error
unknown | undefined
The current observer failure. It clears when the live stream recovers.
evaluationError
unknown | undefined
The last evaluation failure. It clears after a successful evaluation attempt or when the instance ID changes. It does not change ready.
guards
readonly MutationGuardDoc[] | undefined
The live guard list. It is undefined before the first successful guard read or when that stream is invalid.
tick
() => Promise<OperationResult>
Re-evaluates and advances the instance through automatic actions and transitions, then commits the result.
fireAction
(args: {activity: string; action: string; params?: Record<string, unknown>}) => Promise<OperationResult>
Fires one named activity action with optional parameters and commits the result.
editField
(args: {field: EditableFieldEvaluation; mode?: EditMode; value?: unknown} | {target: EditFieldTarget; mode?: EditMode; value?: unknown}) => Promise<OperationResult>
Commits one declared editable-field operation. Call it at a deliberate editing boundary.
previewField
(args: {field: EditableFieldEvaluation; mode?: EditMode; value?: unknown} | {target: EditFieldTarget; mode?: EditMode; value?: unknown}) => void
Stages an in-memory field preview and recomputes the evaluation without writing history or persisted state.
discardFieldPreview
(fieldOrTarget?: EditableFieldEvaluation | EditFieldTarget) => void
Removes the preview for one field target, or every staged preview when no target is supplied.
Next steps
- Build a workflow interface with the App SDK: build the instance-list and task-session application around these controls.
- Fields: understand editable field types, scopes, and stored values.
- History and audit trail: use instance history when presenting the workflow’s visited path.
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?