Workflows

Reusable UI components

Add assignment, date, member, and workflow-diagram controls to a custom Workflows interface.

Workflows provides reusable React components in @sanity/workflows-ui. Its components subpath, @sanity/workflows-ui/components, contains assignment and date controls, timestamps, and status indicators. Its diagram subpath, @sanity/workflows-ui/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/workflows-ui/components, @sanity/workflows-ui/diagram, and @sanity/workflows-ui/react.

These packages render workflow data. They don’t load it or write it. Your application supplies the members and workflow data, chooses which evaluated fields to show, and sends 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/workflows-ui @sanity/workflows @sanity/ui@^4.2.1 \
  react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2

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

An assignment can name people, roles, or both:

  • Select a person to assign the work to them directly.
  • Select a role to offer the work to everyone who holds that role. Once anyone is assigned directly, the role no longer puts the work in other people’s lists.

Store a role’s machine name, such as editor, not its display title. A workflow definition can also declare role aliases. An alias lets people with another role qualify for the work, but it doesn’t add the work to that other role’s list.

Assignment badges

Use ActorBadge and ActorBadges to show stored user and role assignees. A badge never shows a raw user ID. Instead, it shows one of these labels:

  • A user that isn’t in the members list: “Unknown user”, with the ID in the tooltip.
  • A robot token: its token label, or “Automation” if it has no label.
  • A user while members are still loading: a placeholder the size of a name.
  • A user when loading members failed: “Couldn't load”.

Pass the badges a vocabulary object. The useProjectMembers result already holds the members, the role catalog, and loading state, so pass it as it is:

import {ActorBadges} from '@sanity/workflows-ui/components'

<ActorBadges assignees={assignees} vocabulary={directory} />
  • The user or role assignment to display.

  • ActorBadge.vocabulary

    AssigneeVocabulary

    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

    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/workflows-ui/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 as ActorAvatar draws them.

  • roles

    readonly MemberRole[]

    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 components to name whoever a stored actor or user ID belongs to. actorDisplayFor(directory, id) looks up the ID in the loaded members and the optional robots list. It returns one of these kinds: person, robot, automation, unknown, unavailable, or pending.

Pass the result to a component:

  • ActorName renders one actor’s face and name, with a hover card.
  • ActorNames renders several actors as inline text.
  • ActorFace, ActorAvatar, and ActorHintContent render the individual parts.

The stored ID appears only in the hover card for a single actor, and only when that actor is unknown, unavailable, a robot, or automation.

import {ActorName, actorDisplayFor} from '@sanity/workflows-ui/components'

<ActorName actor={actorDisplayFor(directory, actorId)} />

actorDisplayFor needs a loaded member directory. Sometimes you need to resolve one stored ID without loading the whole directory, for example in a script or a notification. In an App SDK application, call sdkProjectUserDirectory(sdk, projectId).findById(id) from @sanity/workflows-ui/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.displayName is the name to show.

  • 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/workflows-ui/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 member and RoleAvatar for a role. A member without a photo, or whose photo fails to load, shows their 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/workflows-ui/components'

<MemberAvatar imageUrl={member.imageUrl} name={member.displayName} />
<MemberAvatarGroup members={members} />
  • 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 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 member. Its list is announced to assistive technology as “Members”.

import {MemberPicker} from '@sanity/workflows-ui/components'

<MemberPicker
  {...members}
  onSelect={setMember}
  selectedIds={selectedIds}
/>

Assignee picker

Use AssigneePicker for assignments that accept both people and roles. These props shape what it offers:

  • maxUsers={1} fits a field that holds one person. Selecting another person replaces the current one and keeps the selected roles.
  • eligibleRoles limits new choices to people who qualify for those roles. Role rows show how many people qualify.

This example starts with the work offered to the editor role and allows one person to be selected. Replace editor with a role in your project. Pass directory from useProjectMembers(projectId). If the workflow definition the engine returns has roleAliases, pass those too. The example keeps the selection in local React state. To save it to the instance, see the field-editing example on this page.

import {useState} from 'react'
import {
  AssigneePicker,
  type ResourceMembersState,
} from '@sanity/workflows-ui/components'
import type {Assignee, WorkflowDefinition} from '@sanity/workflows'

export function ReviewAssigneePicker({
  directory,
  roleAliases,
}: {
  directory: ResourceMembersState
  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 ResourceMember[]

    Resolved members available to assign.

  • AssigneePicker.roles

    readonly MemberRole[]

    Role catalog of the directory’s resource. An empty array falls back to roles held by loaded members.

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

The pickers behave the same way for search and display:

  • The current user comes first. Other people are sorted by display name.
  • When two people share a display name, each row also shows the person’s email. If a person has no email, the row shows their sign-in provider.
  • Search matches names, email addresses, role names, and role titles.
  • Hovering a person shows their email, sign-in provider badge, whether they’re the current user, and their roles.

eligibleRoles and roleAliases only narrow what the picker offers. Before you save a change, still check the evaluated field and the action verdicts.

The role list comes from the project’s role catalog when the catalog has entries. It then includes roles nobody holds yet. If the catalog is empty or can’t be read, the picker lists the roles that loaded members hold. A role already stored in the value stays visible and can be removed.

Date controls

Use DatePicker for selection only. ClearableDatePicker adds an explicit clear action.

import {ClearableDatePicker, DatePicker} from '@sanity/workflows-ui/components'

<DatePicker onSelect={setDate} value={date} />

<ClearableDatePicker
  clearLabel="Clear due date"
  onClear={() => setDueDate(undefined)}
  onPick={setDueDate}
  value={dueDate}
/>

Progress

Use ProgressBar to display a progress field. It does not edit the field.

import {ProgressBar} from '@sanity/workflows-ui/components'

<ProgressBar label="Content import" value={62.5} />

Timestamps and workflow status

Use these components to show when work started and whether it has finished:

  • AgoStamp shows a short age, such as “5m ago”, and the full local time on hover. Pass an ISO timestamp and a now value. The component starts no timer, so update now yourself to keep the age current. An invalid timestamp shows a dash, and a future timestamp shows “just now”.
  • ActivityStatusIcon displays 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.
  • StartIncompleteBadge marks 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/workflows-ui/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 members

Components that show members take a ResourceMembersState object. It holds the members, the role catalog for the directory’s resource, and loading state. In an App SDK application, load it with useProjectMembers(projectId) from @sanity/workflows-ui/sdk.

The result has two lists of members:

  • members lists people only, so a picker never offers a robot token.
  • robots lists the project’s robot-token members.

Pass the whole result as the badge vocabulary or as the actorDisplayFor directory. Then an actor recorded by an API token shows its token label. If the role catalog can’t be read, the result has an empty catalog, and pickers offer the roles the loaded people hold.

ResourceMember.id is normally the person’s account-global sanityUserId, which is the ID user assignments store. If the profile can’t supply that ID, the row keeps the project membership ID instead. The engine rejects a new assignment that uses a project membership ID.

  • Account-global sanityUserId when resolved; otherwise the project membership ID. The engine rejects unresolved project IDs in new assignments.

  • Name shown by member controls.

  • ResourceMember.email

    string | undefined

    Optional email used by member search.

  • ResourceMember.imageUrl

    string | undefined

    Optional profile image URL.

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

  • ResourceMember.isCurrentUser

    boolean | undefined

    Whether this row represents the person whose token loaded the directory.

  • ResourceMember.roles

    readonly MemberRole[]

    Roles the member holds on the directory’s resource. Each record carries the stored machine name and an optional display title.

  • Machine role name stored in assignee values and compared by the engine.

  • MemberRole.title

    string | undefined

    The role’s display title in that resource. Presentation falls back to the machine name when absent.

  • Returns a role's display title or its machine name.

  • Resolves a stored role name through the resource’s role catalog, then member-held roles.

  • Resolves a stored role name and returns its display label.

  • RoleVocabulary

    Pick<ResourceMembersState, 'members' | 'roles'>

    The member and role-catalog input used by role resolvers and assignee badges.

  • ResourceMembersState.members

    readonly ResourceMember[]

    The members the host has read. While loading is true, a host that reads a long listing in pages can hold the people read so far; the pickers then list them with a “Loading more members…” footer.

  • ResourceMembersState.roles

    readonly MemberRole[]

    The resource’s assignable role catalog, including roles with no holders. Empty until the host has read the catalog, or when the host cannot supply one; assignment controls then offer member-held roles. It can fill in while loading is still true.

  • true while the host is still reading its members or role catalog; false once both reads finish or the member read fails.

  • ResourceMembersState.error

    string | undefined

    Member-loading failure to display. When it is set, even to an empty string, pickers show their error state instead of the member list.

  • assignmentMatch(members, identity)(members, identity): AssignmentMatch: 'user' | 'role' | undefined

    Reports whether the supplied identity holds the assignment directly or through a literal 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 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 ResourceMember[]

      The loaded member directory.

    • args.requiredRoles

      readonly string[]

      The 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 role's title does not change persisted workflow data.

Integrations without React can import loadProjectRolesOrNone and ProjectRole from @sanity/workflows-ui/sdk/project-users. Reading the catalog needs the sanity-project-roles: read permission. The result is cached per client and project. If the read fails, the function returns [], and keeps returning it 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/workflows-ui/components'
import type {Assignee} from '@sanity/workflows'
import {useProjectMembers} from '@sanity/workflows-ui/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 show the values in session.evaluation.editableFields. Save changes with session.editField, so the engine checks the change and records it in the instance history. For the complete pattern, see the App SDK guide.

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 {ActorBadges, AssigneePicker, type ResourceMembersState} from '@sanity/workflows-ui/components'
import {errorMessage, type Assignee, type EditableFieldEvaluation} from '@sanity/workflows'
import type {WorkflowSession} from '@sanity/workflows-ui/sdk'
import {useState} from 'react'

type AssignmentField = EditableFieldEvaluation & {
  type: 'assignees'
  value: readonly Assignee[]
}

export function AssignmentPicker({
  field,
  members,
  session,
}: {
  field: AssignmentField
  members: ResourceMembersState
  session: Pick<WorkflowSession, 'editField'>
}) {
  const [failure, setFailure] = useState<string>()
  if (!field.editable) {
    return field.value.length > 0 ? (
      <ActorBadges assignees={field.value} vocabulary={members} />
    ) : (
      <Text muted size={1}>
        —
      </Text>
    )
  }
  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}
        eligibleRoles={field.roles}
        onChange={change}
        roleAliases={field.roleAliases}
        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 {ResourceMembersState} from '@sanity/workflows-ui/components'
import type {Assignee, EditableFieldEvaluation, WorkflowEvaluation} from '@sanity/workflows'
import type {WorkflowSession} from '@sanity/workflows-ui/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: ResourceMembersState
  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 that Workflows components and recipes take come from these sources:

  • engine

    Engine

    Returned by useWorkflowEngine from @sanity/workflows-ui/sdk.

  • Selected from a row returned by the instance-list hooks, or supplied by application routing.

  • session

    WorkflowSession

    Returned by useWorkflowSession for the selected instance.

  • evaluation

    WorkflowEvaluation

    Read from session.evaluation after 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

    ResourceMembersState

    Members, role catalog, and loading state returned by useProjectMembers.

  • fire

    function

    An application callback that awaits session.fireAction and surfaces a rejected commit.

  • projectId

    string

    The project ID from the application's SanityApp configuration.

Render the workflow diagram

Pass the session’s WorkflowEvaluation to WorkflowDiagram. Each prop draws one part of the diagram:

  • definition draws the stages and transitions. It’s the definition version the instance is pinned to.
  • currentStage highlights the active stage.
  • history draws the path the instance has taken.
  • evaluation adds live explanations when explain is set.
import {Card, Stack, Text} from '@sanity/ui'
import {WorkflowDiagram} from '@sanity/workflows-ui/diagram'
import type {WorkflowEvaluation} from '@sanity/workflows'

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. A static diagram always opens with 'fit'.

  • direction

    DiagramDirection ('right' | 'down'), optional

    Which way the workflow flows from its initial stage. The default 'right' lays it out left to right; 'down' lays it out top to bottom.

  • visitedStyle

    VisitedStyle ('check' | 'filled'), optional

    How stages the instance has already been through are drawn, apart from the current stage. The default 'check' puts a check icon before the label. 'filled' draws them as filled pills without the icon, so a stage the instance returned to does not read as done; the current stage keeps the only accent outline. Needs history.

  • fitWidth

    FitWidth ({maxZoom?: number; minZoom?: number}), optional

    Zooms the workflow to the container's width and sizes the canvas to the workflow's height at that zoom. Pass {} for the default bounds: maxZoom 1, and minZoom 0.3, or 0.05 for a static diagram. It refits after every layout, so the canvas follows a workflow whose state changes, and on container resize until the reader pans or zooms. A workflow too wide to fit at minZoom makes the canvas wider than its container, so give the container overflow: 'auto' to scroll it. With fitWidth set, fill and initialView are ignored and height applies only before the first layout. Throws when a bound you pass is not positive or minZoom exceeds maxZoom.

  • onStageClick

    (stage: string) => void, optional

    Called with the stage's name when a stage is clicked, or activated with Enter or Space. When set, every stage is a focusable button labeled by its title.

To use the diagram as an app's main stage view, lay it out top to bottom, fit it to its container's width, and handle stage clicks. The container scrolls a workflow too wide to fit at minZoom:

import {WorkflowDiagram} from '@sanity/workflows-ui/diagram'
import type {WorkflowEvaluation} from '@sanity/workflows'

export function StageView({
  evaluation,
  onSelectStage,
}: {
  evaluation: WorkflowEvaluation
  onSelectStage: (stage: string) => void
}) {
  return (
    <div style={{overflow: 'auto'}}>
      <WorkflowDiagram
        currentStage={evaluation.instance.currentStage}
        definition={evaluation.definition}
        direction="down"
        fitWidth={{minZoom: 0.5}}
        history={evaluation.instance.history}
        key={evaluation.instance._id}
        onStageClick={onSelectStage}
        visitedStyle="filled"
      />
    </div>
  )
}

The diagram shows instance state with color, line style, and opacity:

  • The current stage has the accent color.
  • Completed stages have checkmarks.
  • Transitions the instance took are solid. Transitions it didn’t take are dashed.
  • Unvisited stages that the current stage can no longer reach fade out, 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.

Set explain to show why each transition is open or closed. Pass the live evaluation to include the current verdicts.

Instance list hooks

A session covers one instance. To find which instances to show, use these hooks:

  • useWorkflowInstances and useDocumentWorkflows come from @sanity/workflows-ui/sdk. They connect to the App SDK store for you.
  • useInstancePreviews comes from @sanity/workflows-ui/react. It takes an observer argument that connects it to your data store.

useWorkflowInstances and useDocumentWorkflows list completed and aborted instances unless the filter excludes them. filter is one GROQ filter expression, and params binds every $name it reads. Each hook ANDs the filter onto the scope it always applies: the instance type, the engine’s partition, and, for useDocumentWorkflows, the document match. A filter can narrow the list but never widen it.

The filter runs against each stored sanity.workflow.instance document. Fields it can read include definition, currentStage, startedAt, completedAt, abortedAt, lastChangedAt, fields, and stages. An aborted instance has completedAt as well as abortedAt, so filter: '!defined(completedAt)' lists in-flight instances only, and filter: 'defined(completedAt)' lists finished ones. Workflow instance document describes each field.

The hook throws a ContractViolationError during render, so the error reaches the nearest error boundary. It throws when:

  • filter is not one valid GROQ expression.
  • params uses a name the engine binds for itself, listed in INSTANCES_QUERY_RESERVED_PARAMS from @sanity/workflows.
  • filter reads a parameter that params does not bind.
  • You pass params without a filter.

This example counts the in-flight instances in the review stage and the finished (completed or aborted) instances that reference one article:

import type {Engine} from '@sanity/workflows'
import {useDocumentWorkflows, useWorkflowInstances} from '@sanity/workflows-ui/sdk'

export function ReviewCounts({engine}: {engine: Engine}) {
  // Every in-flight instance currently in stage `review`, live.
  const inReview = useWorkflowInstances({
    engine,
    filter: 'currentStage == $stage && !defined(completedAt)',
    params: {stage: 'review'},
  })

  // The finished (completed or aborted) instances that involve this document, live. GDR URIs only.
  const finished = useDocumentWorkflows({
    engine,
    document: 'dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID',
    filter: 'defined(completedAt)',
  })

  if (inReview.loading || finished.loading) return <p>Loading…</p>
  return (
    <p>
      {inReview.instances?.length ?? 0} in review, {finished.instances?.length ?? 0} finished for
      this article
    </p>
  )
}

Build the observer for useInstancePreviews with makeSdkObserver:

import {useSanityInstance} from '@sanity/sdk-react'
import type {Engine} from '@sanity/workflows'
import {useInstancePreviews} from '@sanity/workflows-ui/react'
import {observerResource} from '@sanity/workflows-ui/react/observer'
import {makeSdkObserver} from '@sanity/workflows-ui/sdk/observer'
import {useMemo} from 'react'

export function WorkflowDashboard({engine}: {engine: Engine}) {
  const sdk = useSanityInstance()
  const observer = useMemo(
    () => makeSdkObserver(sdk, {engineResource: observerResource(engine.workflowResource)}),
    [sdk, engine],
  )
  const {previews, drained, unreadable, error} = useInstancePreviews({engine, observer})

  if (error) return <p>Could not load workflows: {error}</p>
  if (!previews) return <p>Loading workflows…</p>

  const inFlight = previews.filter((preview) => preview.completedAt === undefined)
  return (
    <>
      <p>
        {inFlight.length} in progress{drained ? '' : ' so far'}
      </p>
      {unreadable.length > 0 && <p>{unreadable.length} could not be read.</p>}
      <ul>
        {inFlight.map((preview) => (
          <li key={preview._id}>
            {preview.definition}: {preview.currentStage}
          </li>
        ))}
      </ul>
    </>
  )
}

previews is undefined until the first page of results arrives or a fetch fails. After a failed first fetch it is an empty array, so check error first, as the example does. While drained is false, more pages are still loading, so a count of previews is a minimum, not a total. A preview row has the definition name in definition but not the definition’s title, so get display titles from the deployed definitions and fall back to the name. For paging and reconnect behavior, see Instance previews.

Reactive session return contract

useWorkflowSession takes engine and instanceId. The deprecated grantsFromPath option has no effect, because the engine reads the caller’s grants for $can from its workflow resource. The hook returns the current state and the commands that preview or save 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

Visiting agent?

Was this page helpful?

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