📋 Table of Contents
- The Autonomous Agent Trust Gap
- 1. The Planning Phase: Capturing the Structured Intent from LLMs
- 2. Data Modeling the Plan: From Flat Arrays to Directed Acyclic Graphs
- 3. Crafting the Vue 3 Composition API State Store
- 4. Building the Interactive UI: Drag-and-Drop, Inline Editing, and Step Injections
- 5. Real-Time Constraint Validation and Dependency Resolution
- 6. Optimistic Locking and Syncing Edits Back to the Backend Engine
- 7. Handling Streaming Updates While the User Is Editing
- The Architectural Verdict: When to Intercept vs. When to Let Go
The Autonomous Agent Trust Gap
We have all experienced it. You prompt an advanced AI agent to refactor a database schema, spin up a multi-service deployment, or execute a complex data migration. The model returns a wall of confident text, declares that the operation is complete, and proceeds to drop a production index because it misinterpreted a secondary WHERE clause.
Autonomous agents are phenomenal at reasoning and sequence generation, but they suffer from a terminal lack of situational awareness. They don’t know that Friday afternoon deployments are forbidden, they don’t realize your staging environment uses a different port configuration, and they certainly won't hesitate to delete your customer analytics table if the prompt leaves room for ambiguity.
The industry standard response to this risk has been binary: either run the agent in fully autonomous "YOLO mode" and pray for the best, or require human-in-the-loop (HITL) approval for every single tool call. Both approaches fail at scale. YOLO mode causes catastrophic data loss. Tool-call approval fatigue causes developers to mindlessly click "Approve" on every prompt, defeating the entire purpose of security guardrails.
The middle ground—and the only sustainable architectural pattern for production AI applications—is Plan Interception.
Instead of forcing a human to approve opaque tool executions one by one, your system asks the LLM to generate an explicit, structured execution plan before touching any side effects. Your frontend then renders this plan as an interactive review screen in Vue, empowering the user to inspect, reorder, edit, delete, or inject steps before final authorization.
In this deep-dive guide, we are going to build a production-grade Vue 3 review screen that transforms an AI agent’s raw execution plan into an editable, validated, and resilient workflow dashboard.
1. The Planning Phase: Capturing the Structured Intent from LLMs
Scenario: Your AI assistant receives a prompt to clean up abandoned user accounts across three microservices. It responds with a conversational block explaining how it plans to execute the task, followed by unparsed text instructions. Your backend has no safe way to execute freeform prose.
Why it matters: If you let an LLM execute actions directly from text output, your frontend cannot render an interactive interface. You need guaranteed structural predictability. Relying on regex parsing of Markdown code blocks will inevitably break the moment the model decides to write an extra sentence outside the JSON tags.
Solution:
Force the LLM to output its plan using strict schema validation via provider-level structured outputs (such as OpenAI's response_format with JSON Schema, Anthropic's tool-use parameter forcing, or Instructor in Python/TypeScript). Never accept raw text when you need a directed execution graph.
Code:
// backend/services/planner.ts
import OpenAI from 'openai';
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';
const AgentStepSchema = z.object({
id: z.string().describe("Unique kebab-case identifier, e.g., 'fetch-users'"),
title: z.string().describe("Human-readable action title"),
tool: z.enum(['database_query', 'stripe_api', 'email_dispatch', 'log_audit']),
payload: z.record(z.any()).describe("Strict arguments passed to the tool executor"),
dependencies: z.array(z.string()).describe("IDs of steps that must complete successfully before this runs"),
riskLevel: z.enum(['low', 'medium', 'high']),
});
const AgentPlanSchema = z.object({
summary: z.string().describe("High-level overview of what this plan intends to achieve"),
steps: z.array(AgentStepSchema),
});
export type AgentPlan = z.infer<typeof AgentPlanSchema>;
export async function generateExecutionPlan(prompt: string): Promise<AgentPlan> {
const openai = new OpenAI();
const completion = await openai.beta.chat.completions.parse({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a precise infrastructure automation agent. Break down user requests into safe, atomic, ordered execution steps.' },
{ role: 'user', content: prompt }
],
response_format: zodResponseFormat(AgentPlanSchema, 'agent_plan'),
});
const plan = completion.choices[0].message.parsed;
if (!plan) throw new Error("Failed to parse agent execution plan.");
return plan;
}
Why this works:
By leveraging native constrained decoding (response_format), the model provider's inference engine masks logits during token generation, making it structurally impossible for the model to return invalid JSON or stray outside your Zod schema.
💡 Practical note: Even with structured outputs, LLMs frequently generate circular step dependencies (e.g., Step A depends on Step B, which depends on Step A). Always run a cycle-detection check on the backend before sending the plan to your Vue frontend.
2. Data Modeling the Plan: From Flat Arrays to Directed Acyclic Graphs
Scenario: Your backend sends the parsed JSON plan to the Vue frontend. You store the steps in a flat array inside a reactive ref. When a user tries to drag a step or delete an item, the UI breaks because steps implicitly depend on indices or missing parent references.
Why it matters: An AI-generated plan is rarely a simple linear checklist ($1 \to 2 \to 3$). It is a Directed Acyclic Graph (DAG). If a user deletes Step 2, any downstream step depending on Step 2's output will silently fail or throw runtime errors during execution.
Solution: Normalize the plan data structure on the client side. Maintain a dictionary (lookup map) alongside the array of steps, and implement explicit relationship tracking so the Vue interface can instantly highlight orphaned dependencies or invalid execution orders.
Code:
// types/plan.ts
export type RiskLevel = 'low' | 'medium' | 'high';
export interface PlanStep {
id: string;
title: string;
tool: string;
payload: Record<string, any>;
dependencies: string[]; // IDs of prerequisite steps
riskLevel: RiskLevel;
isEditing?: boolean;
}
export interface NormalizedPlan {
summary: string;
steps: Record<string, PlanStep>;
executionOrder: string[]; // Topological sort of step IDs
}
export function normalizePlan(raw: { summary: string; steps: PlanStep[] }): NormalizedPlan {
const stepsMap: Record<string, PlanStep> = {};
for (const step of raw.steps) {
stepsMap[step.id] = { ...step, isEditing: false };
}
return {
summary: raw.summary,
steps: stepsMap,
executionOrder: raw.steps.map(s => s.id) // Initial order
};
}
Why this works:
Using a record lookup map (Record<string, PlanStep>) guarantees $O(1)$ updates when a user edits a step's payload or toggles its risk level. You never have to iterate over an entire array just to update a single step's properties.
3. Crafting the Vue 3 Composition API State Store
Scenario: As your review screen grows to include undo/redo history, step reordering, inline payload editing, and validation warnings, your Vue component turns into a 1,000-line monolithic script with prop drilling passing state down five levels.
Why it matters: Plan editing is state-heavy. Users expect to modify payloads, reorder steps, discard changes, and submit the revised plan back to the server without losing their place. Global stores like Pinia excel here, but they must be structured carefully to support local draft states without mutating the pristine original plan.
Solution:
Build a dedicated Pinia store that maintains both the originalPlan (received from the backend) and the draftPlan (actively modified by the user in the Vue review screen), complete with a computed isDirty flag and localized mutation actions.
Code:
// stores/usePlanStore.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { NormalizedPlan, PlanStep } from '@/types/plan';
import { normalizePlan } from '@/types/plan';
export const usePlanStore = defineStore('agentPlan', () => {
const pristinePlan = ref<NormalizedPlan | null>(null);
const draftPlan = ref<NormalizedPlan | null>(null);
const activeStepId = ref<string | null>(null);
const isDirty = computed(() => {
if (!pristinePlan.value || !draftPlan.value) return false;
return JSON.stringify(pristinePlan.value) !== JSON.stringify(draftPlan.value);
});
const orderedSteps = computed(() => {
if (!draftPlan.value) return [];
return draftPlan.value.executionOrder.map(id => draftPlan.value!.steps[id]);
});
function loadPlan(raw: { summary: string; steps: PlanStep[] }) {
const normalized = normalizePlan(raw);
pristinePlan.value = JSON.parse(JSON.stringify(normalized));
draftPlan.value = normalized;
}
function updateStepPayload(stepId: string, newPayload: Record<string, any>) {
if (!draftPlan.value) return;
if (draftPlan.value.steps[stepId]) {
draftPlan.value.steps[stepId].payload = newPayload;
}
}
function removeStep(stepId: string) {
if (!draftPlan.value) return;
// Remove from execution order
draftPlan.value.executionOrder = draftPlan.value.executionOrder.filter(id => id !== stepId);
// Delete from map
delete draftPlan.value.steps[stepId];
// Clean up dangling dependencies in remaining steps
for (const id of draftPlan.value.executionOrder) {
const step = draftPlan.value.steps[id];
step.dependencies = step.dependencies.filter(depId => depId !== stepId);
}
}
function resetToOriginal() {
if (!pristinePlan.value) return;
draftPlan.value = JSON.parse(JSON.stringify(pristinePlan.value));
}
return {
pristinePlan,
draftPlan,
activeStepId,
isDirty,
orderedSteps,
loadPlan,
updateStepPayload,
removeStep,
resetToOriginal,
};
});
Why this works: Deep cloning the pristine plan ensures that hitting a "Reset Changes" button requires zero asynchronous network requests. It also gives you a precise baseline to calculate diffs when sending the finalized plan back to your backend orchestrator.
4. Building the Interactive UI: Drag-and-Drop, Inline Editing, and Step Injections
Scenario: Your users need to reorder AI-generated steps because the agent mistakenly placed a database migration after sending confirmation emails to customers. They also need to edit JSON payloads without breaking syntax or inject custom emergency override steps.
Why it matters: Standard form inputs are too rigid for arbitrary JSON tool payloads. Developers and power users expect rich syntax highlighting, smooth drag-and-drop reordering, and instant visual cues for high-risk actions.
Solution: Create a modular Vue component tree featuring draggable step cards, an embedded JSON editor (or structured key-value form fields based on tool type), and prominent risk badges.
Code:
<!-- components/AgentPlanReview.vue -->
<script setup lang="ts">
import { usePlanStore } from '@/stores/usePlanStore';
import { VueDraggable } from 'vue-draggable-plus';
import { AlertTriangle, Trash2, Edit3, Check, X } from 'lucide-vue-next';
const store = usePlanStore();
function getRiskBadgeClass(risk: string) {
switch (risk) {
case 'high': return 'bg-red-500/10 text-red-400 border-red-500/20';
case 'medium': return 'bg-amber-500/10 text-amber-400 border-amber-500/20';
default: return 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20';
}
}
</script>
template
<template>
<div class="max-w-4xl mx-auto p-6 bg-slate-950 text-slate-100 rounded-xl border border-slate-800">
<header class="mb-6 flex items-center justify-between border-b border-slate-800 pb-4">
<div>
<h1 class="text-xl font-bold tracking-tight">AI Agent Execution Plan</h1>
<p class="text-sm text-slate-400 mt-1">{{ store.draftPlan?.summary }}</p>
</div>
<div v-if="store.isDirty" class="flex items-center gap-3">
<span class="text-xs text-amber-400 font-medium">Modified locally</span>
<button
@click="store.resetToOriginal()"
class="px-3 py-1.5 text-xs font-semibold bg-slate-800 hover:bg-slate-700 rounded-lg transition"
>
Reset
</button>
</div>
</header>
<!-- Draggable Step List -->
<VueDraggable
v-model="store.draftPlan!.executionOrder"
item-key="id"
class="space-y-4"
handle=".drag-handle"
>
<div
v-for="(step, index) in store.orderedSteps"
:key="step.id"
class="p-4 bg-slate-900 border border-slate-800 rounded-lg transition hover:border-slate-700 relative group"
>
<div class="flex items-center justify-between">
<div class="flex items-center gap-3">
<span class="drag-handle cursor-grab text-slate-600 hover:text-slate-400 font-mono text-sm">
#{{ index + 1 }}
</span>
<h3 class="font-semibold text-slate-200">{{ step.title }}</h3>
<span :class="['px-2 py-0.5 text-xs rounded-full border', getRiskBadgeClass(step.riskLevel)]">
{{ step.riskLevel }} risk
</span>
</div>
<div class="flex items-center gap-2">
<button
@click="store.removeStep(step.id)"
class="p-1.5 text-slate-500 hover:text-red-400 rounded-md transition"
title="Delete Step"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<!-- Tool Payload Preview -->
<div class="mt-3 bg-slate-950 p-3 rounded border border-slate-800/80 font-mono text-xs text-slate-300 overflow-x-auto">
<span class="text-cyan-400 font-semibold">tool:</span> {{ step.tool }}
<div class="mt-1 text-slate-400">
{{ JSON.stringify(step.payload, null, 2) }}
</div>
</div>
<!-- Dependencies footer -->
<div v-if="step.dependencies.length > 0" class="mt-3 flex items-center gap-2 text-xs text-slate-500">
<span>Depends on:</span>
<span v-for="dep in step.dependencies" :key="dep" class="px-1.5 py-0.5 bg-slate-800 rounded text-slate-300 font-mono">
{{ dep }}
</span>
</div>
</div>
</VueDraggable>
</div>
</template>
Why this works:
Using vue-draggable-plus (a modern wrapper around Sortable.js compatible with Vue 3 Composition API) allows users to physically reorder execution steps while automatically synchronizing the executionOrder array in your Pinia store.
⚠️ Gotcha: When using drag-and-drop with complex nested state, never mutate array indices directly in template events without updating your underlying dependency graph. If Step C depends on Step A, and the user drags Step A below Step C, your UI must either flag a dependency violation or automatically adjust the relationship.
5. Real-Time Constraint Validation and Dependency Resolution
Scenario:
A user deletes Step A from the review screen. However, Step B and Step C still list Step A in their dependencies array. When you submit the plan to the execution engine, the backend crashes with a missing dependency reference.
Why it matters: AI agents generate plans assuming a pristine linear or branching flow. Once humans start hacking away at steps, deleting prerequisites, or injecting new tasks, the plan's integrity collapses unless validated in real time on the client.
Solution: Implement a reactive validation computed property in your Vue store that inspects the DAG before submission, instantly highlighting dangling references and missing requirements directly in the UI.
Code:
// stores/usePlanStore.ts (Validation Extension)
export interface PlanValidationError {
stepId: string;
message: string;
}
// Inside your store definition:
const validationErrors = computed<PlanValidationError[]>(() => {
if (!draftPlan.value) return [];
const errors: PlanValidationError[] = [];
const validIds = new Set(draftPlan.value.executionOrder);
for (const id of draftPlan.value.executionOrder) {
const step = draftPlan.value.steps[id];
// Check for dangling dependencies
for (const depId of step.dependencies) {
if (!validIds.has(depId)) {
errors.push({
stepId: step.id,
message: `Depends on missing or deleted step '${depId}'`
});
}
}
// Check for high-risk unconfirmed actions
if (step.riskLevel === 'high' && !step.payload?.explicitlyConfirmed) {
errors.push({
stepId: step.id,
message: `High-risk step '${step.title}' requires explicit user confirmation.`
});
}
}
return errors;
});
const isValid = computed(() => validationErrors.value.length === 0);
Why this works: Running validation locally inside computed properties means the "Execute Plan" button can be disabled instantly with zero network round-trips, providing immediate feedback to the operator.
6. Optimistic Locking and Syncing Edits Back to the Backend Engine
Scenario: While the user is spending 5 minutes reviewing and editing the AI's 12-step plan in your Vue interface, the underlying database records or API tokens change. When they finally click "Execute", the plan executes against stale state.
Why it matters: Distributed agent systems are asynchronous. If state drift occurs between plan generation and plan execution, the agent's pre-calculated payloads may reference outdated resource IDs.
Solution: Include a cryptographic content hash or version timestamp in the plan payload when it arrives from the backend. When submitting edits, send both the modified plan and the original hash for optimistic concurrency control.
Code:
// services/api.ts
import type { NormalizedPlan } from '@/types/plan';
interface ExecutionPayload {
planId: string;
versionHash: string;
steps: {
id: string;
tool: string;
payload: Record<string, any>;
dependencies: string[];
}[];
}
export async function submitEditedPlan(planId: string, versionHash: string, plan: NormalizedPlan) {
const payload: ExecutionPayload = {
planId,
versionHash,
steps: plan.executionOrder.map(id => {
const s = plan.steps[id];
return {
id: s.id,
tool: s.tool,
payload: s.payload,
dependencies: s.dependencies
};
})
};
const response = await fetch('/api/agent/plans/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.status === 409) {
throw new Error("Plan version conflict: The environment state changed while you were editing.");
}
if (!response.ok) {
throw new Error("Failed to dispatch execution plan.");
}
return response.json();
}
Why this works: Optimistic locking prevents silent data corruption. If another agent or user modified the underlying resource pool, the backend rejects the stale plan, forcing your Vue app to fetch the latest state and reconcile conflicts.
7. Handling Streaming Updates While the User Is Editing
Scenario: For complex, multi-stage workflows, your backend streams the AI-generated plan incrementally using Server-Sent Events (SSE) or WebSockets. While the user is already editing Steps 1 through 3, the LLM is still streaming Steps 4 through 8 from the server.
Why it matters: If your Vue store blindly overwrites state every time a new chunk arrives from the SSE stream, it will wipe out the user's local edits, triggering immense frustration.
Solution: Implement a merge strategy where incoming stream chunks only append new steps or update unedited properties, while locking any step the user is actively interacting with.
Code:
// composables/usePlanStream.ts
import { usePlanStore } from '@/stores/usePlanStore';
import type { PlanStep } from '@/types/plan';
export function usePlanStream(planId: string) {
const store = usePlanStore();
function connectStream() {
const eventSource = new EventSource(`/api/agent/plans/${planId}/stream`);
eventSource.onmessage = (event) => {
const chunk = JSON.parse(event.data);
// If user has modified this step locally, ignore incoming stream updates for it
if (store.isDirty) {
console.warn("Skipping stream update due to active local edits.");
return;
}
// Otherwise, merge new steps into draft plan
if (chunk.type === 'plan_update') {
store.loadPlan(chunk.data);
}
};
eventSource.onerror = () => {
eventSource.close();
};
}
return { connectStream };
}
Why this works:
Checking store.isDirty before applying streaming patches prevents race conditions between background AI generation and active human intervention.
The Architectural Verdict: When to Intercept vs. When to Let Go
Not every AI agent workflow requires an editable Vue review screen. Adding human friction to low-stakes tasks destroys the speed advantage that LLMs provide.
Use the following decision matrix to determine when to build an intercept review screen versus when to let the agent run autonomously:
| Dimension | Autonomous Execution (YOLO Mode) | Intercept & Edit Review Screen |
|---|---|---|
| Side Effects | Read-only (e.g., generating reports, querying logs) | Write/Mutate (e.g., database writes, API calls, deployments) |
| Reversibility | Easily reversible or idempotent | Irreversible (e.g., deleting records, sending external emails) |
| Confidence Threshold | High determinism, narrow prompt scope | High ambiguity, multi-step orchestration |
| User Persona | End-consumer or automated cron job | Senior engineer, admin, or technical operator |
| Best Stack Fit | Background workers + WebSockets | Vue 3 + Pinia + Backend DAG Validator |
By treating AI agent outputs as draft proposals rather than final commands, you shift your frontend architecture from passive display to active governance. Your users regain absolute control, your systems stay protected against hallucinations, and your AI agents finally become reliable partners in production.