Model AI Task Lifecycles in Vue with an Explicit State Machine

Your user opens a multi-modal AI generation dashboard in Vue. They trigger a heavy batch job: compiling video summaries, generating localized voiceovers, and embedding dense vector indices.

Suddenly, they click "Pause." Then they refresh the page. Then they navigate to another view and come back.

In a naive Vue application built with scattered reactive flags (isGenerating, isPaused, hasError), this exact sequence is where your app quietly falls apart. The UI stutters, the progress bars desynchronize from the backend WebSockets, a failed task gets stuck in an infinite polling loop, and your user is left staring at a spinning loader that will spin until the heat death of the universe.

Managing asynchronous, multi-stage workflows in frontend applications is notoriously difficult. When those workflows involve costly, unpredictable AI tasks—spanning chunked streaming responses, rate limits, manual user interventions, and transient network failures—simple boolean flags are a recipe for architectural debt.

To build robust AI-driven dashboards, we need a formalized mental model. We need state machines.

📋 Table of Contents


The Anatomy of an AI Task Lifecycle

Before writing any Vue composables, let's map out what an AI task actually goes through in a modern web application. Unlike standard CRUD operations (which are typically synchronous request-response cycles), AI workloads are inherently asynchronous, long-running, and prone to interruption.

A robust AI task moves through these core states:

  1. Idle: The task is defined in the UI, parameters are configured, but execution hasn't been triggered.
  2. Queued: The task has been dispatched by the user, but it's waiting for an available concurrency slot in the local queue or on the backend worker pool.
  3. Running: The network request is active, tokens or chunks are streaming in via SSE (Server-Sent Events) or WebSockets, and progress is updating.
  4. Paused: The user has intentionally suspended the operation. Network streams are aborted cleanly, and intermediate state is preserved.
  5. Failed: An unrecoverable error occurred (e.g., token limit exceeded, API key expired, or network dropped permanently).
  6. Completed: The payload has been fully received, validated, and rendered.

The biggest mistake developers make is allowing any state to transition to any other state via random component methods. If a user clicks "Pause" while a task is Queued, what happens? If a task has already Failed, can it be Paused?

A Finite State Machine (FSM) prevents these illegal transitions entirely.


1. Modeling the Strict State Transition Matrix

Scenario:

Your junior developer adds a "Retry" button to a failed AI task card. However, because the component doesn't check if the task is actually finished cleaning up its previous stream connection, clicking "Retry" rapidly three times fires three concurrent requests, instantly exhausting your LLM rate limit and throwing duplicate primary key errors in your database.

Why it matters:

Unconstrained UI event handlers allow users (and buggy useEffect/watch hooks) to trigger asynchronous operations out of order. You need a centralized matrix that explicitly defines what transitions are legal.

Solution:

Define a strict transition dictionary where every state explicitly declares its allowed neighboring states.

// types/ai-task.ts
export type TaskState = 'idle' | 'queued' | 'running' | 'paused' | 'failed' | 'completed';

export type TaskEvent = 'DISPATCH' | 'START' | 'PAUSE' | 'RESUME' | 'FAIL' | 'COMPLETE' | 'RESET';

export const VALID_TRANSITIONS: Record<TaskState, TaskState[]> = {
  idle: ['queued', 'running'],
  queued: ['running', 'failed', 'idle'],
  running: ['paused', 'failed', 'completed', 'queued'],
  paused: ['running', 'idle', 'failed'],
  failed: ['queued', 'idle'],
  completed: ['idle']
};

export function canTransition(currentState: TaskState, targetState: TaskState): boolean {
  return VALID_TRANSITIONS[currentState]?.includes(targetState) ?? false;
}

Why this works:

By decoupling your state logic from your Vue component templates, you create a pure, testable JavaScript module. Components no longer guess if an action is valid; they ask the transition guard.

💡 Practical note: Keep your state machine definitions framework-agnostic. You should be able to unit test your transition matrix with simple Jest or Vitest assertions without mounting a single Vue component.


2. Implementing a Reactive Finite State Machine in Vue 3 Composition API

Scenario:

You need a reusable pattern across your application where multiple AI generation cards (text summarization, image generation, code translation) share the exact same lifecycle management without duplicating state management code.

Why it matters:

Writing custom reactive logic directly inside component <script setup> blocks leads to deeply nested ref definitions and tangled lifecycle hooks.

Solution:

Encapsulate the state machine and its associated execution handlers inside a dedicated Vue composition function (useAiTask).

// composables/useAiTask.ts
import { ref, computed } from 'vue';
import { TaskState, canTransition } from '@/types/ai-task';

export interface AiTaskOptions {
  id: string;
  executor: (signal: AbortSignal, onProgress: (progress: number) => void) => Promise<any>;
}

export function useAiTask(options: AiTaskOptions) {
  const currentState = ref<TaskState>('idle');
  const progress = ref(0);
  const error = ref<Error | null>(null);
  const result = ref<any>(null);
  
  let abortController: AbortController | null = null;

  const isTerminal = computed(() => ['completed', 'failed'].includes(currentState.value));
  const isRunning = computed(() => currentState.value === 'running');
  const isPaused = computed(() => currentState.value === 'paused');

  function transitionTo(newState: TaskState) {
    if (!canTransition(currentState.value, newState)) {
      console.warn(`[FSM] Invalid transition attempt from '${currentState.value}' to '${newState}'`);
      return false;
    }
    console.log(`[FSM] Transition: ${currentState.value} -> ${newState}`);
    currentState.value = newState;
    return true;
  }

  async function start() {
    if (currentState.value === 'idle' || currentState.value === 'failed') {
      if (!transitionTo('queued')) return;
    }

    if (!transitionTo('running')) return;

    error.value = null;
    abortController = new AbortController();

    try {
      // Execute the async AI workload with cancellation support
      result.value = await options.executor(
        abortController.signal, 
        (p) => { progress.value = p; }
      );
      transitionTo('completed');
    } catch (err: any) {
      if (err.name === 'AbortError') {
        // Paused or cancelled intentionally
        if (currentState.value !== 'paused') {
          transitionTo('idle');
        }
      } else {
        error.value = err;
        transitionTo('failed');
      }
    } finally {
      abortController = null;
    }
  }

  function pause() {
    if (!isRunning.value) return;
    if (abortController) {
      abortController.abort();
    }
    transitionTo('paused');
  }

  function resume() {
    if (!isPaused.value) return;
    start();
  }

  function reset() {
    if (abortController) {
      abortController.abort();
    }
    if (transitionTo('idle')) {
      progress.value = 0;
      error.value = null;
      result.value = null;
    }
  }

  return {
    id: options.id,
    state: currentState,
    progress,
    error,
    result,
    isRunning,
    isPaused,
    isTerminal,
    start,
    pause,
    resume,
    reset
  };
}

Why this works:

This composable encapsulates both the state and the side effects (AbortController handling, error catching, progress reporting) into a single, cohesive unit. Components consume it with minimal boilerplate:

<!-- components/AiTaskCard.vue -->
<script setup lang="ts">
import { useAiTask } from '@/composables/useAiTask';

const task = useAiTask({
  id: 'task-101',
  executor: async (signal, onProgress) => {
    // Simulated chunked AI generation stream
    for (let i = 1; i <= 10; i++) {
      if (signal.aborted) throw new DOMException('Aborted', 'AbortError');
      await new Promise((r) => setTimeout(r, 500));
      onProgress(i * 10);
    }
    return { summary: 'Generated AI summary successfully.' };
  }
});
</script>

<template>
  <div class="p-4 border rounded-lg shadow-sm bg-white dark:bg-zinc-900">
    <div class="flex justify-between items-center mb-2">
      <span class="font-mono text-xs uppercase px-2 py-1 rounded" :class="{
        'bg-yellow-100 text-yellow-800': task.state.value === 'queued',
        'bg-blue-100 text-blue-800': task.state.value === 'running',
        'bg-orange-100 text-orange-800': task.state.value === 'paused',
        'bg-green-100 text-green-800': task.state.value === 'completed',
        'bg-red-100 text-red-800': task.state.value === 'failed',
      }">
        {{ task.state.value }}
      </span>
      <span class="text-sm font-semibold">{{ task.progress.value }}%</span>
    </div>

    <!-- Progress Bar -->
    <div class="w-full bg-zinc-200 h-2 rounded-full overflow-hidden mb-4">
      <div class="bg-indigo-600 h-full transition-all duration-300" :style="{ width: `${task.progress.value}%` }"></div>
    </div>

    <!-- Controls -->
    <div class="flex gap-2">
      <button v-if="task.state.value === 'idle' || task.state.value === 'failed'" @click="task.start()" class="px-3 py-1 bg-indigo-600 text-white rounded text-sm">
        Start Task
      </button>
      <button v-if="task.isRunning.value" @click="task.pause()" class="px-3 py-1 bg-amber-600 text-white rounded text-sm">
        Pause
      </button>
      <button v-if="task.isPaused.value" @click="task.resume()" class="px-3 py-1 bg-emerald-600 text-white rounded text-sm">
        Resume
      </button>
      <button @click="task.reset()" class="px-3 py-1 bg-zinc-200 text-zinc-800 rounded text-sm">
        Reset
      </button>
    </div>
  </div>
</template>

3. Handling Resumable Streams and AbortControllers

Scenario:

Your user triggers a long-form text generation task using Server-Sent Events (SSE). Halfway through (at token 450 out of 1000), they click "Pause." Later, they click "Resume." If your frontend just opens a brand-new connection from scratch without passing the last processed token index or state identifier, your LLM wastes compute generating the exact same first 450 tokens again.

Why it matters:

AI generation is expensive. Poor stream handling leads to wasted API credits, broken user trust, and unresponsive interfaces when network conditions jitter.

Solution:

Bind your AbortSignal to both the fetch request and your chunk parser, and store the last successfully processed chunk offset in your state machine so you can resume intelligently.

// composables/useStreamingAiTask.ts
import { ref } from 'vue';

export function useStreamingAiTask(endpoint: string) {
  const data = ref('');
  const lastProcessedIndex = ref(0);
  let abortController: AbortController | null = null;

  async function streamTask(prompt: string, startIndex = 0, signal: AbortSignal) {
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt, startIndex }),
      signal
    });

    if (!response.body) throw new Error('ReadableStream not supported.');

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    try {
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value, { stream: true });
        data.value += chunk;
        lastProcessedIndex.value += chunk.length;
      }
    } finally {
      reader.releaseLock();
    }
  }

  return { data, lastProcessedIndex, streamTask };
}

⚠️ Gotcha: When using AbortController with native fetch, calling abort() throws a DOMException with the name AbortError. Always explicitly check for this error in your catch blocks so you don't mistakenly mark user-paused tasks as system failures.


4. Managing Concurrency Queues with Max-Flight Limits

Scenario:

A user selects 20 documents and clicks "Generate AI Embeddings" all at once. Your Vue app immediately fires 20 simultaneous HTTP requests to your backend vector processing endpoint. Your gateway instantly throttles requests with 429 Too Many Requests, and 15 of your tasks fail simultaneously.

Why it matters:

Uncontrolled parallelism overwhelms browser connection limits (typically 6 simultaneous connections per domain in HTTP/1.1, though better in HTTP/2), clogs up backend worker pools, and triggers rate-limiting walls on third-party LLM APIs like OpenAI or Anthropic.

Solution:

Build a centralized Queue Manager service in Vue that respects a strict maxConcurrent flight limit, automatically promoting items from queued to running as slots open up.

// services/AiQueueManager.ts
import { reactive } from 'vue';

export interface QueuedTask {
  id: string;
  run: () => Promise<void>;
  status: 'queued' | 'running' | 'completed' | 'failed';
}

export class AiQueueManager {
  private queue = reactive<Map<string, QueuedTask>>(new Map());
  private maxConcurrent: number;

  constructor(maxConcurrent = 3) {
    this.maxConcurrent = maxConcurrent;
  }

  addTask(id: string, run: () => Promise<void>) {
    this.queue.set(id, { id, run, status: 'queued' });
    this.processNext();
  }

  private async processNext() {
    const runningCount = Array.from(this.queue.values()).filter(t => t.status === 'running').length;
    
    if (runningCount >= this.maxConcurrent) return;

    const nextTask = Array.from(this.queue.values()).find(t => t.status === 'queued');
    if (!nextTask) return;

    nextTask.status = 'running';

    try {
      await nextTask.run();
      nextTask.status = 'completed';
    } catch (err) {
      nextTask.status = 'failed';
    } finally {
      // Recursively process the next item in line
      this.processNext();
    }
  }

  getTasks() {
    return Array.from(this.queue.values());
  }
}

Why this works:

By decoupling the dispatch action from immediate execution, you ensure that even if a user triggers 50 tasks at once, your application smoothly processes them in disciplined batches of 3 (or whatever limit your tier allows).


5. Surviving Page Refreshes: Persistent State Hydration

Scenario:

Your user kicks off a 3-minute video transcription AI task. Five seconds later, they accidentally hit Cmd+R to refresh the tab. When the page reloads, your Vue app initializes with clean state (idle), and the ongoing task context is completely lost in the UI, even though the background worker on the server is still happily chugging away.

Why it matters:

Web apps are stateless by default. If your state machine only lives in browser memory (ref / reactive), any navigation, reload, or crash breaks the illusion of continuous background processing.

Solution:

Persist task states and IDs to localStorage or sessionStorage (or sync them with a lightweight IndexedDB wrapper like localForage) and re-hydrate active tasks upon component mounting.

// composables/usePersistentAiTask.ts
import { ref, watch } from 'vue';
import { TaskState } from '@/types/ai-task';

export function usePersistentAiTask(storageKey: string) {
  const savedState = localStorage.getItem(`${storageKey}_state`) as TaskState | null;
  const savedProgress = localStorage.getItem(`${storageKey}_progress`);

  const state = ref<TaskState>(savedState || 'idle');
  const progress = ref(savedProgress ? parseInt(savedProgress, 10) : 0);

  // Automatically sync to localStorage on change
  watch(state, (newState) => {
    localStorage.setItem(`${storageKey}_state`, newState);
  });

  watch(progress, (newProgress) => {
    localStorage.setItem(`${storageKey}_progress`, newProgress.toString());
  });

  function clearPersistence() {
    localStorage.removeItem(`${storageKey}_state`);
    localStorage.removeItem(`${storageKey}_progress`);
  }

  return { state, progress, clearPersistence };
}

Why this works:

When the Vue application boots up, usePersistentAiTask checks local storage. If a task was in the running or queued state when the refresh happened, your app can immediately ping the backend with the task ID to re-establish a WebSocket or SSE connection.


6. Graceful Recovery from Exponential Backoff Failures

Scenario:

An AI service experiences a transient 502 Bad Gateway error. Your component immediately marks the task as failed, requiring the user to manually click "Retry" every single time until the provider recovers.

Why it matters:

Enterprise infrastructure is messy. Network blips, gateway timeouts, and provider cold starts happen. Forcing manual intervention on temporary failures degrades user experience.

Solution:

Incorporate an auto-retry wrapper with exponential backoff and jitter directly into your state machine's failure handling branch.

// utils/retryWithBackoff.ts
export async function retryWithBackoff<T>(
  fn: () => Promise<T>,
  retries = 3,
  delay = 1000
): Promise<T> {
  try {
    return await fn();
  } catch (error) {
    if (retries <= 0) throw error;
    
    // Add random jitter to prevent thundering herd problem
    const jitter = Math.random() * 200;
    const nextDelay = delay * 2 + jitter;
    
    console.warn(`[Queue] Task failed. Retrying in ${Math.round(nextDelay)}ms... (${retries} attempts left)`);
    
    await new Promise((resolve) => setTimeout(resolve, nextDelay));
    return retryWithBackoff(fn, retries - 1, nextDelay);
  }
}

Why this works:

By wrapping your executor function in retryWithBackoff, transient network errors transition the state machine into a temporary waiting state rather than instantly crashing to a hard failed screen.


7. Testing and Visualizing Your State Machine UI

Scenario:

You have complex multi-step AI pipelines (e.g., Audio Upload -> Transcription -> Sentiment Analysis -> Summary Generation). Debugging why a task got stuck between step 2 and step 3 requires digging through sprawling console logs.

Why it matters:

State machines shine when they are transparent. If developers and QA engineers can't instantly see why a state transition was rejected, debugging distributed asynchronous workflows becomes a guessing game.

Solution:

Build a simple state-inspection debug overlay in development mode that logs every transition event and exposes the internal state history.

// composables/useFsmInspector.ts
import { ref } from 'vue';

interface TransitionLog {
  timestamp: string;
  from: string;
  to: string;
}

export function useFsmInspector(taskId: string) {
  const history = ref<TransitionLog[]>([]);

  function logTransition(from: string, to: string) {
    if (import.meta.env.DEV) {
      history.value.unshift({
        timestamp: new Date().toLocaleTimeString(),
        from,
        to
      });
      if (history.value.length > 20) history.value.pop();
    }
  }

  return { history, logTransition };
}

Architectural Decision Guide: When to Keep State Client-Side vs Server-Driven

When designing AI task management architectures in Vue, one of the first major decisions you will face is where the source of truth should live. Should your Vue client maintain the finite state machine, or should the browser act as a dumb renderer mirroring a state machine running in a Redis-backed backend queue (such as Celery, BullMQ, or Laravel Queue)?

Dimension Client-Side FSM (Vue Composable) Server-Driven FSM (Backend Queue + WebSockets)
Complexity Low to Moderate High (requires WebSocket / SSE infrastructure)
Resilience Low (lost on hard tab close without persistence) High (persisted safely in database/Redis)
Multi-Tab Sync Difficult (requires BroadcastChannel API) Native (all connected clients receive state sync)
Best Use Case Quick client-side transformations, simple chat streams, lightweight local processing. Heavy enterprise AI pipelines, multi-hour batch jobs, billing-tied operations.

The Hybrid Recommendation:

For production-grade AI dashboards, use a hybrid approach. Let the backend manage the authoritative queue and execution state, but implement a local Finite State Machine on the Vue frontend to handle optimistic UI updates, immediate user interruptions (Pause/Cancel), and local animation feedback loops.

When your frontend FSM is backed by a strict transition matrix and guarded by robust concurrency queues, your Vue application will remain buttery smooth, predictable, and resilient—even when your AI providers are acting anything but.

Post a Comment

Previous Post Next Post