Add script/TTS step handlers, dashboard, and pipeline UI (#35, #36, #43, #44)

StepHandler abstraction (app/Support/VideoWorkflow/StepHandlers/) plugs
into WorkflowEngine without coupling it to how any given step type is
actually executed:
- ScriptGenerationHandler: builds a prompt from the project's title/
  description (or an explicit outline/tone/keywords/target length in
  step input), generates via an active OpenAI AiProvider, stores the
  result as a 'script' asset.
- TtsVoiceoverHandler: voices step.input.text, or falls back to the
  project's latest script asset, via an active ElevenLabs AiProvider;
  voice_id/model_id are configurable per step. No direct "speed"
  control — ElevenLabs' base TTS endpoint doesn't expose one.

RunWorkflowStepJob resolves a step's handler by type and runs it on
the queue, matching the existing PublishPostJob pattern (including a
stale-dispatch guard: no-op if the step isn't 'in_progress' anymore).

UI, under its own /video-projects routes and nav entry — separate
from /projects per the earlier decision:
- VideoProjects/Index (#43): list projects with status and step
  progress, create new ones.
- VideoProjects/Show (#44): start a project from a WorkflowTemplate or
  a hardcoded default 8-step pipeline; per-step Run/Approve/Reject/
  Retry/Skip actions; auto-queues the next step after any transition
  when a handler exists for its type (steps with no handler yet just
  sit in_progress rather than auto-failing); lists project assets.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
m105
2026-08-06 20:56:01 +03:00
co-authored by Claude Sonnet 5
parent 0e315ada04
commit 55fa2ebfda
17 changed files with 1105 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Jobs;
use App\Models\WorkflowStep;
use App\Support\VideoWorkflow\StepHandlers\StepHandlerManager;
use App\Support\VideoWorkflow\WorkflowEngine;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Throwable;
class RunWorkflowStepJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $timeout = 180;
public function __construct(public readonly int $stepId) {}
public function handle(StepHandlerManager $handlers, WorkflowEngine $engine): void
{
$step = WorkflowStep::find($this->stepId);
// Stale/duplicate dispatch — the step moved on (or was retried and
// re-dispatched) before this run got picked up.
if (! $step || $step->status !== 'in_progress') {
return;
}
$handler = $handlers->resolve($step->type);
if (! $handler) {
$engine->failStep($step, "No handler registered for step type '{$step->type}'.");
return;
}
try {
$handler->handle($step, $engine);
} catch (Throwable $e) {
Log::error('workflow step handler threw', ['step_id' => $step->id, 'error' => $e->getMessage()]);
$fresh = $step->fresh();
if ($fresh && $fresh->status === 'in_progress') {
$engine->failStep($fresh, $e->getMessage());
}
}
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Livewire\VideoProjects;
use App\Models\VideoProject;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('components.layouts.app')]
class Index extends Component
{
public bool $showForm = false;
public string $title = '';
public ?string $description = null;
public function render()
{
return view('livewire.video-projects.index', [
'projects' => VideoProject::withCount([
'steps',
'steps as completed_steps_count' => fn ($q) => $q->whereIn('status', ['completed', 'skipped']),
])
->with(['steps' => fn ($q) => $q->whereNotIn('status', ['completed', 'skipped'])->orderBy('order')->limit(1)])
->orderByDesc('created_at')
->get(),
]);
}
public function create(): void
{
$this->title = '';
$this->description = null;
$this->resetValidation();
$this->showForm = true;
}
public function save(): void
{
$validated = $this->validate([
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string'],
]);
$project = VideoProject::create($validated);
$this->showForm = false;
$this->redirect(route('video-projects.show', $project), navigate: true);
}
public function delete(int $id): void
{
VideoProject::findOrFail($id)->delete();
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace App\Livewire\VideoProjects;
use App\Jobs\RunWorkflowStepJob;
use App\Models\VideoProject;
use App\Models\WorkflowStep;
use App\Models\WorkflowTemplate;
use App\Support\VideoWorkflow\StepHandlers\StepHandlerManager;
use App\Support\VideoWorkflow\WorkflowEngine;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('components.layouts.app')]
class Show extends Component
{
public VideoProject $videoProject;
public string $workflowTemplateId = '';
public ?string $notice = null;
public function mount(VideoProject $videoProject): void
{
$this->videoProject = $videoProject;
}
public function render()
{
$this->videoProject->refresh();
return view('livewire.video-projects.show', [
'steps' => $this->videoProject->steps()->with('assets')->get(),
'assets' => $this->videoProject->assets()->orderByDesc('created_at')->get(),
'templates' => WorkflowTemplate::orderBy('name')->get(),
'hasActiveStep' => $this->videoProject->steps()
->whereIn('status', ['pending', 'in_progress'])
->exists(),
]);
}
public function startWithTemplate(WorkflowEngine $engine): void
{
if (! $this->workflowTemplateId) {
$this->notice = 'Pick a template first.';
return;
}
$template = WorkflowTemplate::findOrFail($this->workflowTemplateId);
$engine->startFromTemplate($this->videoProject, $template);
$this->runCurrentStepIfHandled($engine);
}
public function startDefault(WorkflowEngine $engine): void
{
$engine->start($this->videoProject, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover', 'requires_approval' => true],
['type' => 'storyboard', 'requires_approval' => true],
['type' => 'video_generation', 'requires_approval' => true],
['type' => 'video_editing', 'requires_approval' => true],
['type' => 'thumbnail_generation', 'requires_approval' => true],
['type' => 'metadata_generation', 'requires_approval' => true],
['type' => 'youtube_publish', 'requires_approval' => true],
]);
$this->runCurrentStepIfHandled($engine);
}
public function runStep(int $stepId): void
{
RunWorkflowStepJob::dispatch($stepId);
$this->notice = 'Step queued to run.';
}
public function approveStep(int $stepId, WorkflowEngine $engine): void
{
$engine->approveStep(WorkflowStep::findOrFail($stepId));
$this->runCurrentStepIfHandled($engine);
}
public function rejectStep(int $stepId, WorkflowEngine $engine): void
{
$engine->rejectStep(WorkflowStep::findOrFail($stepId));
}
public function retryStep(int $stepId, WorkflowEngine $engine): void
{
$step = $engine->retryStep(WorkflowStep::findOrFail($stepId));
RunWorkflowStepJob::dispatch($step->id);
}
public function skipStep(int $stepId, WorkflowEngine $engine): void
{
$engine->skipStep(WorkflowStep::findOrFail($stepId));
$this->runCurrentStepIfHandled($engine);
}
private function runCurrentStepIfHandled(WorkflowEngine $engine): void
{
$current = $engine->currentStep($this->videoProject->fresh());
if ($current && $current->status === 'in_progress' && app(StepHandlerManager::class)->resolve($current->type)) {
RunWorkflowStepJob::dispatch($current->id);
}
}
}
+8
View File
@@ -11,6 +11,9 @@ use App\Support\Publishing\PublisherManager;
use App\Support\Publishing\RedditPublisher; use App\Support\Publishing\RedditPublisher;
use App\Support\Publishing\TwitterPublisher; use App\Support\Publishing\TwitterPublisher;
use App\Support\Publishing\WordPressPublisher; use App\Support\Publishing\WordPressPublisher;
use App\Support\VideoWorkflow\StepHandlers\ScriptGenerationHandler;
use App\Support\VideoWorkflow\StepHandlers\StepHandlerManager;
use App\Support\VideoWorkflow\StepHandlers\TtsVoiceoverHandler;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
@@ -32,6 +35,11 @@ class AppServiceProvider extends ServiceProvider
'stability_ai' => $app->make(StabilityAiDriver::class), 'stability_ai' => $app->make(StabilityAiDriver::class),
'elevenlabs' => $app->make(ElevenLabsDriver::class), 'elevenlabs' => $app->make(ElevenLabsDriver::class),
])); ]));
$this->app->singleton(StepHandlerManager::class, fn ($app) => new StepHandlerManager([
$app->make(ScriptGenerationHandler::class),
$app->make(TtsVoiceoverHandler::class),
]));
} }
/** /**
@@ -0,0 +1,87 @@
<?php
namespace App\Support\VideoWorkflow\StepHandlers;
use App\Models\AiProvider;
use App\Models\WorkflowStep;
use App\Support\AiProviders\AiGenerationException;
use App\Support\AiProviders\AiProviderManager;
use App\Support\AssetStorage\AssetStorage;
use App\Support\VideoWorkflow\WorkflowEngine;
/**
* Turns a project's title/description (or an explicit outline) into a full
* script via an OpenAI-backed AiProvider, with optional tone/SEO-keyword/
* length guidance from the step's input.
*/
class ScriptGenerationHandler implements StepHandler
{
public function __construct(
private readonly AiProviderManager $aiProviders,
private readonly AssetStorage $assets,
) {}
public function type(): string
{
return 'script_generation';
}
public function handle(WorkflowStep $step, WorkflowEngine $engine): void
{
$provider = AiProvider::query()->where('provider', 'openai')->where('is_active', true)->first();
if (! $provider) {
$engine->failStep($step, 'No active OpenAI provider configured.');
return;
}
try {
$result = $this->aiProviders->generate($provider, $this->buildPrompt($step));
} catch (AiGenerationException $e) {
$engine->failStep($step, $e->getMessage());
return;
}
$asset = $this->assets->store(
$step->videoProject,
'script',
$result->content,
'txt',
step: $step,
mimeType: 'text/plain',
);
$engine->completeStep($step, [
'asset_id' => $asset->id,
'word_count' => str_word_count($result->content),
]);
}
private function buildPrompt(WorkflowStep $step): string
{
$input = $step->input ?? [];
$project = $step->videoProject;
$outline = $input['outline'] ?? trim(($project->title ?? '')."\n\n".($project->description ?? ''));
$prompt = "Write a complete, engaging YouTube video script.\n\nTopic/Outline:\n{$outline}";
if (! empty($input['tone'])) {
$prompt .= "\n\nTone: {$input['tone']}";
}
if (! empty($input['seo_keywords'])) {
$prompt .= "\n\nNaturally include these SEO keywords where relevant: ".implode(', ', $input['seo_keywords']);
}
if (! empty($input['target_words'])) {
$prompt .= "\n\nTarget length: approximately {$input['target_words']} words.";
}
$prompt .= "\n\nWrite only the script content, no preamble or explanation.";
return $prompt;
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Support\VideoWorkflow\StepHandlers;
use App\Models\WorkflowStep;
use App\Support\VideoWorkflow\WorkflowEngine;
interface StepHandler
{
/**
* The WorkflowStep::TYPES value this handler executes.
*/
public function type(): string;
/**
* Do the actual work for this step (call an AI provider, render
* something, etc.) and report the result back through $engine —
* completeStep() on success, failStep() on failure. $step must be
* 'in_progress' when this is called.
*/
public function handle(WorkflowStep $step, WorkflowEngine $engine): void;
}
@@ -0,0 +1,22 @@
<?php
namespace App\Support\VideoWorkflow\StepHandlers;
class StepHandlerManager
{
/**
* @param array<StepHandler> $handlers
*/
public function __construct(private readonly array $handlers) {}
public function resolve(string $type): ?StepHandler
{
foreach ($this->handlers as $handler) {
if ($handler->type() === $type) {
return $handler;
}
}
return null;
}
}
@@ -0,0 +1,95 @@
<?php
namespace App\Support\VideoWorkflow\StepHandlers;
use App\Models\AiProvider;
use App\Models\WorkflowStep;
use App\Support\AiProviders\AiGenerationException;
use App\Support\AiProviders\AiProviderManager;
use App\Support\AssetStorage\AssetStorage;
use App\Support\VideoWorkflow\WorkflowEngine;
/**
* Synthesizes narration audio via an ElevenLabs-backed AiProvider. Text
* comes from $step->input['text'] if given, otherwise the project's latest
* 'script' asset. Voice selection (input.voice_id / input.model_id) is
* per-step, falling back to the AiProvider's own config.
*
* Note: ElevenLabs' base TTS endpoint doesn't expose a direct "speed"
* parameter — only voice_id/model_id are wired through here for now.
*/
class TtsVoiceoverHandler implements StepHandler
{
public function __construct(
private readonly AiProviderManager $aiProviders,
private readonly AssetStorage $assets,
) {}
public function type(): string
{
return 'tts_voiceover';
}
public function handle(WorkflowStep $step, WorkflowEngine $engine): void
{
$provider = AiProvider::query()->where('provider', 'elevenlabs')->where('is_active', true)->first();
if (! $provider) {
$engine->failStep($step, 'No active ElevenLabs provider configured.');
return;
}
$text = $this->resolveText($step);
if (! $text) {
$engine->failStep($step, 'No script text available to voice — set input.text or complete a script_generation step first.');
return;
}
$input = $step->input ?? [];
$options = array_filter([
'voice_id' => $input['voice_id'] ?? null,
'model_id' => $input['model_id'] ?? null,
]);
try {
$result = $this->aiProviders->generate($provider, $text, $options);
} catch (AiGenerationException $e) {
$engine->failStep($step, $e->getMessage());
return;
}
$asset = $this->assets->store(
$step->videoProject,
'audio',
$result->content,
'mp3',
step: $step,
mimeType: $result->contentType,
);
$engine->completeStep($step, [
'asset_id' => $asset->id,
'characters' => strlen($text),
]);
}
private function resolveText(WorkflowStep $step): ?string
{
$input = $step->input ?? [];
if (! empty($input['text'])) {
return $input['text'];
}
$scriptAsset = $step->videoProject->assets()
->where('type', 'script')
->orderByDesc('version')
->first();
return $scriptAsset ? $this->assets->contents($scriptAsset) : null;
}
}
@@ -16,6 +16,9 @@
<a href="{{ route('tasks.index') }}" class="font-medium hover:text-blue-600">Tasks</a> <a href="{{ route('tasks.index') }}" class="font-medium hover:text-blue-600">Tasks</a>
<a href="{{ route('ideas.index') }}" class="font-medium hover:text-blue-600">Ideas</a> <a href="{{ route('ideas.index') }}" class="font-medium hover:text-blue-600">Ideas</a>
<span class="border-l border-gray-200 h-5"></span>
<a href="{{ route('video-projects.index') }}" class="font-medium hover:text-blue-600">Video Projects</a>
@auth @auth
<form method="POST" action="{{ route('logout') }}" class="ml-auto"> <form method="POST" action="{{ route('logout') }}" class="ml-auto">
@csrf @csrf
@@ -0,0 +1,78 @@
<div>
<div class="flex justify-between items-center mb-4">
<h1 class="text-xl font-semibold">Video Projects</h1>
<button wire:click="create" class="bg-blue-600 text-white px-4 py-2 rounded">New Video Project</button>
</div>
<table class="w-full bg-white border border-gray-200 rounded">
<thead>
<tr class="text-left border-b border-gray-200">
<th class="p-3">Title</th>
<th class="p-3">Status</th>
<th class="p-3">Current Step</th>
<th class="p-3">Progress</th>
<th class="p-3">Created</th>
<th class="p-3"></th>
</tr>
</thead>
<tbody>
@forelse ($projects as $project)
<tr wire:key="video-project-{{ $project->id }}" class="border-b border-gray-100">
<td class="p-3">
<a href="{{ route('video-projects.show', $project) }}" wire:navigate class="text-blue-600 hover:underline">{{ $project->title }}</a>
</td>
<td class="p-3">{{ ucfirst($project->status) }}</td>
<td class="p-3">
@if ($project->steps->isNotEmpty())
{{ str($project->steps->first()->type)->headline() }}
<span class="text-xs text-gray-500">({{ str($project->steps->first()->status)->headline() }})</span>
@else
—
@endif
</td>
<td class="p-3">
@if ($project->steps_count > 0)
{{ $project->completed_steps_count }} / {{ $project->steps_count }}
@else
not started
@endif
</td>
<td class="p-3">{{ $project->created_at->format('Y-m-d') }}</td>
<td class="p-3 text-right space-x-2">
<a href="{{ route('video-projects.show', $project) }}" wire:navigate class="text-blue-600">Open</a>
<button wire:click="delete({{ $project->id }})" wire:confirm="Delete this video project?" class="text-red-600">Delete</button>
</td>
</tr>
@empty
<tr>
<td colspan="6" class="p-3 text-center text-gray-500">No video projects yet.</td>
</tr>
@endforelse
</tbody>
</table>
@if ($showForm)
<div class="fixed inset-0 bg-black/30 flex items-center justify-center">
<div class="bg-white p-6 rounded w-full max-w-md space-y-4">
<h2 class="text-lg font-semibold">New Video Project</h2>
<div>
<label class="block text-sm font-medium">Title</label>
<input type="text" wire:model="title" class="w-full border rounded p-2">
@error('title') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
</div>
<div>
<label class="block text-sm font-medium">Description (optional)</label>
<textarea wire:model="description" rows="3" class="w-full border rounded p-2"></textarea>
@error('description') <span class="text-red-600 text-sm">{{ $message }}</span> @enderror
</div>
<div class="flex justify-end gap-2">
<button wire:click="$set('showForm', false)" class="px-4 py-2">Cancel</button>
<button wire:click="save" class="bg-blue-600 text-white px-4 py-2 rounded">Create</button>
</div>
</div>
</div>
@endif
</div>
@@ -0,0 +1,123 @@
<div @if ($hasActiveStep) wire:poll.3s @endif>
<div class="mb-4">
<a href="{{ route('video-projects.index') }}" wire:navigate class="text-sm text-blue-600 hover:underline">&larr; Video Projects</a>
</div>
<div class="bg-white p-6 rounded border border-gray-200 mb-6">
<div class="flex justify-between items-start">
<div>
<h1 class="text-xl font-semibold">{{ $videoProject->title }}</h1>
@if ($videoProject->description)
<p class="text-gray-600 mt-1">{{ $videoProject->description }}</p>
@endif
</div>
<span class="text-sm font-medium px-2 py-1 rounded bg-gray-100">{{ ucfirst($videoProject->status) }}</span>
</div>
</div>
@if ($notice)
<div class="mb-4 p-3 bg-amber-50 border border-amber-200 text-amber-800 rounded text-sm">{{ $notice }}</div>
@endif
@if ($steps->isEmpty())
<div class="bg-white p-6 rounded border border-gray-200 mb-6 space-y-4">
<h2 class="text-lg font-semibold">Start Workflow</h2>
@if ($templates->isNotEmpty())
<div class="flex items-end gap-2">
<div class="flex-1">
<label class="block text-sm font-medium">From a template</label>
<select wire:model="workflowTemplateId" class="w-full border rounded p-2">
<option value="">Select template</option>
@foreach ($templates as $template)
<option value="{{ $template->id }}">{{ $template->name }}</option>
@endforeach
</select>
</div>
<button wire:click="startWithTemplate" class="bg-blue-600 text-white px-4 py-2 rounded">Start</button>
</div>
@endif
<div>
<button wire:click="startDefault" class="bg-gray-800 text-white px-4 py-2 rounded">
Start with default pipeline
</button>
<p class="text-xs text-gray-500 mt-1">Script &rarr; Voiceover &rarr; Storyboard &rarr; Video &rarr; Editing &rarr; Thumbnail &rarr; Metadata &rarr; Publish, each requiring approval.</p>
</div>
</div>
@else
<div class="bg-white rounded border border-gray-200 mb-6 divide-y divide-gray-100">
@foreach ($steps as $step)
<div wire:key="step-{{ $step->id }}" class="p-4">
<div class="flex justify-between items-center">
<div>
<span class="font-medium">{{ $loop->iteration }}. {{ str($step->type)->headline() }}</span>
<span @class([
'text-xs px-2 py-0.5 rounded ml-2',
'bg-gray-100 text-gray-700' => in_array($step->status, ['pending', 'skipped']),
'bg-blue-100 text-blue-700' => $step->status === 'in_progress',
'bg-amber-100 text-amber-700' => $step->status === 'awaiting_approval',
'bg-green-100 text-green-700' => $step->status === 'completed',
'bg-red-100 text-red-700' => in_array($step->status, ['failed', 'rejected']),
])>{{ str($step->status)->headline() }}</span>
</div>
<div class="space-x-2">
@if ($step->status === 'in_progress')
<button wire:click="runStep({{ $step->id }})" class="text-blue-600 text-sm">Run</button>
<button wire:click="skipStep({{ $step->id }})" wire:confirm="Skip this step?" class="text-gray-500 text-sm">Skip</button>
@elseif ($step->status === 'awaiting_approval')
<button wire:click="approveStep({{ $step->id }})" class="text-green-700 text-sm">Approve</button>
<button wire:click="rejectStep({{ $step->id }})" class="text-red-600 text-sm">Reject</button>
@elseif (in_array($step->status, ['failed', 'rejected']))
<button wire:click="retryStep({{ $step->id }})" class="text-blue-600 text-sm">Retry</button>
@elseif ($step->status === 'pending')
<button wire:click="skipStep({{ $step->id }})" wire:confirm="Skip this step?" class="text-gray-500 text-sm">Skip</button>
@endif
</div>
</div>
@if ($step->error)
<p class="text-sm text-red-600 mt-1">{{ $step->error }}</p>
@endif
@if ($step->output)
<p class="text-xs text-gray-500 mt-1">
@if (isset($step->output['word_count']))
{{ $step->output['word_count'] }} words generated
@elseif (isset($step->output['characters']))
{{ $step->output['characters'] }} characters synthesized
@endif
</p>
@endif
</div>
@endforeach
</div>
@endif
@if ($assets->isNotEmpty())
<div class="bg-white rounded border border-gray-200">
<h2 class="text-lg font-semibold p-4 border-b border-gray-100">Assets</h2>
<table class="w-full">
<thead>
<tr class="text-left border-b border-gray-100 text-sm text-gray-500">
<th class="p-3">Type</th>
<th class="p-3">Version</th>
<th class="p-3">Size</th>
<th class="p-3">Created</th>
</tr>
</thead>
<tbody>
@foreach ($assets as $asset)
<tr class="border-b border-gray-50">
<td class="p-3">{{ ucfirst($asset->type) }}</td>
<td class="p-3">v{{ $asset->version }}</td>
<td class="p-3">{{ $asset->size_bytes ? number_format($asset->size_bytes / 1024, 1).' KB' : '—' }}</td>
<td class="p-3">{{ $asset->created_at->format('Y-m-d H:i') }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</div>
+5
View File
@@ -31,4 +31,9 @@ Route::middleware('auth')->group(function () {
Route::get('/tasks', \App\Livewire\Tasks\Index::class)->name('tasks.index'); Route::get('/tasks', \App\Livewire\Tasks\Index::class)->name('tasks.index');
Route::get('/task-comments', \App\Livewire\TaskComments\Index::class)->name('task-comments.index'); Route::get('/task-comments', \App\Livewire\TaskComments\Index::class)->name('task-comments.index');
Route::get('/ideas', \App\Livewire\Ideas\Index::class)->name('ideas.index'); Route::get('/ideas', \App\Livewire\Ideas\Index::class)->name('ideas.index');
// Video Projects — a separate domain from Projects/Tasks/Ideas above,
// see task #47 on the "YouTube Content Creation System" project.
Route::get('/video-projects', \App\Livewire\VideoProjects\Index::class)->name('video-projects.index');
Route::get('/video-projects/{videoProject}', \App\Livewire\VideoProjects\Show::class)->name('video-projects.show');
}); });
@@ -0,0 +1,77 @@
<?php
use App\Jobs\RunWorkflowStepJob;
use App\Models\AiProvider;
use App\Models\VideoProject;
use App\Support\AiProviders\AiProviderManager;
use App\Support\VideoWorkflow\StepHandlers\StepHandlerManager;
use App\Support\VideoWorkflow\WorkflowEngine;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
Storage::fake();
$this->engine = new WorkflowEngine;
});
test('it runs the matching handler and completes the step', function () {
Http::fake(['api.openai.com/*' => Http::response(['choices' => [['message' => ['content' => 'a script']]]])]);
AiProvider::factory()->create(['provider' => 'openai']);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
(new RunWorkflowStepJob($step->id))->handle(app(StepHandlerManager::class), $this->engine);
expect($step->fresh()->status)->toBe('completed');
});
test('it fails the step when no handler is registered for its type', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'video_generation']]);
(new RunWorkflowStepJob($step->id))->handle(app(StepHandlerManager::class), $this->engine);
expect($step->fresh())
->status->toBe('failed')
->error->toContain('No handler registered');
});
test('it does nothing for a step that is no longer in_progress', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->skipStep($step);
(new RunWorkflowStepJob($step->id))->handle(app(StepHandlerManager::class), $this->engine);
expect($step->fresh()->status)->toBe('skipped');
});
test('it does nothing for a missing step', function () {
(new RunWorkflowStepJob(999999))->handle(app(StepHandlerManager::class), $this->engine);
})->throwsNoExceptions();
test('it fails the step when the handler throws unexpectedly', function () {
$badHandler = new class implements \App\Support\VideoWorkflow\StepHandlers\StepHandler
{
public function type(): string
{
return 'script_generation';
}
public function handle(\App\Models\WorkflowStep $step, WorkflowEngine $engine): void
{
throw new \RuntimeException('boom');
}
};
$manager = new StepHandlerManager([$badHandler]);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
(new RunWorkflowStepJob($step->id))->handle($manager, $this->engine);
expect($step->fresh())
->status->toBe('failed')
->error->toBe('boom');
});
@@ -0,0 +1,54 @@
<?php
use App\Livewire\VideoProjects\Index;
use App\Models\User;
use App\Models\VideoProject;
use App\Support\VideoWorkflow\WorkflowEngine;
use Livewire\Livewire;
test('video projects index page lists existing projects', function () {
VideoProject::factory()->create(['title' => 'My Awesome Video']);
$this->actingAs(User::factory()->create())
->get(route('video-projects.index'))
->assertOk()
->assertSee('My Awesome Video');
});
test('a new video project can be created', function () {
Livewire::test(Index::class)
->set('title', 'New Video')
->set('description', 'A description')
->call('save');
expect(VideoProject::where('title', 'New Video')->exists())->toBeTrue();
});
test('title is required to create a video project', function () {
Livewire::test(Index::class)
->set('title', '')
->call('save')
->assertHasErrors(['title']);
});
test('a video project can be deleted', function () {
$project = VideoProject::factory()->create();
Livewire::test(Index::class)->call('delete', $project->id);
expect(VideoProject::find($project->id))->toBeNull();
});
test('it shows step progress counts for a started project', function () {
$project = VideoProject::factory()->create(['title' => 'Progress Test']);
$engine = new WorkflowEngine;
$step = $engine->start($project, [
['type' => 'script_generation'],
['type' => 'tts_voiceover'],
]);
$engine->completeStep($step);
$this->actingAs(User::factory()->create())
->get(route('video-projects.index'))
->assertSee('1 / 2');
});
@@ -0,0 +1,129 @@
<?php
use App\Jobs\RunWorkflowStepJob;
use App\Livewire\VideoProjects\Show;
use App\Models\VideoProject;
use App\Models\WorkflowTemplate;
use App\Support\VideoWorkflow\WorkflowEngine;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;
test('starting the default pipeline creates steps and queues the first handled one', function () {
Queue::fake();
$project = VideoProject::factory()->create();
Livewire::test(Show::class, ['videoProject' => $project])
->call('startDefault');
expect($project->fresh()->status)->toBe('in_progress');
expect($project->steps()->count())->toBe(8);
expect($project->steps()->orderBy('order')->first()->type)->toBe('script_generation');
Queue::assertPushed(RunWorkflowStepJob::class, function ($job) use ($project) {
$step = $project->steps()->orderBy('order')->first();
return $job->stepId === $step->id;
});
});
test('starting from a template uses its steps and does not queue unhandled types', function () {
Queue::fake();
$template = WorkflowTemplate::factory()->create(['steps' => [
['type' => 'video_generation'],
['type' => 'youtube_publish'],
]]);
$project = VideoProject::factory()->create();
Livewire::test(Show::class, ['videoProject' => $project])
->set('workflowTemplateId', $template->id)
->call('startWithTemplate');
expect($project->fresh()->workflow_template_id)->toBe($template->id);
expect($project->steps()->count())->toBe(2);
// video_generation has no handler yet, so nothing should be queued
Queue::assertNotPushed(RunWorkflowStepJob::class);
});
test('startWithTemplate shows a notice when no template is selected', function () {
$project = VideoProject::factory()->create();
Livewire::test(Show::class, ['videoProject' => $project])
->call('startWithTemplate')
->assertSee('Pick a template first.');
expect($project->fresh()->status)->toBe('draft');
});
test('runStep dispatches the job for the given step', function () {
Queue::fake();
$project = VideoProject::factory()->create();
$step = (new WorkflowEngine)->start($project, [['type' => 'script_generation']]);
Livewire::test(Show::class, ['videoProject' => $project])
->call('runStep', $step->id);
Queue::assertPushed(RunWorkflowStepJob::class, fn ($job) => $job->stepId === $step->id);
});
test('approving a step advances and queues the next handled step', function () {
Queue::fake();
$project = VideoProject::factory()->create();
$engine = new WorkflowEngine;
$step = $engine->start($project, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover'],
]);
$engine->completeStep($step, ['script' => 'draft']);
Livewire::test(Show::class, ['videoProject' => $project])
->call('approveStep', $step->id);
$next = $project->steps()->where('order', 1)->first();
expect($next->status)->toBe('in_progress');
Queue::assertPushed(RunWorkflowStepJob::class, fn ($job) => $job->stepId === $next->id);
});
test('rejecting a step blocks the pipeline', function () {
$project = VideoProject::factory()->create();
$engine = new WorkflowEngine;
$step = $engine->start($project, [['type' => 'script_generation', 'requires_approval' => true]]);
$engine->completeStep($step, ['script' => 'bad']);
Livewire::test(Show::class, ['videoProject' => $project])
->call('rejectStep', $step->id);
expect($step->fresh()->status)->toBe('rejected');
});
test('retrying a failed step re-queues it', function () {
Queue::fake();
$project = VideoProject::factory()->create();
$engine = new WorkflowEngine;
$step = $engine->start($project, [['type' => 'script_generation']]);
$engine->failStep($step, 'boom');
Livewire::test(Show::class, ['videoProject' => $project])
->call('retryStep', $step->id);
expect($step->fresh()->status)->toBe('in_progress');
Queue::assertPushed(RunWorkflowStepJob::class, fn ($job) => $job->stepId === $step->id);
});
test('skipping a step advances and queues the next handled step', function () {
Queue::fake();
$project = VideoProject::factory()->create();
$engine = new WorkflowEngine;
$step = $engine->start($project, [
['type' => 'video_generation'],
['type' => 'script_generation'],
]);
Livewire::test(Show::class, ['videoProject' => $project])
->call('skipStep', $step->id);
$next = $project->steps()->where('order', 1)->first();
expect($step->fresh()->status)->toBe('skipped');
expect($next->status)->toBe('in_progress');
Queue::assertPushed(RunWorkflowStepJob::class, fn ($job) => $job->stepId === $next->id);
});
@@ -0,0 +1,91 @@
<?php
use App\Models\AiProvider;
use App\Models\VideoProject;
use App\Support\AiProviders\AiProviderManager;
use App\Support\AssetStorage\AssetStorage;
use App\Support\VideoWorkflow\StepHandlers\ScriptGenerationHandler;
use App\Support\VideoWorkflow\WorkflowEngine;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
Storage::fake();
$this->engine = new WorkflowEngine;
$this->handler = new ScriptGenerationHandler(app(AiProviderManager::class), new AssetStorage);
});
test('it generates a script, stores it as an asset, and completes the step', function () {
Http::fake([
'api.openai.com/*' => Http::response([
'choices' => [['message' => ['content' => 'Welcome back to the channel today']]],
]),
]);
AiProvider::factory()->create(['provider' => 'openai', 'is_active' => true]);
$project = VideoProject::factory()->create(['title' => 'Best Coffee Gadgets 2026']);
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->handler->handle($step, $this->engine);
$fresh = $step->fresh();
expect($fresh->status)->toBe('completed');
expect($fresh->output['word_count'])->toBe(6);
$asset = \App\Models\Asset::find($fresh->output['asset_id']);
expect($asset->type)->toBe('script');
expect($asset->video_project_id)->toBe($project->id);
expect(Storage::get($asset->disk_path))->toBe('Welcome back to the channel today');
Http::assertSent(fn ($request) => str_contains($request['messages'][0]['content'], 'Best Coffee Gadgets 2026'));
});
test('it uses an explicit outline, tone, keywords, and target length when given', function () {
Http::fake(['api.openai.com/*' => Http::response(['choices' => [['message' => ['content' => 'script']]]])]);
AiProvider::factory()->create(['provider' => 'openai']);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$step->update(['input' => [
'outline' => 'A history of espresso machines',
'tone' => 'casual and funny',
'seo_keywords' => ['espresso', 'coffee history'],
'target_words' => 800,
]]);
$this->handler->handle($step->fresh(), $this->engine);
Http::assertSent(function ($request) {
$prompt = $request['messages'][0]['content'];
return str_contains($prompt, 'A history of espresso machines')
&& str_contains($prompt, 'casual and funny')
&& str_contains($prompt, 'espresso, coffee history')
&& str_contains($prompt, 'approximately 800 words');
});
});
test('it fails the step when no active OpenAI provider is configured', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->handler->handle($step, $this->engine);
expect($step->fresh())
->status->toBe('failed')
->error->toContain('No active OpenAI provider');
});
test('it fails the step when the AI provider call fails', function () {
Http::fake(['api.openai.com/*' => Http::response(['error' => ['message' => 'rate limited']], 429)]);
AiProvider::factory()->create(['provider' => 'openai']);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->handler->handle($step, $this->engine);
expect($step->fresh())
->status->toBe('failed')
->error->toBe('rate limited');
});
@@ -0,0 +1,92 @@
<?php
use App\Models\AiProvider;
use App\Models\VideoProject;
use App\Support\AiProviders\AiProviderManager;
use App\Support\AssetStorage\AssetStorage;
use App\Support\VideoWorkflow\StepHandlers\TtsVoiceoverHandler;
use App\Support\VideoWorkflow\WorkflowEngine;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
Storage::fake();
$this->engine = new WorkflowEngine;
$this->assets = new AssetStorage;
$this->handler = new TtsVoiceoverHandler(app(AiProviderManager::class), $this->assets);
});
test('it voices explicit input text and completes the step', function () {
Http::fake(['api.elevenlabs.io/*' => Http::response('fake-mp3-bytes', 200, ['Content-Type' => 'audio/mpeg'])]);
AiProvider::factory()->create(['provider' => 'elevenlabs', 'config' => ['voice_id' => 'v1']]);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'tts_voiceover']]);
$step->update(['input' => ['text' => 'Hello and welcome']]);
$this->handler->handle($step->fresh(), $this->engine);
$fresh = $step->fresh();
expect($fresh->status)->toBe('completed');
expect($fresh->output['characters'])->toBe(strlen('Hello and welcome'));
$asset = \App\Models\Asset::find($fresh->output['asset_id']);
expect($asset->type)->toBe('audio');
expect($asset->mime_type)->toBe('audio/mpeg');
expect(Storage::get($asset->disk_path))->toBe('fake-mp3-bytes');
Http::assertSent(fn ($request) => $request['text'] === 'Hello and welcome');
});
test('it falls back to the latest script asset when no input text is given', function () {
Http::fake(['api.elevenlabs.io/*' => Http::response('bytes')]);
AiProvider::factory()->create(['provider' => 'elevenlabs', 'config' => ['voice_id' => 'v1']]);
$project = VideoProject::factory()->create();
$this->assets->store($project, 'script', 'Old draft', 'txt');
$this->assets->store($project, 'script', 'Latest draft', 'txt');
$step = $this->engine->start($project, [['type' => 'tts_voiceover']]);
$this->handler->handle($step, $this->engine);
Http::assertSent(fn ($request) => $request['text'] === 'Latest draft');
});
test('a voice_id in step input overrides the provider default', function () {
Http::fake(['api.elevenlabs.io/*' => Http::response('bytes')]);
AiProvider::factory()->create(['provider' => 'elevenlabs', 'config' => ['voice_id' => 'default-voice']]);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'tts_voiceover']]);
$step->update(['input' => ['text' => 'hi', 'voice_id' => 'custom-voice']]);
$this->handler->handle($step->fresh(), $this->engine);
Http::assertSent(fn ($request) => str_contains($request->url(), '/text-to-speech/custom-voice'));
});
test('it fails the step when there is no text to voice', function () {
AiProvider::factory()->create(['provider' => 'elevenlabs', 'config' => ['voice_id' => 'v1']]);
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'tts_voiceover']]);
$this->handler->handle($step, $this->engine);
expect($step->fresh())
->status->toBe('failed')
->error->toContain('No script text available');
});
test('it fails the step when no active ElevenLabs provider is configured', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'tts_voiceover']]);
$step->update(['input' => ['text' => 'hi']]);
$this->handler->handle($step->fresh(), $this->engine);
expect($step->fresh())
->status->toBe('failed')
->error->toContain('No active ElevenLabs provider');
});