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

# 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](https://reference.sanity.io/_sanity/workflow-components/), [@sanity/workflows-ui/diagram](https://reference.sanity.io/_sanity/workflow-diagram/), and [@sanity/workflows-ui/react](https://reference.sanity.io/_sanity/workflow-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**

```shell
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
```

**pnpm**

```shell
pnpm add @sanity/workflows-ui @sanity/workflows @sanity/ui@^4.2.1 \
  react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2
```

**yarn**

```shell
yarn add @sanity/workflows-ui @sanity/workflows @sanity/ui@^4.2.1 \
  react@^19.2.7 react-dom@^19.2.7 styled-components@^6.4.2
```

**bun**

```shell
bun add @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](https://www.sanity.io/docs/workflows/app-sdk) before connecting these controls to live data.

Workflows components and diagrams use Sanity UI 4. Wrap your interface in its theme provider:

```tsx
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:

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

<ActorBadges assignees={assignees} vocabulary={directory} />
```

#### Properties

**ActorBadge.assignee** (Assignee)

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.

```tsx
import {AssigneeStack} from '@sanity/workflows-ui/components'

<AssigneeStack members={assignedMembers} roles={assignedRoles} />
```

#### Properties

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

```tsx
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:

#### Properties

**status: 'resolved'** ({status, user: SanityUser})

The ID belongs to a project member. user.profile.displayName is 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.

**src/actorLabel.ts**

```typescript
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.

```tsx
import {MemberAvatar, MemberAvatarGroup} from '@sanity/workflows-ui/components'

<MemberAvatar imageUrl={member.imageUrl} name={member.displayName} />
<MemberAvatarGroup members={members} />
```

#### Properties

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

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

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

#### Properties

**MemberPicker.members** (readonly ResourceMember[])

Resolved 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: ResourceMember | 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 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.

**src/ReviewAssigneePicker.tsx**

```tsx
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}
    />
  )
}
```

#### Properties

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

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

```tsx
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}
/>
```

#### Properties

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

**ClearableDatePicker.clearLabel** (string)

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.

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

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

#### Properties

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

- `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:

**src/WorkflowStatus.tsx**

```tsx
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](https://www.sanity.io/docs/workflows/studio-plugin).

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

#### Properties

**ResourceMember.id** (string)

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

**ResourceMember.displayName** (string)

Name shown by member controls.

**ResourceMember.email** (string | undefined)

Optional email used by member search.

**ResourceMember.imageUrl** (string | undefined)

Optional profile image URL.

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

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

**MemberRole.name** (string)

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.

**roleLabel(role)** (string)

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

**memberRoleFor(vocabulary, name)** (MemberRole)

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

**roleLabelFor(vocabulary, name)** (string)

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.

**ResourceMembersState.loading** (boolean)

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:

**src/ProjectMemberExample.tsx**

```tsx
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](https://www.sanity.io/docs/workflows/app-sdk).

To store an assignment on the instance, the definition needs an `assignees` field with `editable: true`. [Configure workflow fields](https://www.sanity.io/docs/workflows/fields) shows the field type. This picker commits each change through the session and surfaces a rejected commit:

**src/AssignmentPicker.tsx**

```tsx
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:

**src/WorkflowEditableFields.tsx**

```tsx
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:

#### Properties

**engine** (Engine)

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

**instanceId** (string)

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.

![A live workflow diagram shows Review as the current stage, followed by Legal and End. Hovering the Review-to-Legal transition opens a Publish insight: Approved is true, but Legal approved must still become true before the transition can fire.](https://cdn.sanity.io/images/3do82whm/next/592a3b172b523d57a2f4db939289c007ec5e0529-1596x521.png)

**src/WorkflowDiagramRecipe.tsx**

```tsx
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>
  )
}
```

#### Properties

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

**src/StageView.tsx**

```tsx
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.

#### Properties

**useWorkflowInstances({engine, filter?, params?, documents?, limit?})** (WorkflowInstanceList)

A live list of full instances. Use it when the surface needs instance detail for a bounded set. filter and params narrow the list with GROQ, as described below. documents keeps instances that reference any of the given GDR URIs. limit keeps only the newest instances, newest started first. Without it, every match is listed, oldest started first.

**useDocumentWorkflows({engine, document, filter?, params?})** (WorkflowInstanceList)

The instances that reference one document. Use it for a document banner. document is a global document reference URI.

**useInstancePreviews({engine, observer, pageSize?})** (InstancePreviewList)

A progressively hydrated list of reduced rows for every instance in the partition, completed ones included. Use it for an inbox, board, or dashboard that should not load every full instance. It takes no filter. To narrow the list, filter the returned previews in your component.

**WorkflowInstanceList.instances** (readonly WorkflowInstance[] | undefined)

Set only for a ready snapshot.

**WorkflowInstanceList.loading** (boolean)

True while the snapshot is pending. An empty instances with loading: false and no error is a confirmed empty result.

**WorkflowInstanceList.unreadable** (readonly InvalidDoc[])

Workflow documents this engine cannot read, skipped from instances and flagged here.

**WorkflowInstanceList.error** (unknown)

Set when the live read failed. Clears when the stream recovers.

`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](https://www.sanity.io/docs/workflows/engine) 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:

**src/ReviewCounts.tsx**

```tsx
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`:

**src/WorkflowDashboard.tsx**

```tsx
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](https://www.sanity.io/docs/workflows/custom-reactive-adapters).

## 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:

#### Properties

**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](https://www.sanity.io/docs/workflows/app-sdk): build the instance-list and task-session application around these controls.
- [Fields](https://www.sanity.io/docs/workflows/fields): understand editable field types, scopes, and stored values.
- [History and audit trail](https://www.sanity.io/docs/workflows/history-and-audit-trail): use instance history when presenting the workflow’s visited path.

> [!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).





## Related changelog entries

Entries are listed newest first; each link points to the full entry as markdown. Follow one when you need to know what changed, when, or why — for example, to summarize recent updates, explain behavior that differs from older documentation, or check whether a fix has shipped.

- [Workflows v0.39.0: Four packages, start roles, and stricter checks](https://www.sanity.io/docs/changelog/workflows-MC4zOS4w.md) — November 16, 2026