Your Vue dashboard is snappy when rendering fifty rows of user data, but the moment you wire it up to an asynchronous, multi-step generative AI workflow—say, a content generation pipeline that takes a brief, streams an outline, refines the sections, generates images, and runs a final compliance check—your UI state management collapses into a tangled web of ref variables, race conditions, and unhandled cancellation tokens.
Every frontend engineer building agentic or generative interfaces eventually hits this exact wall. You start with a simple loading boolean. Then the product team wants step-by-step progress bars. Then they want the ability to pause mid-stream, retry a single failing step without resetting the entire context, edit intermediate JSON payloads, and roll back state when an LLM hallucination poisons the workflow.
Before you know it, your component script setup is 800 lines long, littered with nested try/catch blocks, AbortControllers, and asynchronous flags that even you can't reason about on a Tuesday afternoon.
The solution isn't writing more inline component logic. The solution is treating AI workflows for what they actually are: state machines with side effects. And in Vue 3, the cleanest way to encapsulate, test, and reuse state machines is through a well-crafted composable.
📋 Table of Contents
- The Anatomy of a Multi-Step AI Workflow
- 1. The State Machine Foundation: Moving Beyond Boolean Flags
- 2. Handling Granular Step Progression and Rollbacks
- 3. Streaming LLM Responses Inside Composable Loops
- 4. Managing AbortControllers and Cancellation Tokens Safely
- 5. Step-Level Error Boundaries and Resilient Retries
- 6. Type Safety and Generic Context Propagation
- 7. Plugging into Vue's Lifecycle: Cleanup and Persistence
- Production Architecture: When the Composable Meets Pinia
The Anatomy of a Multi-Step AI Workflow
Unlike traditional CRUD applications where state transitions are discrete and immediate (click button, hit API, store result), AI workflows are inherently asynchronous, long-running, and fluid. A single user action might trigger a sequence like this:
[Input Extraction] ➔ [Outline Generation (Streaming)] ➔ [User Review] ➔ [Parallel Section Expansion] ➔ [Final Polish]
If you manage this directly inside a Single File Component (SFC), you inevitably couple your presentation layer to your orchestration logic. When you need that same workflow in a sidebar, a modal, or a dedicated full-screen view, you end up duplicating code or struggling to extract it.
A reusable Vue composable (useWorkflow or useAIWorkflow) abstracts this orchestration. It exposes a clean, reactive API to your components while encapsulating step execution, error recovery, cancellation, and context accumulation behind the scenes.
1. The State Machine Foundation: Moving Beyond Boolean Flags
Scenario:
You write a component with isAnalyzing, isGenerating, and isPolishing refs. Halfway through the project, the client asks to add a "Review" step between generation and polishing. You now have to introduce isReviewing, update your disabled state bindings across a dozen templates, and fix a bug where isGenerating stays true even when the review step fails.
Why it matters:
Independent boolean flags scale exponentially with the number of states. An $N$-step workflow with error, idle, and loading states cannot be accurately represented by a collection of disconnected booleans without inviting impossible UI states (e.g., isGenerating: true and isCompleted: true simultaneously).
Solution: Model your composable around a strict state machine pattern with explicit transitions. Instead of tracking what the app is doing, track where it is in the lifecycle and what data it currently holds.
Code:
// useAIWorkflow.ts
import { ref, computed, shallowRef } from 'vue'
export type WorkflowStatus = 'idle' | 'running' | 'paused' | 'failed' | 'completed'
export interface Step<TContext = any> {
id: string
name: string
execute: (context: TContext, signal: AbortSignal) => Promise<Partial<TContext>>
}
export function useAIWorkflow<TContext extends Record<string, any>>(initialContext: TContext, steps: Step<TContext>[]) {
const status = ref<WorkflowStatus>('idle')
const currentIndex = ref(0)
const context = shallowRef<TContext>({ ...initialContext })
const error = ref<Error | null>(null)
const currentStep = computed(() => steps[currentIndex.value] || null)
const progress = computed(() => Math.round((currentIndex.value / steps.length) * 100))
return {
status,
currentIndex,
currentStep,
context,
error,
progress
}
}
Why this works:
Using shallowRef for the workflow context prevents Vue from deep-proxying large, nested objects returned by LLMs (such as sprawling ASTs, massive JSON payloads, or token arrays), which can introduce measurable overhead in rendering performance. The currentStep and progress computed properties derive their values directly from the currentIndex, eliminating synchronization bugs.
💡 Practical note: Keep your step definitions pure functions where possible. Avoid mutating the incoming
contextobject directly inside step definitions; returning a partial object to be merged keeps your state updates predictable and traceable.
2. Handling Granular Step Progression and Rollbacks
Scenario: Step 3 of your content generation workflow successfully generates a markdown draft, but Step 4 (SEO optimization) crashes because the LLM returned malformed JSON. When the user clicks "Retry," your workflow restarts from Step 1, wasting time, tokens, and user patience.
Why it matters: AI API calls are expensive in both latency and financial cost. Forcing users to repeat completed, deterministic steps just because a downstream generative step failed is an unacceptable developer experience.
Solution: Implement explicit forward progression, step-by-step state accumulation, and the ability to jump back or retry individual steps without wiping out prior context.
Code:
// Continuing inside useAIWorkflow.ts
let abortController: AbortController | null = null
export function useAIWorkflow<TContext extends Record<string, any>>(initialContext: TContext, steps: Step<TContext>[]) {
// ... previous refs ...
const runStep = async (index: number) => {
if (index < 0 || index >= steps.length) return
currentIndex.value = index
status.value = 'running'
error.value = null
abortController = new AbortController()
try {
const step = steps[index]
const stepResult = await step.execute(context.value, abortController.signal)
// Accumulate context immutably
context.value = {
...context.value,
...stepResult
}
if (currentIndex.value < steps.length - 1) {
currentIndex.value++
await runStep(currentIndex.value)
} else {
status.value = 'completed'
}
} catch (err: any) {
if (err.name === 'AbortError') {
status.value = 'paused'
} else {
status.value = 'failed'
error.value = err
}
}
}
const start = () => runStep(0)
const retryCurrentStep = () => runStep(currentIndex.value)
return {
// ... exposed state ...
start,
retryCurrentStep
}
}
Why this works:
By tracking currentIndex, runStep can be invoked recursively or targeted directly via retryCurrentStep. Because the accumulated context persists across steps, a failure in Step 4 leaves the context intact up to the end of Step 3. When retryCurrentStep runs, it picks up right where it left off with all prior data preserved.
3. Streaming LLM Responses Inside Composable Loops
Scenario: Your AI workflow needs to stream text chunk-by-chunk from an LLM endpoint during Step 2. You need to expose this live stream to the UI component so users aren't staring at a blank screen for ten seconds, while still allowing the composable to capture the final assembled string into the workflow context.
Why it matters:
Standard await fetch() calls block until the entire response body is downloaded. In generative UI, perceived performance is everything. A composable that cannot handle ReadableStreams natively forces developers to write ad-hoc event emitter workarounds inside their components.
Solution:
Design step execution functions to accept stream callbacks or handle ReadableStream consumption natively inside the composable's execution loop, exposing a reactive streamBuffer property.
Code:
// Adding streaming capabilities to the composable
const streamBuffer = ref('')
const executeStreamingStep = async (
endpoint: string,
payload: any,
signal: AbortSignal
): Promise<string> => {
streamBuffer.value = ''
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal
})
if (!response.ok || !response.body) {
throw new Error(`AI generation failed: ${response.statusText}`)
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let accumulated = ''
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value, { stream: true })
accumulated += chunk
streamBuffer.value = accumulated
}
} finally {
reader.releaseLock()
}
return accumulated
}
Why this works:
The streamBuffer ref updates reactively on every chunk read from the stream reader. The component consuming this composable can bind directly to streamBuffer to display a real-time typewriter effect. Once the stream finishes, the full string is returned and automatically merged into the workflow's main context object.
4. Managing AbortControllers and Cancellation Tokens Safely
Scenario: A user kicks off a heavy 5-step AI generation workflow, realizes they pasted the wrong prompt in Step 1, and immediately clicks a "Cancel" button or navigates away to a different route. Meanwhile, your background fetches continue hammering your LLM provider, burning through your API rate limits and generating ghost tokens.
Why it matters: Network requests triggered inside composables don't automatically cancel when components unmount or users abort. Without centralized cancellation management, you create memory leaks, orphan network requests, and race conditions where late-arriving responses mutate unmounted component state.
Solution:
Incorporate an AbortController lifecycle directly into the composable's root scope, exposing clean cancel() and pause() methods that automatically propagate down to active fetch calls.
Code:
export function useAIWorkflow(...) {
let activeController: AbortController | null = null
const cancel = () => {
if (activeController) {
activeController.abort()
activeController = null
}
status.value = 'paused'
}
const runStep = async (index: number) => {
// Cancel any existing prior controller
if (activeController) {
activeController.abort()
}
activeController = new AbortController()
const signal = activeController.signal
try {
const step = steps[index]
const result = await step.execute(context.value, signal)
// ... handle success ...
} catch (err: any) {
if (err.name === 'AbortError') {
// Expected cancellation, do not treat as application failure
status.value = 'paused'
return
}
status.value = 'failed'
error.value = err
}
}
// Ensure automatic cleanup on scope disposal (Vue 3.5+)
tryOnScopeDispose(() => {
cancel()
})
return {
cancel,
// ... other returns
}
}
Why this works:
Using AbortController is the web platform standard for terminating asynchronous operations. By tying the controller instance directly to the composable's execution cycle and leveraging tryOnScopeDispose (from @vueuse/core or built-in scope tracking), you guarantee that leaving the page immediately kills all in-flight AI generation requests.
5. Step-Level Error Boundaries and Resilient Retries
Scenario:
An LLM provider throws a 503 Service Unavailable error right in the middle of Step 3 due to high traffic. If your workflow fails instantly, the user has to start over. If you loop infinitely without backoff, you risk getting banned for rate-limiting.
Why it matters: AI infrastructure is notoriously flaky compared to traditional deterministic databases. Transient failures are a matter when, not if. Your workflow execution engine needs built-in resilience strategies like exponential backoff and automatic retry thresholds.
Solution: Wrap step execution in a resilient retry wrapper with configurable backoff logic before bubbling the error up to the UI state machine.
Code:
async function executeWithRetry(
stepFn: () => Promise<any>,
retries = 3,
delay = 1000,
signal: AbortSignal
): Promise<any> {
try {
return await stepFn()
} catch (error: any) {
if (signal.aborted || retries <= 0) {
throw error
}
// Don't retry client-side validation errors (4xx)
if (error.status && error.status >= 400 && error.status < 500) {
throw error
}
await new Promise((resolve, reject) => {
const timer = setTimeout(resolve, delay)
signal.addEventListener('abort', () => {
clearTimeout(timer)
reject(new DOMException('Aborted', 'AbortError'))
}, { once: true })
})
return executeWithRetry(stepFn, retries - 1, delay * 2, signal)
}
}
Why this works:
This recursive wrapper catches transient server errors (5xx, rate limits), waits with an exponential backoff (delay * 2), and checks the AbortSignal during the backoff delay so cancellation isn't blocked by a waiting timer. Client-side errors (like a malformed prompt returning a 400 Bad Request) fail fast without pointless retries.
6. Type Safety and Generic Context Propagation
Scenario:
You write a generic workflow composable, but inside your Vue component, accessing properties on context.value yields any, robbing you of TypeScript autocomplete when passing generated data from Step 1 into Step 3.
Why it matters: AI workflows manipulate complex, evolving data shapes (e.g., raw prompt ➔ extracted entities ➔ generated outline ➔ expanded chapters). Losing type safety across step boundaries invites runtime undefined errors.
Solution: Leverage TypeScript generics to allow developers to declare the shape of the workflow context or infer it progressively as steps are added.
Code:
export interface WorkflowStep<TInput = any, TOutput = any> {
id: string
label: string
run: (input: TInput, signal: AbortSignal) => Promise<TOutput>
}
// Factory function for strict type-safe workflow definition
export function createWorkflowSteps<TBase>(steps: WorkflowStep<TBase, any>[]) {
return steps
}
export function useTypedWorkflow<TContext extends Record<string, any>>(initial: TContext) {
const context = shallowRef<TContext>({ ...initial })
function updateContext<K extends keyof TContext>(key: K, value: TContext[K]) {
context.value = {
...context.value,
[key]: value
}
}
return {
context,
updateContext
}
}
Why this works:
Constraining context updates with keyof constraints (<K extends keyof TContext>) ensures that components can only mutate valid properties of the workflow state, catching typos at compile time rather than in production browser consoles.
7. Plugging into Vue's Lifecycle: Cleanup and Persistence
Scenario: Your user spends three minutes crafting prompts and generating a massive multi-step report. Suddenly, they accidentally refresh the browser tab. All generated content vanishes into the void.
Why it matters: Long-running client-side processes are vulnerable to accidental navigation, tab closures, and network drops. While server-side persistence is ideal for production, client-side session caching provides a safety net during development and quick interactions.
Solution:
Extend your composable with an optional persistence layer that synchronizes workflow state and step index to sessionStorage or localStorage automatically using Vue's watch effects.
Code:
import { watch } from 'vue'
export function usePersistentWorkflow<TContext extends Record<string, any>>(
storageKey: string,
initialContext: TContext
) {
const savedState = sessionStorage.getItem(storageKey)
const parsed = savedState ? JSON.parse(savedState) : { index: 0, context: initialContext }
const currentIndex = ref(parsed.index)
const context = shallowRef<TContext>(parsed.context)
watch([currentIndex, context], ([newIndex, newContext]) => {
sessionStorage.setItem(storageKey, JSON.stringify({
index: newIndex,
context: newContext
}))
}, { deep: true })
const clearPersistence = () => {
sessionStorage.removeItem(storageKey)
}
return {
currentIndex,
context,
clearPersistence
}
}
Why this works:
A deep watcher on [currentIndex, context] captures every state transition and persists it instantly. When the component mounts again, it rehydrates from sessionStorage, allowing users to resume their multi-step AI workflow right where they left off after an accidental refresh.
⚠️ Gotcha: Avoid persisting large binary blobs, active
AbortControllerinstances, or rawReadableStreamobjects intosessionStorage. Keep persisted state strictly limited to JSON-serializable text context and indices.
Production Architecture: When the Composable Meets Pinia
Composables are phenomenal for component-scoped state, but what happens when your multi-step AI workflow needs to be accessed across multiple distant components—for instance, displaying a progress indicator in the navbar while the user is filling out a form on the main page?
This is where developers often make the mistake of rewriting their composable into a monolithic Pinia store. Don't.
Instead, use the Composable Factory Pattern: keep your core orchestration logic inside a pure composable, and wrap it in a Pinia store only when global sharing is required.
// useWorkflowStore.ts
import { defineStore } from 'pinia'
import { useAIWorkflow } from './useAIWorkflow'
export const useWorkflowStore = defineStore('ai-workflow', () => {
const workflow = useAIWorkflow(
{ prompt: '', outline: '', chapters: [] },
[
// step definitions...
]
)
return {
...workflow
}
})
By keeping the orchestration logic inside a reusable composable (useAIWorkflow), you retain the flexibility to instantiate multiple independent workflow instances in local components (e.g., batch processing three different documents simultaneously), while Pinia acts merely as a thin container when global singleton state is mandatory.
When you decouple your AI workflow logic from your UI components, building complex generative interfaces stops feeling like walking through a minefield of race conditions and starts feeling like standard, testable frontend engineering.