Build a Vue Dashboard for Human Approval Before AI Agents Execute Actions

Autonomous AI agents are wonderful until they delete a production database at 3:00 AM because an LLM hallucinated a schema migration.

As engineering teams shift from building simple chat interfaces to deploying autonomous agents that write code, trigger cloud infrastructure deployments, execute financial transactions, and modify CRM records, the architecture must change. We can no longer treat agent execution as a fire-and-forget API call.

We need a Human-in-the-Loop (HITL) architecture.

In this deep-dive engineering guide, we will design and build a production-grade Vue 3 dashboard explicitly engineered to intercept, inspect, modify, and authorize or reject actions proposed by AI agents before they ever touch your backend systems.


📋 Table of Contents


The Architectural Problem: Autonomous Chaos vs. Enterprise Reality

Most developers building with modern agent frameworks like LangChain, AutoGen, or custom tool-calling loops start with a naive architecture:

[ LLM Agent ] ---> Executes Tool Directly ---> [ Production DB / Stripe / AWS ]

When you run this locally with a mock database, it feels like magic. The agent determines it needs to update user records, formats a JSON payload, hits your API, and completes the task.

Then you move it to production. The agent encounters an ambiguous prompt injection or a slightly malformed instruction. It decides that "cleaning up inactive accounts" means executing a DROP TABLE users CASCADE; or refunding every transaction from the last 24 hours.

To solve this, we must introduce an asynchronous Hold-and-Verify state machine:

[ LLM Agent ] ---> Generates Action Intent ---> [ Interception Queue ] 
                                                        │
                                                        ▼
[ Production System ] <--- Authorized Payload --- [ Vue 3 HITL Dashboard ]

Building this requires a frontend that isn't just a static CRUD table. It must handle high-frequency WebSocket streams, complex JSON diffs, optimistic UI concurrency, and cryptographic verification logs. Let's build it step by step.


1. Designing the Agent Interception Proxy Pattern

Scenario: Your AI agent wants to execute a Stripe refund tool. Instead of letting the agent call Stripe directly, your backend intercepts the tool execution request, writes it to a Redis-backed queue with a pending_approval status, and suspends the agent's execution thread.

Why it matters: If your frontend dashboard crashes, loses connection, or the human operator is away from their desk, the agent thread cannot hang indefinitely, nor can it silently time out and assume failure.

Solution: Implement an interceptor middleware on your backend that pauses the execution graph and issues a webhook or WebSocket event to your Vue frontend, pairing the event with an absolute expiration TTL.

// backend-interceptor.ts (Node/TypeScript conceptual reference)
import { Redis } from 'ioredis';
import { v4 as uuidv4 } from 'uuid';

interface AgentToolCall {
  toolName: string;
  arguments: Record<string, any>;
  agentId: string;
  sessionId: string;
}

export async function interceptAgentAction(call: AgentToolCall, redis: Redis): Promise<any> {
  const approvalId = uuidv4();
  const payload = {
    id: approvalId,
    ...call,
    status: 'pending',
    createdAt: Date.now(),
    expiresAt: Date.now() + 1000 * 60 * 15 // 15-minute TTL
  };

  // Store in Redis with TTL matching expiration
  await redis.setex(`approval:${approvalId}`, 900, JSON.stringify(payload));
  
  // Publish to Redis channel for WebSocket server broadcast
  await redis.publish('agent:approvals:pending', JSON.stringify(payload));

  // Block and wait for resolution via Redis pub/sub or polling
  return await waitForHumanDecision(approvalId, redis);
}

Why this works: Decoupling agent execution from frontend rendering via Redis ensures that even if 50 agents trigger actions simultaneously, your dashboard consumes a clean, ordered stream of discrete JSON payloads without overwhelming the client.

💡 Practical note: Always implement a hard fallback timeout on the backend. If a human operator doesn't respond within 15 minutes, the action must automatically resolve to a safe state—usually rejected or escalated—so agent threads don't leak memory or exhaust connection pools.


2. Building the Vue 3 Reactive State Engine with Pinia and TypeScript

Scenario: Your Vue dashboard needs to manage hundreds of incoming agent requests across multiple tabs, filter them by risk level, agent ID, and tool type, and instantly reflect approvals or rejections made by other team members in real time.

Why it matters: A reactive store that only handles local state will cause race conditions where two operators approve the same dangerous action simultaneously.

Solution: Build a robust Pinia store using Vue 3 Composition API style (defineStore) with strong TypeScript typings, optimistic state tracking, and centralized normalization.

// stores/agentApprovals.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface PendingAction {
  id: string;
  toolName: string;
  arguments: Record<string, any>;
  agentId: string;
  sessionId: string;
  riskScore: 'low' | 'medium' | 'high' | 'critical';
  status: 'pending' | 'approved' | 'rejected' | 'expired';
  createdAt: number;
  expiresAt: number;
  modifiedArguments?: Record<string, any>;
}

export const useAgentApprovalsStore = defineStore('agentApprovals', () => {
  const actions = ref<Map<string, PendingAction>>(new Map());
  const selectedActionId = ref<string | null>(null);
  const filterRisk = ref<string>('all');

  // Computed list sorted by creation time, filtered by risk
  const sortedPendingActions = computed(() => {
    return Array.from(actions.value.values())
      .filter(action => action.status === 'pending')
      .filter(action => filterRisk.value === 'all' || action.riskScore === filterRisk.value)
      .sort((a, b) => b.createdAt - a.createdAt);
  });

  const selectedAction = computed(() => {
    return selectedActionId.value ? actions.value.get(selectedActionId.value) || null : null;
  });

  function ingestAction(action: PendingAction) {
    actions.value.set(action.id, action);
  }

  function updateActionStatus(id: string, status: 'approved' | 'rejected' | 'expired', modifiedArgs?: Record<string, any>) {
    const action = actions.value.get(id);
    if (action) {
      action.status = status;
      if (modifiedArgs) {
        action.modifiedArguments = modifiedArgs;
      }
    }
  }

  function removeAction(id: string) {
    actions.value.delete(id);
    if (selectedActionId.value === id) {
      selectedActionId.value = null;
    }
  }

  return {
    actions,
    selectedActionId,
    filterRisk,
    sortedPendingActions,
    selectedAction,
    ingestAction,
    updateActionStatus,
    removeAction
  };
});

Why this works: Using a JavaScript Map inside the Pinia store provides $O(1)$ lookups and updates when WebSocket patch events arrive, which keeps the UI performant even when dealing with high-volume agent swarms generating hundreds of actions per hour.


3. Real-Time Event Streaming via WebSockets and SSE

Scenario: Polling an HTTP endpoint every second for pending agent approvals creates unnecessary server load and introduces noticeable latency before actions appear on the screen.

Why it matters: When an AI agent is waiting for approval to execute an urgent customer support refund, every millisecond of human friction counts. The dashboard must update instantly when a new payload arrives.

Solution: Create a resilient WebSocket composable in Vue that handles automatic reconnection, exponential backoff, and heartbeat pings, feeding directly into the Pinia store.

// composables/useAgentWebSocket.ts
import { onMounted, onUnmounted } from 'vue';
import { useAgentApprovalsStore, PendingAction } from '@/stores/agentApprovals';

export function useAgentWebSocket(url: string) {
  const store = useAgentApprovalsStore();
  let socket: WebSocket | null = null;
  let reconnectAttempts = 0;
  let heartbeatTimer: number | null = null;

  function connect() {
    socket = new WebSocket(url);

    socket.onopen = () => {
      reconnectAttempts = 0;
      startHeartbeat();
    };

    socket.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        
        switch (message.type) {
          case 'ACTION_CREATED':
            store.ingestAction(message.payload as PendingAction);
            break;
          case 'ACTION_RESOLVED':
            store.updateActionStatus(message.payload.id, message.payload.status);
            // Optional: remove after animation
            setTimeout(() => store.removeAction(message.payload.id), 1000);
            break;
          default:
            console.warn('Unknown WebSocket message type:', message.type);
        }
      } catch (err) {
        console.error('Failed to parse incoming WebSocket frame:', err);
      }
    };

    socket.onclose = () => {
      stopHeartbeat();
      reconnectWithBackoff();
    };

    socket.onerror = (error) => {
      console.error('WebSocket error encountered:', error);
      socket?.close();
    };
  }

  function reconnectWithBackoff() {
    const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
    reconnectAttempts++;
    setTimeout(connect, delay);
  }

  function startHeartbeat() {
    heartbeatTimer = window.setInterval(() => {
      if (socket?.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({ type: 'PING' }));
      }
    }, 30000);
  }

  function stopHeartbeat() {
    if (heartbeatTimer) clearInterval(heartbeatTimer);
  }

  onMounted(() => connect());
  onUnmounted(() => {
    stopHeartbeat();
    socket?.close();
  });
}

Why this works: Automatic reconnection with exponential backoff prevents your frontend from hammering your WebSocket gateway if your infrastructure undergoes a rolling deployment or network blip.


4. Component Architecture: Diff Viewers and JSON Patch Inspection

Scenario: An AI agent proposes modifying a complex JSON configuration or database record. Simply displaying a raw <pre> block of the JSON makes it impossible for an operator to spot subtle, malicious, or erroneous modifications injected by bad prompts.

Why it matters: Human approvers suffer from cognitive fatigue. If reviewing an action requires mental parsing of raw JSON keys, approvals become rubber-stamps, defeating the entire purpose of the security gateway.

Solution: Build a dedicated Vue component that renders a structured diff view highlighting additions, modifications, and deletions between the current state and the agent's proposed state.

<!-- components/ActionDiffViewer.vue -->
<script setup lang="ts">
import { computed } from 'vue';
import { diffJson } from 'diff';

const props = defineProps<{
  originalState: Record<string, any>;
  proposedState: Record<string, any>;
}>();

const jsonDiffParts = computed(() => {
  const originalStr = JSON.stringify(props.originalState, null, 2);
  const proposedStr = JSON.stringify(props.proposedState, null, 2);
  return diffJson(originalStr, proposedStr);
});
</script>

template>
  <div class="rounded-lg bg-slate-900 p-4 font-mono text-sm text-slate-100 overflow-x-auto shadow-inner border border-slate-800">
    <div class="text-xs text-slate-400 mb-2 uppercase tracking-wider font-semibold">
      Payload Difference Inspection
    </div>
    <pre class="whitespace-pre-wrap"><code><span 
      v-for="(part, index) in jsonDiffParts" 
      :key="index"
      :class="{
        'bg-emerald-950/60 text-emerald-300 border-l-2 border-emerald-500 pl-1': part.added,
        'bg-rose-950/60 text-rose-300 line-through opacity-75 pl-1': part.removed,
        'text-slate-300': !part.added && !part.removed
      }"
    >{{ part.value }}</span></code></pre>
  </div>
</template>

Why this works: By leveraging semantic diffing libraries (diff), you instantly draw the human reviewer's eyes to exactly what the AI agent is changing, reducing review time from minutes to seconds and drastically lowering error rates.

⚠️ Gotcha: Never pass raw unsanitized user-generated strings straight into innerHTML or complex custom parsers. Always rely on structural text diffing libraries that treat object keys and values as inert strings.


5. Granular Decision-Making: Approve, Reject, Edit, and Timeout Policies

Scenario: An agent correctly identifies that a customer needs a refund, but proposes refunding $500 instead of the correct $50. Rejecting the action entirely forces the user to restart the agent workflow, while approving it loses money.

Why it matters: Rigid binary "Approve/Reject" interfaces lead to workflow friction. Operators need the ability to edit the agent's proposed arguments inline before granting authorization.

Solution: Build an editable form wrapper inside the approval drawer that validates the agent's arguments against a Zod schema before sending the authorization back to the backend.

<!-- components/ApprovalDecisionPanel.vue -->
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useAgentApprovalsStore, PendingAction } from '@/stores/agentApprovals';
import ActionDiffViewer from './ActionDiffViewer.vue';

const props = defineProps<{
  action: PendingAction;
}>();

const store = useAgentApprovalsStore();
const isEditing = ref(false);
const editableArguments = ref<string>('');
const editError = ref<string | null>(null);

watch(() => props.action, (newAction) => {
  editableArguments.value = JSON.stringify(newAction.arguments, null, 2);
  isEditing.value = false;
  editError.value = null;
}, { immediate: true });

async function handleApprove(withEdits: boolean) {
  let finalArgs = props.action.arguments;
  
  if (withEdits) {
    try {
      finalArgs = JSON.parse(editableArguments.value);
      editError.value = null;
    } catch (e: any) {
      editError.value = `Invalid JSON format: ${e.message}`;
      return;
    }
  }

  // Dispatch API call to backend authorization endpoint
  try {
    const response = await fetch(`/api/agent/approvals/${props.action.id}/resolve`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        decision: 'approved',
        modifiedArguments: withEdits ? finalArgs : undefined
      })
    });

    if (!response.ok) throw new Error('Failed to submit authorization');

    store.updateActionStatus(props.action.id, 'approved', finalArgs);
  } catch (err: any) {
    alert(`Authorization failed: ${err.message}`);
  }
}

async function handleReject() {
  try {
    await fetch(`/api/agent/approvals/${props.action.id}/resolve`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ decision: 'rejected' })
    });
    store.updateActionStatus(props.action.id, 'rejected');
  } catch (err: any) {
    alert(`Rejection failed: ${err.message}`);
  }
}
</script>

<template>
  <div class="bg-slate-950 border border-slate-800 rounded-xl p-6 flex flex-col gap-6 text-slate-100 shadow-xl">
    <div class="flex justify-between items-center border-b border-slate-800 pb-4">
      <div>
        <span class="text-xs uppercase tracking-wider px-2.5 py-1 rounded-md bg-indigo-950 text-indigo-400 font-semibold border border-indigo-800/50">
          Tool: {{ action.toolName }}
        </span>
        <h3 class="text-lg font-bold mt-2 text-slate-100">Session: {{ action.sessionId }}</h3>
      </div>
      <div class="text-right text-xs text-slate-400 font-mono">
        Agent ID: {{ action.agentId }}
      </div>
    </div>

    <!-- Payload Inspection -->
    <div class="flex flex-col gap-3">
      <div class="flex justify-between items-center">
        <span class="text-sm font-medium text-slate-300">Proposed Arguments</span>
        <button 
          @click="isEditing = !isEditing" 
          class="text-xs text-indigo-400 hover:text-indigo-300 underline underline-offset-4"
        >
          {{ isEditing ? 'Cancel Edit' : 'Edit Before Approve' }}
        </button>
      </div>

      <div v-if="!isEditing">
        <ActionDiffViewer 
          :originalState="{}" 
          :proposedState="action.arguments" 
        />
      </div>

      <div v-else class="flex flex-col gap-2">
        <textarea 
          v-model="editableArguments"
          rows="8"
          class="w-full rounded-lg bg-slate-900 border border-slate-700 p-3 font-mono text-sm text-amber-300 focus:outline-none focus:border-indigo-500"
        ></textarea>
        <p v-if="editError" class="text-xs text-rose-400 font-medium">{{ editError }}</p>
      </div>
    </div>

    <!-- Action Buttons -->
    <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-800">
      <button 
        @click="handleReject"
        class="px-4 py-2 rounded-lg bg-rose-950/40 hover:bg-rose-900/50 text-rose-300 font-medium text-sm border border-rose-800/60 transition-colors"
      >
        Reject Action
      </button>

      <button 
        @click="handleApprove(isEditing)"
        class="px-5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium text-sm shadow-lg shadow-indigo-950 transition-all flex items-center gap-2"
      >
        <span>{{ isEditing ? 'Approve with Edits' : 'Approve Execution' }}</span>
      </button>
    </div>
  </div>
</template>

Why this works: Empowering engineers and operators to edit parameters inline transforms the dashboard from a rigid gatekeeper into an active agent collaboration tool, solving the common dilemma where minor parameter errors block productive automation.


6. Optimistic UI Updates and Error Recovery Under Network Partitions

Scenario: An operator clicks "Approve Execution", but their corporate VPN stutters for 3 seconds. If the button sits frozen with no visual feedback, the operator clicks it three more times, potentially triggering duplicate API dispatches.

Why it matters: Distributed AI agent systems execute high-stakes mutations (payments, infrastructure provisioning). Double submissions can trigger catastrophic state duplication.

Solution: Implement state transitions with optimistic locking indicators and idempotent request keys in your Vue frontend.

// composables/useOptimisticApproval.ts
import { ref } from 'vue';
import { useAgentApprovalsStore } from '@/stores/agentApprovals';

export function useOptimisticApproval() {
  const store = useAgentApprovalsStore();
  const processingIds = ref<Set<string>>(new Set());

  async function resolveActionOptimistically(
    id: string, 
    decision: 'approved' | 'rejected', 
    modifiedArgs?: Record<string, any>
  ) {
    if (processingIds.value.has(id)) return; // Prevent double-clicks
    
    processingIds.value.add(id);
    const previousState = store.actions.get(id);

    // Optimistically remove from active pending view immediately
    store.updateActionStatus(id, decision === 'approved' ? 'approved' : 'rejected', modifiedArgs);

    const idempotencyKey = crypto.randomUUID();

    try {
      const response = await fetch(`/api/agent/approvals/${id}/resolve`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Idempotency-Key': idempotencyKey
        },
        body: JSON.stringify({ decision, modifiedArguments: modifiedArgs })
      });

      if (!response.ok) {
        throw new Error(`Server returned status ${response.status}`);
      }
    } catch (err) {
      // Rollback state on network failure
      if (previousState) {
        store.actions.set(id, previousState);
      }
      console.error('Network partition detected. Rolling back optimistic UI update:', err);
      alert('Failed to transmit decision. Network error; state restored.');
    } finally {
      processingIds.value.delete(id);
    }
  }

  return {
    processingIds,
    resolveActionOptimistically
  };
}

Why this works: Combining X-Idempotency-Key headers on the backend with optimistic rollback patterns on the frontend ensures that even under unstable network conditions, actions are executed exactly once and the UI never falls out of sync with the database.


7. Security, Cryptographic Audit Logs, and Tamper-Proof Trailing

Scenario: An internal audit reveals that an unauthorized database script was run by an AI agent, and you need to prove definitively which human engineer authorized it, exactly what IP address they used, and whether the payload was altered.

Why it matters: SOC2, HIPAA, and EU AI Act regulations require non-repudiable audit trails for autonomous systems. Standard database logs can be altered by database administrators with superuser access.

Solution: Hash every approval event on the backend using SHA-256 chaining (Merkle-style logging) and display the cryptographic verification badge directly within the Vue dashboard audit drawer.

<!-- components/AuditVerificationBadge.vue -->
<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps<{
  signatureHash: string;
  timestamp: number;
  approvedBy: string;
}>();

const truncatedHash = computed(() => {
  if (!props.signatureHash) return 'Unsigned';
  return `${props.signatureHash.slice(0, 8)}...${props.signatureHash.slice(-8)}`;
});

const formattedDate = computed(() => {
  return new Date(props.timestamp).toISOString();
});
</script>

<template>
  <div class="flex items-center gap-3 p-3 rounded-lg bg-slate-900 border border-slate-800 text-xs font-mono">
    <div class="flex items-center gap-1.5 text-emerald-400">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
      </svg>
      <span>Cryptographically Verified</span>
    </div>
    <div class="text-slate-500">|</div>
    <div class="text-slate-300">By: <span class="text-indigo-400">{{ approvedBy }}</span></div>
    <div class="text-slate-500">|</div>
    <div class="text-slate-400">Hash: <span class="text-amber-400" :title="signatureHash">{{ truncatedHash }}</span></div>
    <div class="text-slate-500">|</div>
    <div class="text-slate-400">{{ formattedDate }}</div>
  </div>
</template>

Why this works: Exposing cryptographic verification markers directly in the UI instills absolute team trust that the dashboard interface cannot be bypassed by direct backend database tampering.


Production Architecture Decision Guide

When deciding how to structure your human-in-the-loop agent authorization pipeline, evaluate your infrastructure choices across these key architectural dimensions:

Dimension Polling Architecture (REST) WebSocket + Redis Pub/Sub Server-Sent Events (SSE)
Complexity Very Low High Medium
Latency High (Poll interval dependent) Sub-millisecond Sub-second (Uni-directional)
Server Load High at scale (N requests/sec) Low (Persistent sockets) Low (HTTP chunk streaming)
NAT / Firewall Issues None Occasional corporate proxy blocks None (Standard HTTP)
Best Use Case Small internal proofs-of-concept High-frequency multi-operator agent swarms Standard production dashboards needing read-only streams

What I Would Choose For Production

If you are building an enterprise-grade agent gateway today, choose WebSockets paired with a Redis pub/sub backbone.

While Server-Sent Events (SSE) are simpler to set up, human-in-the-loop dashboards are inherently bidirectional: operators submit approvals, edit JSON arguments, and send heartbeat pings simultaneously while other team members view the same stream. WebSockets eliminate the need for managing separate HTTP POST endpoints for actions and GET endpoints for streams, keeping your Vue composition logic clean, unified, and lightning fast.

Post a Comment

Previous Post Next Post