Stream Laravel AI Agent Progress to Vue with Laravel Reverb

When you build a chat interface powered by an LLM in a modern web application, the user experience hinges on perceived speed. If a user triggers an autonomous AI agent that takes fifteen seconds to plan, search a vector database, call three tools, and synthesize a final response, leaving them staring at a static loading spinner is a recipe for abandonment. They need to see the agent think, execute tools, and stream output tokens in real time.

Achieving this in a modern Laravel and Vue stack used to require complex gymnastics involving third-party WebSockets, Redis pub/sub channels, Node.js proxy servers, or polling strategies that melted your database. Today, we have Laravel Reverb—a high-performance, first-party WebSocket server written for Laravel, paired with Laravel Echo on the frontend.

In this comprehensive guide, we are going to look under the hood and build a robust, production-grade streaming pipeline that pushes granular AI agent progress updates from a Laravel backend directly to a Vue 3 composition-driven frontend using Laravel Reverb.


📋 Table of Contents


The Architectural Shift: Polling vs. WebSockets for AI Agents

When developers first approach adding AI agent feedback to a web app, they often reach for HTTP polling or Server-Sent Events (SSE). While SSE is brilliant for simple text generation streams where the connection is a direct request-response pipe, autonomous AI agents break this paradigm.

An autonomous agent operating via a tool-calling loop performs asynchronous actions:

  1. It receives a prompt.
  2. It queries an external API or vector database.
  3. It dispatches a queued job to scrape a website.
  4. It evaluates the scraped data and decides to call another tool.

These operations span multiple requests, background queue workers, and event cycles. SSE struggles when your state changes happen across distributed queue workers because SSE is bound to a single HTTP request handler.

Laravel Reverb solves this by providing a persistent WebSocket connection tied directly to Laravel's native event broadcasting system. Your queue workers can fire standard Laravel events (event(new AgentStepProgress(...))), and Reverb instantly multiplexes those events over a single TCP connection to your Vue application.


1. Bootstrapping Laravel Reverb and Vue Echo Connection

Before streaming agent events, you need a rock-solid, authenticated WebSocket pipeline. Let's make sure Reverb and Laravel Echo are configured correctly without hidden gotchas.

Installation and Server Configuration

First, install Reverb via the Artisan CLI:

composer require laravel/reverb
php artisan reverb:install

This publishes your configuration into config/reverb.php and sets up your environment variables. Ensure your .env file reflects your local or production connection details:

BROADCAST_CONNECTION=reverb

REVERB_APP_ID=your-app-id
REVERB_APP_KEY=your-app-key
REVERB_APP_SECRET=your-app-secret
REVERB_HOST="localhost"
REVERB_PORT=8080
REVERB_SCHEME=http

VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"

Frontend Echo Setup

In your Vue application (assuming a Vite-powered setup), install Laravel Echo and Pusher JS (Reverb uses the Pusher protocol underneath, meaning you don't need a heavy custom client):

npm install --save laravel-echo pusher-js

Initialize Echo in your frontend bootstrapping file (e.g., resources/js/echo.js):

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT,
    wssPort: import.meta.env.VITE_REVERB_PORT,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

💡 Practical note: Always run your Reverb server using php artisan reverb:start in a separate terminal during local development. If you use Laravel Herd or Valet, ensure your Vite proxy configuration correctly handles WebSocket upgrade headers if you are terminating SSL locally.


2. Structuring the AI Agent Event Loop in Laravel

Scenario: Your user asks an AI agent to research a competitor. The agent runs a multi-step loop: analyzing intent, searching the web, parsing HTML, and writing a summary. You want to emit these distinct lifecycle phases to the frontend cleanly.

Why it matters: If you pass all log data through a monolithic controller response, the user experiences a multi-second blackout while PHP waits for cURL requests and LLM completions to finish.

Solution: Structure your agent runner as a dedicated service class that emits custom broadcast events at critical milestones within its execution loop.

Code:

namespace App\Services\AI;

use App\Events\AgentProgressUpdated;
use App\Models\AgentSession;
use OpenAI\Client as OpenAIClient;

class ResearchAgent
{
    protected AgentSession $session;
    protected OpenAIClient $openai;

    public function __construct(AgentSession $session)
    {
        $this->session = $session;
        $this->openai = \OpenAI::client(config('services.openai.key'));
    }

    public function execute(string $prompt): string
    {
        $this->broadcastStep('Initializing agent workspace...', 'thinking');

        // Step 1: Planning phase
        $plan = $this->generatePlan($prompt);
        $this->broadcastStep("Plan formulated: {$plan}", 'planned', [
            'plan' => $plan
        ]);

        // Step 2: Tool Execution phase
        $this->broadcastStep('Executing web search tool...', 'tool_execution', [
            'tool' => 'WebScraper',
            'status' => 'running'
        ]);

        $searchResult = $this->runWebSearch($plan);

        $this->broadcastStep('Synthesizing final findings...', 'synthesizing');

        // Step 3: Final generation
        $finalOutput = $this->generateFinalResponse($searchResult);

        $this->broadcastStep('Task completed successfully.', 'completed', [
            'output' => $finalOutput
        ]);

        return $finalOutput;
    }

    protected function broadcastStep(string $message, string $state, array $metadata = []): void
    {
        broadcast(new AgentProgressUpdated(
            sessionId: $this->session->id,
            message: $message,
            state: $state,
            metadata: $metadata
        ));
    }
}

Why this works: By decoupling the agent's internal state machine from the HTTP response lifecycle, your application can execute complex, multi-minute workflows entirely in the background while keeping the user interface completely synchronized.


3. Broadcasting Granular Steps: Thoughts, Tools, and Tokens

When building events for Reverb, payload size and event frequency matter. If your agent emits 50 individual character tokens per second, broadcasting every single token as an individual WebSocket event will saturate your network socket and lock up your frontend event loop.

Let's design a flexible Laravel Event class that handles structured progress updates efficiently.

Code:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class AgentProgressUpdated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public readonly int $sessionId,
        public readonly string $message,
        public readonly string $state,
        public readonly array $metadata = []
    ) {}

    public function broadcastOn(): Channel
    {
        // Use a private channel tied to the specific session for security
        return new PrivateChannel("agent.session.{$this->sessionId}");
    }

    public function broadcastAs(): string
    {
        return 'agent.progress';
    }
}

⚠️ Gotcha: Notice the implementation of ShouldBroadcastNow instead of ShouldBroadcast. When dealing with real-time UI updates for AI typing and tool feedback, you want to bypass the queue worker delay and push directly to Reverb the millisecond the event is instantiated. If you use standard queue broadcasting here, your UI will feel sluggish and disjointed.


4. Handling Long-Running Jobs via Laravel Queues and Reverb

Scenario: An advanced AI agent might take 45 seconds to complete deep research. If a user closes their laptop lid or navigates away and comes back, or if a PHP request hits max execution time, synchronous execution fails catastrophically.

Why it matters: Web servers have strict timeout limits (typically 30–60 seconds via Nginx/Apache/PHP-FPM). AI agents that depend on multiple sequential tool calls will routinely exceed these limits.

Solution: Offload the agent execution loop to a queued job, and let the job broadcast its progress milestones directly via Reverb to the listening client.

Code:

namespace App\Jobs;

use App\Models\AgentSession;
use App\Services\AI\ResearchAgent;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RunAgentSessionJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $timeout = 300; // Allow up to 5 minutes for complex runs

    public function __construct(
        public AgentSession $session,
        public string $prompt
    ) {}

    public function handle(ResearchAgent $agent): void
    {
        try {
            $agent->execute($this->prompt);
            
            $this->session->update(['status' => 'completed']);
        } catch (\Throwable $e) {
            $this->session->update(['status' => 'failed']);
            
            broadcast(new \App\Events\AgentProgressUpdated(
                sessionId: $this->session->id,
                message: 'Agent encountered an error: ' . $e->getMessage(),
                state: 'failed'
            ));
            
            throw $e;
        }
    }
}

When your user clicks "Submit Prompt" in your Vue frontend, your controller simply creates the session model and dispatches the job:

public function store(Request $request, AgentSessionManager $manager)
{
    $session = AgentSession::create([
        'user_id' => $request->user()->id,
        'status' => 'pending'
    ]);

    RunAgentSessionJob::dispatch($session, $request->input('prompt'));

    return response()->json([
        'session_id' => $session->id,
        'status' => 'dispatched'
    ]);
}

5. Consuming Real-Time Agent Events in Vue 3 Composition API

Now let's build the frontend half. We want a clean Vue 3 Composition API hook that manages subscription state, listens to Reverb channels, and exposes reactive variables for our UI components.

Code:

// useAgentStream.js
import { ref, onUnmounted } from 'vue';

export function useAgentStream(sessionId) {
    const steps = ref([]);
    const currentState = ref('idle');
    const isRunning = ref(false);
    const finalOutput = ref(null);

    const subscribe = () => {
        if (!sessionId) return;

        isRunning.value = true;
        currentState.value = 'connecting';

        window.Echo.private(`agent.session.${sessionId}`)
            .listen('.agent.progress', (e) => {
                currentState.value = e.state;
                
                steps.value.push({
                    message: e.message,
                    state: e.state,
                    metadata: e.metadata,
                    timestamp: new Date().toLocaleTimeString()
                });

                if (e.state === 'completed') {
                    isRunning.value = false;
                    finalOutput.value = e.metadata.output ?? null;
                    cleanup();
                }

                if (e.state === 'failed') {
                    isRunning.value = false;
                    cleanup();
                }
            });
    };

    const cleanup = () => {
        window.Echo.leave(`agent.session.${sessionId}`);
    };

    onUnmounted(() => {
        cleanup();
    });

    return {
        steps,
        currentState,
        isRunning,
        finalOutput,
        subscribe
    };
}

Consuming the Hook in a Vue Component

<script setup>
import { ref } from 'vue';
import { useAgentStream } from '@/composables/useAgentStream';
import axios from 'axios';

const prompt = ref('');
const activeSessionId = ref(null);

const { steps, currentState, isRunning, finalOutput, subscribe } = useAgentStream(activeSessionId.value);

const startAgent = async () => {
    try {
        const response = await axios.post('/api/agent/sessions', {
            prompt: prompt.value
        });
        
        activeSessionId.value = response.data.session_id;
        
        // Subscribe once we have the valid session ID
        subscribe();
    } catch (err) {
        console.error('Failed to start agent:', err);
    }
};
</script>

<template>
    <div class="max-w-2xl mx-auto p-6 bg-slate-900 text-slate-100 rounded-xl">
        <h2 class="text-xl font-bold mb-4">AI Research Agent</h2>
        
        <div class="flex gap-2 mb-6">
            <input 
                v-model="prompt" 
                type="text" 
                placeholder="Ask the agent to research..." 
                class="flex-1 bg-slate-800 border border-slate-700 px-4 py-2 rounded-lg"
                :disabled="isRunning"
            />
            <button 
                @click="startAgent" 
                :disabled="isRunning"
                class="bg-indigo-600 px-4 py-2 rounded-lg font-semibold disabled:opacity-50"
            >
                {{ isRunning ? 'Running...' : 'Run Agent' }}
            </button>
        </div>

        <!-- Progress Timeline Feed -->
        <div class="space-y-3 bg-slate-950 p-4 rounded-lg border border-slate-800 min-h-[200px]">
            <div class="text-xs text-slate-500 uppercase tracking-wider font-mono">
                Status: <span class="text-indigo-400">{{ currentState }}</span>
            </div>

            <div v-for="(step, index) in steps" :key="index" class="flex items-start space-x-3 text-sm">
                <span class="text-slate-500 font-mono text-xs mt-0.5">{{ step.timestamp }}</span>
                <div>
                    <p class="text-slate-300">{{ step.message }}</p>
                    <div v-if="step.metadata?.tool" class="text-xs text-amber-400 mt-1 font-mono">
                        ⚙️ Tool: {{ step.metadata.tool }}
                    </div>
                </div>
            </div>
        </div>

        <!-- Final Result Output -->
        <div v-if="finalOutput" class="mt-6 p-4 bg-emerald-950/30 border border-emerald-800/50 rounded-lg">
            <h3 class="font-semibold text-emerald-400 mb-2">Final Output</h3>
            <p class="text-slate-200 whitespace-pre-wrap">{{ finalOutput }}</p>
        </div>
    </div>
</template>

6. Managing UI State, Reconnection Resilience, and Error States

Real-world WebSocket networks are imperfect. Users drive through tunnels, laptops go to sleep, and corporate firewalls aggressively drop idle WebSocket connections. If your application drops connection while an AI agent is halfway through processing a job, your UI shouldn't freeze permanently.

Handling Reconnection in Laravel Echo

Laravel Echo provides built-in connection state listeners that you can leverage to inform your users and request state recovery from the backend if necessary.

window.Echo.connector.pusher.connection.bind('state_change', (states) => {
    // states = { previous: 'connected', current: 'unavailable' }
    if (states.current === 'unavailable' || states.current === 'disconnected') {
        console.warn('WebSocket connection lost. Attempting reconnect...');
    }
    if (states.current === 'connected') {
        console.log('WebSocket reconnected successfully.');
        // Trigger a state sync check with Laravel
    }
});

State Synchronization Recovery Route

If a user reconnects after a drop, they shouldn't miss agent progress. Your backend should expose a simple session state recovery endpoint:

Route::get('/api/agent/sessions/{session}', function (AgentSession $session) {
    // Ensure user owns the session
    abort_unless(auth()->id() === $session->user_id, 403);

    return response()->json([
        'status' => $session->status,
        'steps' => $session->logs()->orderBy('created_at', 'asc')->get()
    ]);
});

On reconnection in Vue, you can fetch this endpoint to instantly hydrate the timeline back to its current truth without requiring a page reload.


7. Security Considerations: Private Channels, Authorization, and Rate Limiting

Because AI agent executions incur real API costs (OpenAI, Anthropic, vector database queries), security is paramount. You cannot allow arbitrary users to listen to or trigger agent sessions belonging to others.

Defining Authorization Rules

In Laravel, private channels are secured via routes/channels.php. Ensure you explicitly authorize the user against the session model:

use App\Models\AgentSession;

Broadcast::channel('agent.session.{sessionId}', function ($user, $sessionId) {
    $session = AgentSession::find($sessionId);
    
    return $session && $session->user_id === $user->id;
});

Protecting Against WebSocket Flooding

Just as you rate-limit HTTP POST endpoints using Laravel's throttle middleware, you must be careful with real-time event triggers. If an unruly client or a compromised frontend script triggers excessive state requests or channel subscriptions, your Reverb server can experience resource exhaustion.

Use Redis-backed rate limiting within your custom jobs and API endpoints to ensure a single user account cannot spawn dozens of concurrent autonomous agent loops simultaneously.


8. Production Performance: Scaling Reverb and Handling Backpressure

When deploying Laravel Reverb to production (e.g., Laravel Forge, Vapor, or a custom Docker swarm), performance tuning ensures smooth multi-client streaming.

Scaling Strategy Comparison

Feature / Dimension Laravel Reverb (Single Node) Reverb with Redis Pub/Sub Cluster Pusher / Ably (Managed SaaS)
Infrastructure Cost Low (Runs on existing VPS) Medium (Requires Redis cluster) High (Pay-per-message pricing)
Max Concurrent Connections Tens of thousands per core Hundreds of thousands Millions
Operational Complexity Low Medium Zero
Latency Sub-millisecond Low Low-to-Medium
Best Use Case Most SaaS applications & dashboards High-traffic enterprise applications Teams avoiding infrastructure management

Handling Backpressure in High-Frequency Streams

If your AI agent outputs streaming tokens at a high frequency (e.g., 100+ chunks per second), do not broadcast every single token individually over Reverb. Instead, buffer or throttle your token emissions on the backend:

protected string $tokenBuffer = '';
protected int $lastBroadcast = 0;

protected function handleToken(string $token): void
{
    $this->tokenBuffer .= $token;
    
    // Broadcast every 100ms rather than every token
    if (microtime(true) - $this->lastBroadcast > 0.1) {
        broadcast(new AgentProgressUpdated(
            sessionId: $this->session->id,
            message: $this->tokenBuffer,
            state: 'streaming'
        ));
        
        $this->tokenBuffer = '';
        $this->lastBroadcast = microtime(true);
    }
}

This simple throttling pattern reduces WebSocket frame overhead by up to 90%, preventing browser frame drops and keeping your Vue reactive rendering silky smooth.


Final Architectural Observation

Streaming AI agent progress from Laravel to Vue no longer requires gluing together disparate Node.js microservices or wrestling with complex third-party billing meters. By combining Laravel Reverb, Queued Jobs, and the Vue 3 Composition API, you get a cohesive, high-performance real-time pipeline built entirely within the ecosystem you already know.

Keep your event payloads focused, buffer high-frequency token chunks, secure your private channels rigorously, and your users will enjoy a responsive, ChatGPT-grade interactive experience without ever staring blindly at a loading spinner again.

Post a Comment

Previous Post Next Post