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

# Build a workflow interface with the App SDK

Render live workflow state and commit actions from your own App SDK application: mount a session, handle its states, render activities and fields from the evaluation, and list instances.

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



This page is for applications outside Studio. To build a Document Action, tool, pane, input, or dialog inside Studio, see [Create a workflow-powered Document Action](https://www.sanity.io/docs/workflows/custom-studio-integrations). [Choose an integration](https://www.sanity.io/docs/workflows/reactive-session) compares the packages.

When the Studio plugin does not fit the interface you need, use `@sanity/workflows-ui/sdk` to build the workflow experience in an App SDK application. It supplies live workflow state and the engine operations that change it.

This guide builds one App SDK screen: a workflow panel that shows an instance’s stage, fires its actions, and edits a field, then an instance list that opens the panel. For assignment, actor, and date controls, see [Reusable UI components](https://www.sanity.io/docs/workflows/ui-components). For the underlying live-data model, see [The reactive session](https://www.sanity.io/docs/workflows/reactive-session).

You need:

- The [Workflows quick start](https://www.sanity.io/docs/workflows/getting-started) completed. This guide uses its `article-review` definition and the `dev` deployment in `sanity.workflow.ts`.
- An App SDK app for the same Sanity project. To create one, follow the [App SDK quick start](https://www.sanity.io/docs/app-sdk/sdk-quickstart).
- Familiarity with [editable workflow fields](https://www.sanity.io/docs/workflows/fields) and [transition conditions](https://www.sanity.io/docs/workflows/conditions). The next section adds both to the quick start definition.

## Install the runtime

Use `@sanity/sdk` and `@sanity/sdk-react` 3.1 or later in the 3.x line. Install matching SDK versions, and the same version of `@sanity/workflows` and `@sanity/workflows-ui`. Use Workflows 0.39.0 or later. Earlier versions take a different filter in `useWorkflowInstances`, and versions before 0.37.0 also reject the partition setting this guide uses.

SDK 3.1.0 can resolve `@sanity/mutate` 0.18.1, which can leave document reads pending with Sanity client 8. Before installing, merge this override into your application’s root package-manager configuration:

**package.json (npm)**

```json
{
  "overrides": {
    "@sanity/sdk": {
      "@sanity/mutate": "0.18.2"
    }
  }
}
```

**pnpm-workspace.yaml (pnpm)**

```yaml
overrides:
  '@sanity/sdk@3>@sanity/mutate': 0.18.2
```

Install the App SDK adapter, shared controls, and their host dependencies:

**npm**

```shell
npm install @sanity/sdk@^3.1 @sanity/sdk-react@^3.1 \
  @sanity/ui@^4.2.1 react@^19.2.7 react-dom@^19.2.7 \
  styled-components@^6.4.2 @sanity/workflows @sanity/workflows-ui
```

**pnpm**

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

**yarn**

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

**bun**

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

`@sanity/workflows-ui/react` supplies the shared reactive hooks used in this guide. The UI examples use Sanity UI 4 and must render inside its [theme provider](https://www.sanity.io/docs/workflows/ui-components).

Run `npm ls @sanity/sdk @sanity/mutate` or `pnpm why @sanity/mutate`. Confirm that SDK 3 resolves Mutate 0.18.2; other dependency branches may use different versions. Commit the configuration and updated lockfile.

Keep the override until your SDK release requires Mutate 0.18.2 or later and excludes 0.18.1. After removing it, reinstall and verify the dependency tree again.

## Prepare the workflow

The panel in this guide edits a score, and the transition out of review waits on that score and a legal approval. The quick start definition has no field the panel can edit and no condition to wait on. In `workflows/article-review.ts`, add two editable fields and a `when` condition on `to-approved`:

**workflows/article-review.ts**

```typescript
export const articleReview = defineWorkflow({
  // ...
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      // ...
    }),
    defineField({type: 'number', name: 'score', title: 'Score', editable: true}),
    defineField({type: 'boolean', name: 'legalApproved', title: 'Legal approved', editable: true}),
  ],
  stages: [
    // drafting is unchanged
    defineStage({
      name: 'review',
      // ...
      transitions: [
        defineTransition({
          name: 'to-approved',
          title: 'Approve and finish',
          to: 'approved',
          when: '$allActivitiesDone && $fields.legalApproved == true && $fields.score > 5',
        }),
      ],
    }),
    // approved is unchanged
  ],
})
```

`editable: true` lets a user change the field while the instance runs. Without it, the field is not in the evaluation’s `editableFields`. The `when` condition keeps the instance in `review` after `sign-off` resolves, until the score is above 5 and legal approval is set.

Redeploy the definition:

**npm**

```shell
npx sanity-workflows deploy
```

**pnpm**

```shell
pnpm dlx sanity-workflows deploy
```

**yarn**

```shell
yarn dlx sanity-workflows deploy
```

**bun**

```shell
bunx sanity-workflows deploy
```

The quick start instance is already in `approved`, and it stays pinned to the version it started under. Start a new instance against the same article:

**npm**

```shell
npx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
```

**pnpm**

```shell
pnpm dlx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
```

**yarn**

```shell
yarn dlx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
```

**bun**

```shell
bunx sanity-workflows start article-review \
  --field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
```

**Output**

```text
Started dev.wf-instance.a1b2c3d4e5f6 — now at drafting
```

Keep the id. The examples below use it as `INSTANCE_ID`.

## Create a live session

A session loads the instance, evaluates its definition against the content it references, and re-evaluates when that content, its guards, or a field preview changes. [The reactive session](https://www.sanity.io/docs/workflows/reactive-session) explains the model.

Create one workflow session for the instance currently open in a detail view. The session keeps that instance's evaluation current and provides the operations that change it. Pass the engine and instance ID to `useWorkflowSession`. Build the engine with `useWorkflowEngine`, using the dataset and `partition: 'dev'` from the quick start’s `dev` deployment. An engine on another partition cannot see the instance. Use the hooks in [List instances and open one](https://www.sanity.io/docs/workflows/app-sdk) to let the user choose an instance without creating a session for every row.

> [!WARNING]
> Do not edit workflow instances as content
> Do not use `useEditDocument` or other content-editing APIs to change workflow instance documents. They bypass engine transactions and can break the audit trail or leave the instance internally inconsistent. Use the session’s operations instead. See [Instance writes are transactions](https://www.sanity.io/docs/workflows/actors-and-enforcement).

**src/WorkflowPanel.tsx**

```tsx
import {useWorkflowEngine, useWorkflowSession} from '@sanity/workflows-ui/sdk'

export function WorkflowPanel({instanceId}: {instanceId: string}) {
  // The same dataset and partition as the dev deployment in sanity.workflow.ts.
  const engine = useWorkflowEngine({
    workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
    partition: 'dev',
  })
  const session = useWorkflowSession({engine, instanceId})
  // A real UI also handles session.invalid, session.error, and
  // session.evaluationError before treating a missing evaluation as loading.
  if (!session.ready || !session.evaluation) return <p>Loading…</p>
  return <pre>{session.evaluation.instance.currentStage}</pre>
}
```

Mount it inside `SanityApp`, configured for the [dataset](https://www.sanity.io/docs/content-lake/datasets) your content lives in. The UI examples need the Sanity UI theme provider, and `WorkflowsTelemetryProvider` lets the engine report its telemetry. Replace `INSTANCE_ID` with the id the start command printed:

**src/App.tsx**

```tsx
import {SanityApp} from '@sanity/sdk-react'
import {ThemeProvider} from '@sanity/ui'
import {buildTheme} from '@sanity/ui/theme'
import {WorkflowsTelemetryProvider} from '@sanity/workflows-ui/sdk'

import {WorkflowPanel} from './WorkflowPanel'

const theme = buildTheme()

export function App() {
  return (
    <SanityApp
      config={[{projectId: 'PROJECT_ID', dataset: 'DATASET_NAME'}]}
      fallback={<p>Loading…</p>}
    >
      <ThemeProvider theme={theme}>
        <WorkflowsTelemetryProvider>
          <WorkflowPanel instanceId="INSTANCE_ID" />
        </WorkflowsTelemetryProvider>
      </ThemeProvider>
    </SanityApp>
  )
}
```

The engine makes every commit with the App SDK client’s token, and history records that token’s user as the actor.

## Render the workflow

A workflow screen must distinguish “still loading” from “this instance cannot be read.” The session reports that state and exposes the evaluation, a read-only projection of the workflow for the current actor, plus the operations that commit changes.

Handle `invalid`, `error`, and `evaluationError` before loading. Render the workflow only when `ready` is true and an evaluation is available. The complete WorkflowPanel handles them in that order. [Session states](https://www.sanity.io/docs/workflows/custom-reactive-adapters) explains what each state means.

A failed evaluation retains the last successful `evaluation`. Check `evaluationError` before displaying that value as current. Loading content is unresolved; it is not evidence that a referenced document was deleted.

### Render activities and actions

The authored definition says which actions could exist. It does not tell your UI what is available right now. Map `evaluation.currentStage.activities`, then pass each entry from `activity.actions` to the action control. The evaluation classifies each action as filtered out, automated, allowed, or blocked:

**src/ActionButton.tsx**

```tsx
import {Button, Text} from '@sanity/ui'
import {actionRendering, type ActionEvaluation} from '@sanity/workflows'
import type {WorkflowSession} from '@sanity/workflows-ui/sdk'

export function ActionButton({
  action,
  activity,
  fire,
}: {
  action: ActionEvaluation
  activity: string
  fire: WorkflowSession['fireAction']
}) {
  const rendering = actionRendering(action)
  const title = action.action.title ?? action.action.name
  if (rendering === 'absent') return null
  if (rendering === 'automation') return <Text muted>{title} runs automatically</Text>
  return (
    <Button
      disabled={!action.allowed}
      mode="ghost"
      onClick={() => void fire({activity, action: action.action.name})}
      text={title}
    />
  )
}
```

### Render editable fields

Editing every keystroke as a workflow commit would create a separate history entry for every change. The evaluation’s `editableFields` identify what the current actor may edit. Use `previewField` for immediate feedback, then `editField` when the user deliberately commits:

**src/ScoreField.tsx**

```tsx
import {useState} from 'react'
import type {WorkflowSession} from '@sanity/workflows-ui/sdk'

export function ScoreField({session}: {session: WorkflowSession}) {
  const [draft, setDraft] = useState<number>()
  const field = session.evaluation?.editableFields.find((entry) => entry.name === 'score')
  if (field === undefined) return null
  return (
    <input
      type="number"
      value={draft ?? Number(field.value ?? 0)}
      disabled={!field.editable}
      onChange={(event) => {
        const value = Number(event.target.value)
        setDraft(value)
        session.previewField({field, value})
      }}
      onBlur={(event) => {
        setDraft(undefined)
        void session.editField({field, value: Number(event.target.value)})
      }}
    />
  )
}
```

### Check the panel

Render the actions and the score field in `WorkflowPanel`, and handle each session state before the loading check. This is the complete component:

**src/WorkflowPanel.tsx**

```tsx
import {Spinner, Stack, Text} from '@sanity/ui'
import {errorMessage} from '@sanity/workflows'
import {useWorkflowEngine, useWorkflowSession} from '@sanity/workflows-ui/sdk'

import {ActionButton} from './ActionButton'
import {ScoreField} from './ScoreField'

export function WorkflowPanel({instanceId}: {instanceId: string}) {
  const engine = useWorkflowEngine({
    workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
    partition: 'dev',
  })
  const session = useWorkflowSession({engine, instanceId})

  if (session.invalid) return <Text>Unreadable instance: {session.invalid.message}</Text>
  if (session.error) return <Text>Could not load workflow: {errorMessage(session.error)}</Text>
  if (session.evaluationError) {
    return <Text>Could not evaluate workflow: {errorMessage(session.evaluationError)}</Text>
  }
  if (!session.ready || !session.evaluation) return <Spinner />

  const {currentStage, instance} = session.evaluation
  return (
    <Stack gap={3}>
      <Text weight="semibold">{instance.currentStage}</Text>
      {currentStage.activities.flatMap(({activity, actions}) =>
        actions.map((action) => (
          <ActionButton
            action={action}
            activity={activity.name}
            fire={session.fireAction}
            key={`${activity.name}/${action.action.name}`}
          />
        )),
      )}
      <ScoreField session={session} />
    </Stack>
  )
}
```

Run the app. The panel shows `drafting` and a `Submit for review` button. Select it. The panel switches to `review` and shows `Approve`. Confirm the change from a terminal:

**npm**

```shell
npx sanity-workflows show INSTANCE_ID
```

**pnpm**

```shell
pnpm dlx sanity-workflows show INSTANCE_ID
```

**yarn**

```shell
yarn dlx sanity-workflows show INSTANCE_ID
```

**bun**

```shell
bunx sanity-workflows show INSTANCE_ID
```

The `Stage` row reads `review`. If you select `Approve` now, the instance stays in `review`: the `when` condition still waits on the score and legal approval. To tell the user what remains, see [Explain workflow decisions](https://www.sanity.io/docs/workflows/evaluation-insights).

## List instances and open one

A session covers one instance. To let the user choose which instance to open, list instances with `useWorkflowInstances` and mount `WorkflowPanel` for the selected one:

**src/WorkflowsTool.tsx**

```tsx
import {Button, Stack, Text} from '@sanity/ui'
import {errorMessage} from '@sanity/workflows'
import {useWorkflowEngine, useWorkflowInstances} from '@sanity/workflows-ui/sdk'
import {useState} from 'react'

import {WorkflowPanel} from './WorkflowPanel'

export function WorkflowsTool() {
  const [selectedId, setSelectedId] = useState<string>()
  if (selectedId) {
    return (
      <Stack gap={3}>
        <Button mode="bleed" onClick={() => setSelectedId(undefined)} text="Back to workflows" />
        <WorkflowPanel instanceId={selectedId} />
      </Stack>
    )
  }
  return <WorkflowList onSelect={setSelectedId} />
}

function WorkflowList({onSelect}: {onSelect: (instanceId: string) => void}) {
  const engine = useWorkflowEngine({
    workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
    partition: 'dev',
  })
  const {instances, loading, unreadable, error} = useWorkflowInstances({engine})

  if (error) return <Text>Could not load workflows: {errorMessage(error)}</Text>
  if (loading) return <Text muted>Loading workflows…</Text>
  return (
    <Stack gap={3}>
      {unreadable.length > 0 ? (
        <Text muted>{unreadable.length} workflow document(s) could not be read.</Text>
      ) : null}
      {instances?.length ? (
        instances.map((instance) => (
          <Button
            key={instance._id}
            mode="ghost"
            onClick={() => onSelect(instance._id)}
            text={`${instance.definition}: ${instance.currentStage}`}
          />
        ))
      ) : (
        <Text muted>No workflow instances yet.</Text>
      )}
    </Stack>
  )
}
```

The list handles a read error, loading, unreadable workflow documents, and an empty result before it renders rows. Without a filter, `useWorkflowInstances` lists every instance in the partition, completed ones included, so the finished quick start instance appears too. To list in-flight instances only, pass `filter: '!defined(completedAt)'`.

In `src/App.tsx`, import `WorkflowsTool` from `./WorkflowsTool` and render `<WorkflowsTool />` in place of `<WorkflowPanel instanceId="INSTANCE_ID" />`.

Run the app. The list shows `article-review: approved` for the finished quick start instance and `article-review: review` for the instance you started. Select it to open the panel, and select **Back to workflows** to return to the list.

To show the workflows for one document, or a dashboard over many instances, see [Instance list hooks](https://www.sanity.io/docs/workflows/ui-components).

## Next steps

- [The reactive session](https://www.sanity.io/docs/workflows/reactive-session) for the conceptual model this page renders.
- [Reusable UI components](https://www.sanity.io/docs/workflows/ui-components): resolve actor names, edit assignments with the shared pickers, and choose an instance list hook.
- [Evaluation insights](https://www.sanity.io/docs/workflows/evaluation-insights): explain why an action is blocked or a transition is still waiting.
- [Test a workflow before you deploy it](https://www.sanity.io/docs/workflows/testing): the test bench evaluates the same projection, so helpers like the ones on this page are directly assertable.
- [Reference guide](https://www.sanity.io/docs/workflows/reference) for the full API surface.
- [Build a custom reactive adapter](https://www.sanity.io/docs/workflows/custom-reactive-adapters): integrate another host or data layer.

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



