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\TwitterPublisher;
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;
class AppServiceProvider extends ServiceProvider
@@ -32,6 +35,11 @@ class AppServiceProvider extends ServiceProvider
'stability_ai' => $app->make(StabilityAiDriver::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;
}
}