Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

fix: subscribe to AI generation channel before dispatching the job (#269)

Paulo Castellanoa1a91724488a
diff --git a/app/Http/Controllers/App/PostAiCreateController.php b/app/Http/Controllers/App/PostAiCreateController.php
index d9410758f..54d5917b1 100644
--- a/app/Http/Controllers/App/PostAiCreateController.php
+++ b/app/Http/Controllers/App/PostAiCreateController.php
@@ -10,7 +10,6 @@ use App\Models\SocialAccount;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response as InertiaResponse;
use Symfony\Component\HttpFoundation\Response;
@@ -40,7 +39,7 @@ class PostAiCreateController extends Controller
}
}
- $creationId = (string) Str::uuid();
+ $creationId = $request->string('creation_id')->toString();
StreamPostCreation::dispatch(
userId: $request->user()->id,
@@ -69,6 +68,10 @@ class PostAiCreateController extends Controller
'imageCount' => (int) $request->query('images', '0'),
'format' => (string) $request->query('format', ''),
'prompt' => (string) $request->query('prompt', ''),
+ 'socialAccountId' => $request->query('social_account_id') ?: null,
+ 'date' => $request->query('date') ?: null,
+ 'template' => (string) $request->query('template', 'image_card'),
+ 'applyBrandVisuals' => $request->boolean('apply_brand_visuals', true),
]);
}
}
diff --git a/app/Http/Controllers/App/PostAiGenerateController.php b/app/Http/Controllers/App/PostAiGenerateController.php
index 58b7d6421..5581db03d 100644
--- a/app/Http/Controllers/App/PostAiGenerateController.php
+++ b/app/Http/Controllers/App/PostAiGenerateController.php
@@ -9,7 +9,6 @@ use App\Jobs\Ai\StreamPostContent;
use App\Models\Post;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
class PostAiGenerateController extends Controller
@@ -25,7 +24,7 @@ class PostAiGenerateController extends Controller
return response()->json(['message' => $gate->message()], Response::HTTP_PAYMENT_REQUIRED);
}
- $generationId = (string) Str::uuid();
+ $generationId = $request->string('generation_id')->toString();
StreamPostContent::dispatch(
workspaceId: $workspace->id,
diff --git a/app/Http/Controllers/App/PostAiRegenerateMediaController.php b/app/Http/Controllers/App/PostAiRegenerateMediaController.php
index e0142aa06..9693f6b25 100644
--- a/app/Http/Controllers/App/PostAiRegenerateMediaController.php
+++ b/app/Http/Controllers/App/PostAiRegenerateMediaController.php
@@ -11,7 +11,6 @@ use App\Models\Post;
use App\Support\PostStatusRules;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
class PostAiRegenerateMediaController extends Controller
@@ -25,6 +24,7 @@ class PostAiRegenerateMediaController extends Controller
if (PostStatusRules::blocksEditing($post)) {
return response()->json([
'message' => PostStatusRules::editBlockedMessage(),
+ 'errors' => ['instruction' => [PostStatusRules::editBlockedMessage()]],
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
@@ -45,10 +45,11 @@ class PostAiRegenerateMediaController extends Controller
if (data_get($mediaItem, 'source') !== Source::Ai->value) {
return response()->json([
'message' => __('posts.ai.image_regenerate.errors.not_ai_media'),
+ 'errors' => ['instruction' => [__('posts.ai.image_regenerate.errors.not_ai_media')]],
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
- $regenerationId = (string) Str::uuid();
+ $regenerationId = $request->string('regeneration_id')->toString();
RegeneratePostMediaImage::dispatch(
workspaceId: $workspace->id,
diff --git a/app/Http/Requests/App/Ai/GeneratePostContentRequest.php b/app/Http/Requests/App/Ai/GeneratePostContentRequest.php
index a94dc5341..759a35e75 100644
--- a/app/Http/Requests/App/Ai/GeneratePostContentRequest.php
+++ b/app/Http/Requests/App/Ai/GeneratePostContentRequest.php
@@ -22,6 +22,7 @@ class GeneratePostContentRequest extends FormRequest
return [
'prompt' => ['required', 'string', 'max:'.AiPromptRules::PROMPT_MAX_LENGTH],
'current_content' => ['nullable', 'string', 'max:10000'],
+ 'generation_id' => ['required', 'string', 'uuid'],
];
}
}
diff --git a/app/Http/Requests/App/Ai/RegeneratePostMediaImageRequest.php b/app/Http/Requests/App/Ai/RegeneratePostMediaImageRequest.php
index 78f25659c..86f32cd3c 100644
--- a/app/Http/Requests/App/Ai/RegeneratePostMediaImageRequest.php
+++ b/app/Http/Requests/App/Ai/RegeneratePostMediaImageRequest.php
@@ -20,6 +20,7 @@ class RegeneratePostMediaImageRequest extends FormRequest
{
return [
'instruction' => ['required', 'string', 'max:1000'],
+ 'regeneration_id' => ['required', 'string', 'uuid'],
];
}
diff --git a/app/Http/Requests/App/Ai/StartPostCreationRequest.php b/app/Http/Requests/App/Ai/StartPostCreationRequest.php
index dcbe13337..10b33527c 100644
--- a/app/Http/Requests/App/Ai/StartPostCreationRequest.php
+++ b/app/Http/Requests/App/Ai/StartPostCreationRequest.php
@@ -27,6 +27,7 @@ class StartPostCreationRequest extends FormRequest
$allowedFormats[] = ContentType::CAROUSEL_FORMAT;
return [
+ 'creation_id' => ['required', 'string', 'uuid'],
'format' => [
'required',
'string',
diff --git a/app/Jobs/Ai/StreamPostCreation.php b/app/Jobs/Ai/StreamPostCreation.php
index ad8b8f264..00fcbc365 100644
--- a/app/Jobs/Ai/StreamPostCreation.php
+++ b/app/Jobs/Ai/StreamPostCreation.php
@@ -24,16 +24,19 @@ use App\Models\User;
use App\Models\Workspace;
use App\Services\Ai\RecordAiUsage;
use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
-class StreamPostCreation implements ShouldQueue
+class StreamPostCreation implements ShouldBeUnique, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+ public int $uniqueFor = 990;
+
public function __construct(
public string $userId,
public string $creationId,
@@ -49,6 +52,11 @@ class StreamPostCreation implements ShouldQueue
$this->onQueue('ai');
}
+ public function uniqueId(): string
+ {
+ return "{$this->userId}:{$this->creationId}";
+ }
+
public function handle(): void
{
$workspace = Workspace::findOrFail($this->workspaceId);
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index d9ff67233..c61611e59 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'استخدام هذا المحتوى',
'retry' => 'إعادة المحاولة',
'cancel' => 'إلغاء',
+ 'errors' => [
+ 'start_failed' => 'تعذّر بدء الإنشاء.',
+ 'generation_failed' => 'فشل الإنشاء بالذكاء الاصطناعي.',
+ ],
],
'review' => [
'button_tooltip' => 'المراجعة بالذكاء الاصطناعي',
diff --git a/lang/de/posts.php b/lang/de/posts.php
index ce4999ee5..bd79bfa3e 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -237,6 +237,10 @@ return [
'apply' => 'Diesen Inhalt verwenden',
'retry' => 'Erneut versuchen',
'cancel' => 'Abbrechen',
+ 'errors' => [
+ 'start_failed' => 'Generierung konnte nicht gestartet werden.',
+ 'generation_failed' => 'KI-Generierung fehlgeschlagen.',
+ ],
],
'review' => [
'button_tooltip' => 'Mit KI prüfen',
diff --git a/lang/el/posts.php b/lang/el/posts.php
index 625687e93..04d8992e1 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Χρήση αυτού του περιεχομένου',
'retry' => 'Δοκιμάστε ξανά',
'cancel' => 'Ακύρωση',
+ 'errors' => [
+ 'start_failed' => 'Δεν ήταν δυνατή η έναρξη της δημιουργίας.',
+ 'generation_failed' => 'Η δημιουργία με AI απέτυχε.',
+ ],
],
'review' => [
'button_tooltip' => 'Έλεγχος με AI',
diff --git a/lang/en/posts.php b/lang/en/posts.php
index 35864b4af..4ce09e420 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Use this content',
'retry' => 'Try again',
'cancel' => 'Cancel',
+ 'errors' => [
+ 'start_failed' => 'Could not start generation.',
+ 'generation_failed' => 'AI generation failed.',
+ ],
],
'review' => [
'button_tooltip' => 'Review with AI',
diff --git a/lang/es/posts.php b/lang/es/posts.php
index 7353c8df5..957d4d1a3 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Usar este contenido',
'retry' => 'Intentar de nuevo',
'cancel' => 'Cancelar',
+ 'errors' => [
+ 'start_failed' => 'No se pudo iniciar la generación.',
+ 'generation_failed' => 'Falló la generación con IA.',
+ ],
],
'review' => [
'button_tooltip' => 'Revisar con IA',
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index 4b6162c40..1983643a7 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Utiliser ce contenu',
'retry' => 'Réessayer',
'cancel' => 'Annuler',
+ 'errors' => [
+ 'start_failed' => 'Impossible de démarrer la génération.',
+ 'generation_failed' => 'Échec de la génération par l\'IA.',
+ ],
],
'review' => [
'button_tooltip' => 'Relire avec l\'IA',
diff --git a/lang/it/posts.php b/lang/it/posts.php
index 3a1e355d5..6460e6cb2 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Usa questo contenuto',
'retry' => 'Riprova',
'cancel' => 'Annulla',
+ 'errors' => [
+ 'start_failed' => 'Impossibile avviare la generazione.',
+ 'generation_failed' => 'Generazione IA non riuscita.',
+ ],
],
'review' => [
'button_tooltip' => 'Rivedi con l\'IA',
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index ffdd60ce0..cdae132c2 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'この内容を使用',
'retry' => 'もう一度試す',
'cancel' => 'キャンセル',
+ 'errors' => [
+ 'start_failed' => '生成を開始できませんでした。',
+ 'generation_failed' => 'AI生成に失敗しました。',
+ ],
],
'review' => [
'button_tooltip' => 'AI でレビュー',
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index 77f5c4437..ee4a20fa7 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => '이 콘텐츠 사용',
'retry' => '다시 시도',
'cancel' => '취소',
+ 'errors' => [
+ 'start_failed' => '생성을 시작할 수 없습니다.',
+ 'generation_failed' => 'AI 생성에 실패했습니다.',
+ ],
],
'review' => [
'button_tooltip' => 'AI로 검토',
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index ff94a555d..d9ef79626 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Gebruik deze inhoud',
'retry' => 'Opnieuw proberen',
'cancel' => 'Annuleren',
+ 'errors' => [
+ 'start_failed' => 'Kan generatie niet starten.',
+ 'generation_failed' => 'AI-generatie mislukt.',
+ ],
],
'review' => [
'button_tooltip' => 'Controleren met AI',
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index b8bde35a0..3f9732a8e 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Użyj tej treści',
'retry' => 'Spróbuj ponownie',
'cancel' => 'Anuluj',
+ 'errors' => [
+ 'start_failed' => 'Nie udało się rozpocząć generowania.',
+ 'generation_failed' => 'Generowanie przez AI nie powiodło się.',
+ ],
],
'review' => [
'button_tooltip' => 'Sprawdź z AI',
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index 37b20993f..a13828d37 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Usar este conteúdo',
'retry' => 'Tentar de novo',
'cancel' => 'Cancelar',
+ 'errors' => [
+ 'start_failed' => 'Não foi possível iniciar a geração.',
+ 'generation_failed' => 'A geração por IA falhou.',
+ ],
],
'review' => [
'button_tooltip' => 'Revisar com IA',
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index e1bc618ed..9787313b2 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Использовать этот контент',
'retry' => 'Попробовать снова',
'cancel' => 'Отмена',
+ 'errors' => [
+ 'start_failed' => 'Не удалось начать генерацию.',
+ 'generation_failed' => 'Не удалось сгенерировать с помощью ИИ.',
+ ],
],
'review' => [
'button_tooltip' => 'Проверить с помощью ИИ',
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index d3074fc5a..5cb220c56 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -237,6 +237,10 @@ return [
'apply' => 'Bu içeriği kullan',
'retry' => 'Tekrar dene',
'cancel' => 'İptal',
+ 'errors' => [
+ 'start_failed' => 'Oluşturma başlatılamadı.',
+ 'generation_failed' => 'AI oluşturma başarısız oldu.',
+ ],
],
'review' => [
'button_tooltip' => 'AI ile incele',
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index 37beb05c8..8dc88b8c1 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => 'Використати цей вміст',
'retry' => 'Спробувати знову',
'cancel' => 'Скасувати',
+ 'errors' => [
+ 'start_failed' => 'Не вдалося розпочати генерацію.',
+ 'generation_failed' => 'Не вдалося згенерувати за допомогою AI.',
+ ],
],
'review' => [
'button_tooltip' => 'Перевірити за допомогою AI',
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index 27cde3989..449ed49e7 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -235,6 +235,10 @@ return [
'apply' => '使用此内容',
'retry' => '重试',
'cancel' => '取消',
+ 'errors' => [
+ 'start_failed' => '无法开始生成。',
+ 'generation_failed' => 'AI 生成失败。',
+ ],
],
'review' => [
'button_tooltip' => '用 AI 校对',
diff --git a/resources/js/components/posts/ai/AiGenerateDialog.vue b/resources/js/components/posts/ai/AiGenerateDialog.vue
index 941fb7f8e..c834575a0 100644
--- a/resources/js/components/posts/ai/AiGenerateDialog.vue
+++ b/resources/js/components/posts/ai/AiGenerateDialog.vue
@@ -1,12 +1,14 @@
<script setup lang="ts">
-import { useHttp } from '@inertiajs/vue3';
-import { computed, ref, watch } from 'vue';
+import { useHttp, usePage } from '@inertiajs/vue3';
+import { trans } from 'laravel-vue-i18n';
+import { computed, onUnmounted, ref, watch } from 'vue';
+import InputError from '@/components/InputError.vue';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
-import { useAiStream } from '@/composables/echo/useAiStream';
+import { aiGenerationChannel, useAiStream } from '@/composables/echo/useAiStream';
import { generate as generatePostAi } from '@/routes/app/posts/ai';
const props = defineProps<{
@@ -20,26 +22,58 @@ const emit = defineEmits<{
(e: 'apply', content: string): void;
}>();
+const page = usePage();
+
const prompt = ref('');
const dispatching = ref(false);
+const promptError = ref<string | undefined>(undefined);
const { text, status, errorMessage, subscribe, unsubscribe, reset } = useAiStream();
-const httpGenerate = useHttp<{ prompt: string; current_content: string | null }>({
+const httpGenerate = useHttp<{ prompt: string; current_content: string | null; generation_id: string }>({
prompt: '',
current_content: null,
+ generation_id: '',
+});
+
+let unmounted = false;
+onUnmounted(() => {
+ unmounted = true;
});
const startGeneration = async () => {
if (! prompt.value.trim()) return;
dispatching.value = true;
- httpGenerate.prompt = prompt.value;
- httpGenerate.current_content = props.currentContent || null;
+ promptError.value = undefined;
+ const generationId = crypto.randomUUID();
+ const channel = aiGenerationChannel(String(page.props.auth.user.id), generationId);
+
try {
- const data = (await httpGenerate.post(generatePostAi.url(props.postId))) as { channel: string };
- subscribe(data.channel);
+ const subscribed = await subscribe(channel);
+
+ if (unmounted || ! open.value) {
+ unsubscribe();
+ return;
+ }
+
+ if (! subscribed) {
+ throw new Error('Channel subscription failed');
+ }
+
+ httpGenerate.prompt = prompt.value;
+ httpGenerate.current_content = props.currentContent || null;
+ httpGenerate.generation_id = generationId;
+ await httpGenerate.post(generatePostAi.url(props.postId));
+
+ if (httpGenerate.hasErrors) {
+ unsubscribe();
+ reset();
+ promptError.value = httpGenerate.errors.prompt ?? trans('posts.ai.generate.errors.start_failed');
+ return;
+ }
} catch {
+ unsubscribe();
status.value = 'failed';
- errorMessage.value = 'Could not start generation';
+ errorMessage.value = trans('posts.ai.generate.errors.start_failed');
} finally {
dispatching.value = false;
}
@@ -79,6 +113,7 @@ watch(open, () => {
unsubscribe();
reset();
prompt.value = '';
+ promptError.value = undefined;
});
</script>
@@ -100,6 +135,7 @@ watch(open, () => {
:disabled="status === 'streaming'"
rows="3"
/>
+ <InputError :message="promptError" />
</div>
<div v-if="status !== 'idle'" class="grid gap-2">
diff --git a/resources/js/components/posts/ai/AiRegenerateImageDialog.vue b/resources/js/components/posts/ai/AiRegenerateImageDialog.vue
index bec729caf..d46c8e664 100644
--- a/resources/js/components/posts/ai/AiRegenerateImageDialog.vue
+++ b/resources/js/components/posts/ai/AiRegenerateImageDialog.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { watch } from 'vue';
+import InputError from '@/components/InputError.vue';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
@@ -19,7 +20,7 @@ const emit = defineEmits<{
(e: 'regenerated', payload: RegenerationPayload): void;
}>();
-const { instruction, errorMessage, status, isBusy, isProcessing, canSubmit, submit, resetState, blockDismissWhileBusy } = useAiMediaRegeneration({
+const { instruction, errorMessage, instructionError, status, isBusy, isProcessing, canSubmit, submit, resetState, blockDismissWhileBusy } = useAiMediaRegeneration({
postId: props.postId,
getMediaItem: () => props.mediaItem,
onRegenerated: (payload) => emit('regenerated', payload),
@@ -62,6 +63,7 @@ watch(open, (isOpen) => {
:placeholder="$t('posts.ai.image_regenerate.instruction_placeholder')"
rows="4"
/>
+ <InputError :message="instructionError" />
</div>
<p v-if="status === 'processing'" class="text-sm text-foreground/70">
diff --git a/resources/js/components/posts/create/AiPostWizard.vue b/resources/js/components/posts/create/AiPostWizard.vue
index 42e0209d9..1bad3f04d 100644
--- a/resources/js/components/posts/create/AiPostWizard.vue
+++ b/resources/js/components/posts/create/AiPostWizard.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { router, useHttp } from '@inertiajs/vue3';
+import { router } from '@inertiajs/vue3';
import {
IconArrowLeft,
IconCheck,
@@ -8,8 +8,6 @@ import { trans } from 'laravel-vue-i18n';
import { computed, ref, watch } from 'vue';
import { toast } from 'vue-sonner';
-
-import { start as startRoute } from '@/actions/App/Http/Controllers/App/PostAiCreateController';
import ContentStylePicker from '@/components/ai/ContentStylePicker.vue';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
@@ -73,16 +71,6 @@ const PROMPT_MAX = 2000;
const submitting = ref(false);
-const httpStart = useHttp<{
- format: string | null;
- social_account_id: string | null;
- image_count: number;
- prompt: string;
- date: string | null;
- template: string;
- apply_brand_visuals: boolean;
-}>({ format: null, social_account_id: null, image_count: 0, prompt: '', date: null, template: 'image_card', apply_brand_visuals: true });
-
const AI_FORMATS: Array<{ value: AiFormat; platforms: string[] }> = [
{ value: ContentType.InstagramFeed, platforms: ['instagram', 'instagram-facebook'] },
{ value: CAROUSEL_FORMAT, platforms: ['instagram', 'instagram-facebook'] },
@@ -207,36 +195,31 @@ const goBack = () => {
emit('cancel');
};
-const startGeneration = async () => {
+const startGeneration = () => {
if (!canSubmit.value || submitting.value) return;
submitting.value = true;
- httpStart.format = selectedFormat.value;
- httpStart.social_account_id = selectedAccountId.value;
- httpStart.image_count = submittedImageCount.value;
- httpStart.prompt = promptText.value.trim();
- httpStart.date = props.date;
- httpStart.template = resolvedTemplate.value;
- httpStart.apply_brand_visuals = useBrandColors.value;
-
- try {
- const data = await httpStart.post(startRoute.url()) as { creation_id: string; channel: string };
-
- router.visit(loadingRoute(
- { creationId: data.creation_id },
+ router.visit(
+ loadingRoute(
+ { creationId: crypto.randomUUID() },
{
query: {
images: String(submittedImageCount.value),
format: selectedFormat.value ?? '',
prompt: promptText.value.trim(),
+ social_account_id: selectedAccountId.value ?? '',
+ date: props.date ?? '',
+ template: resolvedTemplate.value,
+ apply_brand_visuals: useBrandColors.value ? '1' : '0',
},
},
- ).url);
- } catch (err: any) {
- toast.error(err?.response?.data?.message ?? trans('posts.create.steps.preview_error'));
- submitting.value = false;
- }
+ ).url,
+ {
+ onError: () => toast.error(trans('posts.create.steps.preview_error')),
+ onFinish: () => { submitting.value = false; },
+ },
+ );
};
</script>
diff --git a/resources/js/composables/echo/subscribePrivateChannel.ts b/resources/js/composables/echo/subscribePrivateChannel.ts
new file mode 100644
index 000000000..4a8e405b9
--- /dev/null
+++ b/resources/js/composables/echo/subscribePrivateChannel.ts
@@ -0,0 +1,18 @@
+import { echo } from '@laravel/echo-vue';
+
+/** Resolves once subscribed (or on timeout), false only on a definitive subscribe error. */
+export const subscribePrivateChannel = (
+ channelName: string,
+ configure: (channel: ReturnType<ReturnType<typeof echo>['private']>) => void,
+ timeoutMs = 5000,
+): Promise<boolean> => {
+ const channel = echo().private(channelName);
+ configure(channel);
+
+ return new Promise((resolve) => {
+ const timeout = setTimeout(() => resolve(true), timeoutMs);
+ channel
+ .subscribed(() => { clearTimeout(timeout); resolve(true); })
+ .error(() => { clearTimeout(timeout); resolve(false); });
+ });
+};
diff --git a/resources/js/composables/echo/useAiStream.ts b/resources/js/composables/echo/useAiStream.ts
index 877939fca..2633bad95 100644
--- a/resources/js/composables/echo/useAiStream.ts
+++ b/resources/js/composables/echo/useAiStream.ts
@@ -1,6 +1,9 @@
import { echo } from '@laravel/echo-vue';
+import { trans } from 'laravel-vue-i18n';
import { onUnmounted, ref } from 'vue';
+import { subscribePrivateChannel } from './subscribePrivateChannel';
+
interface TextDeltaEvent {
delta: string;
}
@@ -11,6 +14,8 @@ interface ErrorEvent {
export type AiStreamStatus = 'idle' | 'streaming' | 'completed' | 'failed';
+export const aiGenerationChannel = (userId: string, generationId: string): string => `user.${userId}.ai-gen.${generationId}`;
+
/**
* Subscribe to a private channel for an in-flight AI generation.
* Reactive state accumulates `.TextDelta` event deltas and transitions to
@@ -35,23 +40,25 @@ export const useAiStream = () => {
subscribedName = null;
};
- const subscribe = (channelName: string) => {
+ const subscribe = (channelName: string): Promise<boolean> => {
unsubscribe();
reset();
status.value = 'streaming';
subscribedName = channelName;
- echo().private(channelName)
- .listen('.text_delta', (e: TextDeltaEvent) => {
- text.value += e.delta ?? '';
- })
- .listen('.stream_end', () => {
- status.value = 'completed';
- })
- .listen('.error', (e: ErrorEvent) => {
- status.value = 'failed';
- errorMessage.value = e?.message ?? 'AI generation failed';
- });
+ return subscribePrivateChannel(channelName, (channel) => {
+ channel
+ .listen('.text_delta', (e: TextDeltaEvent) => {
+ text.value += e.delta ?? '';
+ })
+ .listen('.stream_end', () => {
+ status.value = 'completed';
+ })
+ .listen('.error', (e: ErrorEvent) => {
+ status.value = 'failed';
+ errorMessage.value = e?.message ?? trans('posts.ai.generate.errors.generation_failed');
+ });
+ });
};
onUnmounted(() => unsubscribe());
diff --git a/resources/js/composables/useAiMediaRegeneration.ts b/resources/js/composables/useAiMediaRegeneration.ts
index b026439f1..418e72cf4 100644
--- a/resources/js/composables/useAiMediaRegeneration.ts
+++ b/resources/js/composables/useAiMediaRegeneration.ts
@@ -1,9 +1,11 @@
-import { useHttp } from '@inertiajs/vue3';
+import { useHttp, usePage } from '@inertiajs/vue3';
import { echo } from '@laravel/echo-vue';
import { trans } from 'laravel-vue-i18n';
import { computed, onUnmounted, ref } from 'vue';
import { toast } from 'vue-sonner';
+import { subscribePrivateChannel } from '@/composables/echo/subscribePrivateChannel';
+import { extractErrorMessage } from '@/lib/httpError';
import { regenerateMedia as regeneratePostAiMedia } from '@/routes/app/posts/ai';
import type { MediaItem } from '@/types/media';
@@ -14,10 +16,6 @@ export interface RegenerationPayload {
type RegenerationStatus = 'idle' | 'starting' | 'processing';
-interface RegenerationStartResponse {
- channel?: string;
-}
-
interface RegenerationEvent {
media: MediaItem | null;
error?: string | null;
@@ -30,19 +28,25 @@ interface UseAiMediaRegenerationOptions {
onCompleted?: () => void;
}
+const aiMediaRegenerationChannel = (userId: string, regenerationId: string): string => `user.${userId}.ai-media.${regenerationId}`;
+
const REGENERATION_TIMEOUT_MS = 180_000;
export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) => {
+ const page = usePage();
const instruction = ref('');
const errorMessage = ref<string | null>(null);
+ const instructionError = ref<string | undefined>(undefined);
const status = ref<RegenerationStatus>('idle');
- const httpRegenerate = useHttp<{ instruction: string }>({
+ const httpRegenerate = useHttp<{ instruction: string; regeneration_id: string }>({
instruction: '',
+ regeneration_id: '',
});
let subscribedChannel: string | null = null;
let regenerationTimeout: ReturnType<typeof setTimeout> | null = null;
+ let unmounted = false;
const isBusy = computed(() => status.value !== 'idle');
const isProcessing = computed(() => status.value === 'processing');
@@ -71,6 +75,7 @@ export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) =
const resetState = () => {
instruction.value = '';
errorMessage.value = null;
+ instructionError.value = undefined;
status.value = 'idle';
clearRegenerationTimeout();
unsubscribe();
@@ -103,7 +108,7 @@ export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) =
options.onCompleted?.();
};
- const subscribe = (channel: string) => {
+ const subscribe = (channel: string): Promise<boolean> => {
subscribedChannel = channel;
status.value = 'processing';
@@ -113,9 +118,9 @@ export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) =
unsubscribe();
}, REGENERATION_TIMEOUT_MS);
- echo()
- .private(channel)
- .listen('.ai.media.regenerated', (event: RegenerationEvent) => handleRegenerationResult(event));
+ return subscribePrivateChannel(channel, (ch) => {
+ ch.listen('.ai.media.regenerated', (event: RegenerationEvent) => handleRegenerationResult(event));
+ });
};
const submit = async () => {
@@ -127,32 +132,50 @@ export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) =
}
if (!instructionValue) {
- setIdleWithError(trans('posts.ai.image_regenerate.errors.required'));
+ errorMessage.value = null;
+ instructionError.value = trans('posts.ai.image_regenerate.errors.required');
return;
}
errorMessage.value = null;
+ instructionError.value = undefined;
status.value = 'starting';
- httpRegenerate.instruction = instructionValue;
+
+ const regenerationId = crypto.randomUUID();
+ const channel = aiMediaRegenerationChannel(String(page.props.auth.user.id), regenerationId);
try {
- const response = (await httpRegenerate.post(
- regeneratePostAiMedia.url({ post: options.postId, mediaId: mediaItem.id }),
- )) as RegenerationStartResponse;
- const channel = String(response.channel ?? '');
+ const subscribed = await subscribe(channel);
- if (!channel) {
- throw new Error('Missing channel in regeneration response.');
+ if (unmounted) {
+ unsubscribe();
+ return;
}
- subscribe(channel);
+ if (!subscribed) {
+ throw new Error('Channel subscription failed');
+ }
+
+ httpRegenerate.instruction = instructionValue;
+ httpRegenerate.regeneration_id = regenerationId;
+ await httpRegenerate.post(regeneratePostAiMedia.url({ post: options.postId, mediaId: mediaItem.id }));
+
+ if (httpRegenerate.hasErrors) {
+ clearRegenerationTimeout();
+ unsubscribe();
+ status.value = 'idle';
+ instructionError.value = httpRegenerate.errors.instruction ?? trans('posts.ai.image_regenerate.errors.start_failed');
+ return;
+ }
} catch (error: unknown) {
- const responseMessage = (error as { response?: { data?: { message?: string } } })?.response?.data?.message;
- setIdleWithError(responseMessage ?? trans('posts.ai.image_regenerate.errors.start_failed'));
+ clearRegenerationTimeout();
+ unsubscribe();
+ setIdleWithError(extractErrorMessage(error) ?? trans('posts.ai.image_regenerate.errors.start_failed'));
}
};
onUnmounted(() => {
+ unmounted = true;
clearRegenerationTimeout();
unsubscribe();
});
@@ -160,6 +183,7 @@ export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) =
return {
instruction,
errorMessage,
+ instructionError,
status,
isBusy,
isProcessing,
@@ -169,4 +193,3 @@ export const useAiMediaRegeneration = (options: UseAiMediaRegenerationOptions) =
blockDismissWhileBusy,
};
};
-
diff --git a/resources/js/lib/httpError.ts b/resources/js/lib/httpError.ts
new file mode 100644
index 000000000..4a38d9521
--- /dev/null
+++ b/resources/js/lib/httpError.ts
@@ -0,0 +1,9 @@
+export const extractErrorMessage = (error: unknown): string | null => {
+ const data = (error as { response?: { data?: string } })?.response?.data;
+ if (typeof data !== 'string') return null;
+ try {
+ return JSON.parse(data)?.message ?? null;
+ } catch {
+ return null;
+ }
+};
diff --git a/resources/js/pages/posts/ai/Loading.vue b/resources/js/pages/posts/ai/Loading.vue
index 40bc02456..0476d7421 100644
--- a/resources/js/pages/posts/ai/Loading.vue
+++ b/resources/js/pages/posts/ai/Loading.vue
@@ -1,13 +1,16 @@
<script setup lang="ts">
-import { Head, router } from '@inertiajs/vue3';
+import { Head, router, useHttp } from '@inertiajs/vue3';
import { echo } from '@laravel/echo-vue';
import { IconLoader2, IconSparkles } from '@tabler/icons-vue';
import { trans } from 'laravel-vue-i18n';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
+import { start as startPostCreation } from '@/actions/App/Http/Controllers/App/PostAiCreateController';
import { Button } from '@/components/ui/button';
-import date from '@/date';
+import { subscribePrivateChannel } from '@/composables/echo/subscribePrivateChannel';
+import dateFormat from '@/date';
import AppLayout from '@/layouts/AppLayout.vue';
+import { extractErrorMessage } from '@/lib/httpError';
import { calendar as calendarRoute } from '@/routes/app';
import { create as createPostRoute, edit as editPostRoute } from '@/routes/app/posts';
@@ -17,15 +20,21 @@ const props = defineProps<{
imageCount: number;
format: string;
prompt: string;
+ socialAccountId: string | null;
+ date: string | null;
+ template: string;
+ applyBrandVisuals: boolean;
}>();
const status = ref<'loading' | 'error'>('loading');
const errorMessage = ref('');
-
-let echoChannel: any = null;
+let subscribed = false;
+let unmounted = false;
+let generationTimeout: ReturnType<typeof setTimeout> | null = null;
const TEXT_BASELINE_SECONDS = 30;
const PER_IMAGE_SECONDS = 35;
+const GENERATION_TIMEOUT_MS = 960_000;
const estimatedSeconds = computed(() => TEXT_BASELINE_SECONDS + props.imageCount * PER_IMAGE_SECONDS);
@@ -54,17 +63,49 @@ const currentTip = computed(() => trans(tipKeys[tipIndex.value % tipKeys.length]
const elapsed = ref(0);
let elapsedTimer: ReturnType<typeof setInterval> | null = null;
-const elapsedLabel = computed(() => date.formatClock(elapsed.value));
+const elapsedLabel = computed(() => dateFormat.formatClock(elapsed.value));
const progress = computed(() => {
const ratio = elapsed.value / estimatedSeconds.value;
return Math.min(0.95, ratio);
});
-const subscribe = () => {
- echoChannel = echo()
- .private(props.channel)
- .listen('.ai.creation.completed', (e: { post_id?: string; error?: string }) => {
+const unsubscribe = () => {
+ if (subscribed) {
+ echo().leave(`private-${props.channel}`);
+ subscribed = false;
+ }
+ if (generationTimeout) {
+ clearTimeout(generationTimeout);
+ generationTimeout = null;
+ }
+};
+
+const httpStart = useHttp<{
+ creation_id: string;
+ format: string;
+ social_account_id: string | null;
+ image_count: number;
+ prompt: string;
+ date: string | null;
+ template: string;
+ apply_brand_visuals: boolean;
+}>({
+ creation_id: props.creationId,
+ format: props.format,
+ social_account_id: props.socialAccountId,
+ image_count: props.imageCount,
+ prompt: props.prompt,
+ date: props.date,
+ template: props.template,
+ apply_brand_visuals: props.applyBrandVisuals,
+});
+
+const startGeneration = async () => {
+ const confirmed = await subscribePrivateChannel(props.channel, (channel) => {
+ subscribed = true;
+ channel.listen('.ai.creation.completed', (e: { post_id?: string; error?: string }) => {
+ unsubscribe();
if (e.error || !e.post_id) {
status.value = 'error';
errorMessage.value = e.error ?? trans('posts.create.steps.preview_error');
@@ -72,12 +113,38 @@ const subscribe = () => {
}
router.visit(editPostRoute(e.post_id).url);
});
-};
+ });
-const unsubscribe = () => {
- if (echoChannel) {
- echo().leave(`private-${props.channel}`);
- echoChannel = null;
+ if (unmounted) {
+ unsubscribe();
+ return;
+ }
+
+ if (!confirmed) {
+ unsubscribe();
+ status.value = 'error';
+ errorMessage.value = trans('posts.create.steps.preview_error');
+ return;
+ }
+
+ generationTimeout = setTimeout(() => {
+ unsubscribe();
+ status.value = 'error';
+ errorMessage.value = trans('posts.create.steps.preview_error');
+ }, GENERATION_TIMEOUT_MS);
+
+ try {
+ await httpStart.post(startPostCreation.url());
+
+ if (httpStart.hasErrors) {
+ unsubscribe();
+ status.value = 'error';
+ errorMessage.value = httpStart.errors.social_account_id ?? Object.values(httpStart.errors)[0] ?? trans('posts.create.steps.preview_error');
+ }
+ } catch (error: unknown) {
+ unsubscribe();
+ status.value = 'error';
+ errorMessage.value = extractErrorMessage(error) ?? trans('posts.create.steps.preview_error');
}
};
@@ -90,7 +157,7 @@ const createAnother = () => {
};
onMounted(() => {
- subscribe();
+ startGeneration();
tipTimer = setInterval(() => {
tipIndex.value = (tipIndex.value + 1) % tipKeys.length;
}, 5000);
@@ -100,6 +167,7 @@ onMounted(() => {
});
onBeforeUnmount(() => {
+ unmounted = true;
unsubscribe();
if (tipTimer) clearInterval(tipTimer);
if (elapsedTimer) clearInterval(elapsedTimer);
@@ -158,7 +226,10 @@ onBeforeUnmount(() => {
{{ errorMessage || $t('posts.create.steps.preview_error') }}
</p>
</div>
- <Button @click="leave">{{ $t('posts.create.steps.loading_leave_cta') }}</Button>
+ <div class="flex flex-wrap items-center justify-center gap-2">
+ <Button @click="createAnother">{{ $t('posts.create.steps.loading_create_another_cta') }}</Button>
+ <Button variant="outline" @click="leave">{{ $t('posts.create.steps.loading_leave_cta') }}</Button>
+ </div>
</div>
</div>
</AppLayout>
diff --git a/tests/Feature/Ai/PostAiCreateTest.php b/tests/Feature/Ai/PostAiCreateTest.php
index deb01d67f..f34aa5edb 100644
--- a/tests/Feature/Ai/PostAiCreateTest.php
+++ b/tests/Feature/Ai/PostAiCreateTest.php
@@ -10,6 +10,7 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\AiPromptRules;
use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
beforeEach(function () {
@@ -20,7 +21,7 @@ beforeEach(function () {
});
test('start requires authentication', function () {
- $this->postJson(route('app.posts.ai.create'), ['prompt' => 'hello', 'format' => 'x_post'])
+ $this->postJson(route('app.posts.ai.create'), ['prompt' => 'hello', 'format' => 'x_post', 'creation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNAUTHORIZED);
});
@@ -28,16 +29,34 @@ test('start validates prompt is required', function () {
Bus::fake();
$this->actingAs($this->user)
- ->postJson(route('app.posts.ai.create'), ['format' => 'x_post'])
+ ->postJson(route('app.posts.ai.create'), ['format' => 'x_post', 'creation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['prompt']);
});
+test('start requires a valid creation_id', function (mixed $creationId) {
+ Bus::fake();
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.posts.ai.create'), [
+ 'prompt' => 'hello',
+ 'format' => 'x_post',
+ 'creation_id' => $creationId,
+ ])
+ ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
+ ->assertJsonValidationErrors(['creation_id']);
+
+ Bus::assertNotDispatched(StreamPostCreation::class);
+})->with([
+ 'missing' => [null],
+ 'not a uuid' => ['not-a-uuid'],
+]);
+
test('start rejects a prompt shorter than the minimum length', function () {
Bus::fake();
$this->actingAs($this->user)
- ->postJson(route('app.posts.ai.create'), ['prompt' => 'hi', 'format' => 'x_post'])
+ ->postJson(route('app.posts.ai.create'), ['prompt' => 'hi', 'format' => 'x_post', 'creation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['prompt']);
@@ -51,6 +70,7 @@ test('start accepts a prompt at the minimum length', function () {
->postJson(route('app.posts.ai.create'), [
'prompt' => str_repeat('a', AiPromptRules::PROMPT_MIN_LENGTH),
'format' => 'x_post',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_ACCEPTED);
@@ -64,6 +84,7 @@ test('start rejects a prompt longer than the maximum length', function () {
->postJson(route('app.posts.ai.create'), [
'prompt' => str_repeat('a', AiPromptRules::PROMPT_MAX_LENGTH + 1),
'format' => 'x_post',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['prompt']);
@@ -78,6 +99,7 @@ test('start accepts a prompt at the maximum length', function () {
->postJson(route('app.posts.ai.create'), [
'prompt' => str_repeat('a', AiPromptRules::PROMPT_MAX_LENGTH),
'format' => 'x_post',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_ACCEPTED);
@@ -88,7 +110,7 @@ test('start validates format is required', function () {
Bus::fake();
$this->actingAs($this->user)
- ->postJson(route('app.posts.ai.create'), ['prompt' => 'hello'])
+ ->postJson(route('app.posts.ai.create'), ['prompt' => 'hello', 'creation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['format']);
});
@@ -97,7 +119,7 @@ test('start validates format must be a known value', function () {
Bus::fake();
$this->actingAs($this->user)
- ->postJson(route('app.posts.ai.create'), ['prompt' => 'hello', 'format' => 'tiktok_video'])
+ ->postJson(route('app.posts.ai.create'), ['prompt' => 'hello', 'format' => 'tiktok_video', 'creation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['format']);
});
@@ -116,6 +138,7 @@ test('start accepts instagram_carousel as a generation format', function () {
'format' => 'instagram_carousel',
'social_account_id' => $account->id,
'image_count' => 5,
+ 'creation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_ACCEPTED);
@@ -136,11 +159,12 @@ test('start rejects social_account_id from another workspace', function () {
'prompt' => 'hello',
'format' => 'x_post',
'social_account_id' => $foreignAccount->id,
+ 'creation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_FORBIDDEN);
});
-test('start dispatches StreamPostCreation and returns creation_id and channel', function () {
+test('start dispatches StreamPostCreation using the client-supplied creation id', function () {
Bus::fake();
$account = SocialAccount::factory()->create([
@@ -148,17 +172,19 @@ test('start dispatches StreamPostCreation and returns creation_id and channel',
'platform' => Platform::X,
]);
+ $creationId = Str::uuid()->toString();
+
$response = $this->actingAs($this->user)
->postJson(route('app.posts.ai.create'), [
'prompt' => 'Write a post about productivity',
'format' => 'x_post',
'social_account_id' => $account->id,
'image_count' => 2,
+ 'creation_id' => $creationId,
])
->assertStatus(Response::HTTP_ACCEPTED);
- $creationId = $response->json('creation_id');
- expect($creationId)->toBeString()->not->toBeEmpty();
+ expect($response->json('creation_id'))->toBe($creationId);
expect($response->json('channel'))->toBe("user.{$this->user->id}.ai-creation.{$creationId}");
Bus::assertDispatched(StreamPostCreation::class, function ($job) use ($creationId, $account) {
@@ -172,6 +198,49 @@ test('start dispatches StreamPostCreation and returns creation_id and channel',
});
});
+test('start does not dispatch StreamPostCreation twice for the same creation_id', function () {
+ Bus::fake();
+
+ $creationId = Str::uuid()->toString();
+ $payload = [
+ 'prompt' => 'Write a post about productivity',
+ 'format' => 'x_post',
+ 'creation_id' => $creationId,
+ ];
+
+ $this->actingAs($this->user)->postJson(route('app.posts.ai.create'), $payload)
+ ->assertStatus(Response::HTTP_ACCEPTED);
+
+ $this->actingAs($this->user)->postJson(route('app.posts.ai.create'), $payload)
+ ->assertStatus(Response::HTTP_ACCEPTED);
+
+ Bus::assertDispatchedTimes(StreamPostCreation::class, 1);
+});
+
+test('start dispatches for two different users sharing the same creation_id', function () {
+ Bus::fake();
+
+ $otherUser = User::factory()->create();
+ $otherWorkspace = Workspace::factory()->create(['user_id' => $otherUser->id]);
+ $otherWorkspace->members()->attach($otherUser->id, ['role' => Role::Member->value]);
+ $otherUser->update(['current_workspace_id' => $otherWorkspace->id]);
+
+ $creationId = Str::uuid()->toString();
+ $payload = [
+ 'prompt' => 'Write a post about productivity',
+ 'format' => 'x_post',
+ 'creation_id' => $creationId,
+ ];
+
+ $this->actingAs($this->user)->postJson(route('app.posts.ai.create'), $payload)
+ ->assertStatus(Response::HTTP_ACCEPTED);
+
+ $this->actingAs($otherUser)->postJson(route('app.posts.ai.create'), $payload)
+ ->assertStatus(Response::HTTP_ACCEPTED);
+
+ Bus::assertDispatchedTimes(StreamPostCreation::class, 2);
+});
+
test('start works without social_account_id', function () {
Bus::fake();
@@ -179,6 +248,7 @@ test('start works without social_account_id', function () {
->postJson(route('app.posts.ai.create'), [
'prompt' => 'Write a LinkedIn post',
'format' => 'linkedin_post',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_ACCEPTED)
->assertJsonStructure(['creation_id', 'channel']);
@@ -194,6 +264,7 @@ test('start dispatches the job carrying the date param when provided', function
'prompt' => 'hello',
'format' => 'x_post',
'date' => '2026-06-15',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertAccepted();
@@ -208,6 +279,7 @@ test('start carries apply_brand_visuals=false when the user lets the AI decide c
'prompt' => 'hello',
'format' => 'x_post',
'apply_brand_visuals' => false,
+ 'creation_id' => Str::uuid()->toString(),
])
->assertAccepted();
@@ -221,6 +293,7 @@ test('start defaults apply_brand_visuals to true when omitted', function () {
->postJson(route('app.posts.ai.create'), [
'prompt' => 'hello',
'format' => 'x_post',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertAccepted();
@@ -235,6 +308,7 @@ test('start rejects invalid date format', function () {
'prompt' => 'hello',
'format' => 'x_post',
'date' => 'not-a-date',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertUnprocessable()
->assertJsonValidationErrors(['date']);
@@ -251,7 +325,7 @@ test('loading page renders the Inertia component with channel and query context'
$creationId = '019e0532-7b74-7369-b238-a5f2a93d12b7';
$this->actingAs($this->user)
- ->get(route('app.posts.ai.loading', $creationId).'?images=5&format=instagram_carousel&prompt=Hello')
+ ->get(route('app.posts.ai.loading', $creationId).'?images=5&format=instagram_carousel&prompt=Hello&template=tweet_card&apply_brand_visuals=0')
->assertInertia(fn ($page) => $page
->component('posts/ai/Loading')
->where('creationId', $creationId)
@@ -259,6 +333,21 @@ test('loading page renders the Inertia component with channel and query context'
->where('imageCount', 5)
->where('format', 'instagram_carousel')
->where('prompt', 'Hello')
+ ->where('template', 'tweet_card')
+ ->where('applyBrandVisuals', false)
+ );
+});
+
+test('loading page defaults template and applyBrandVisuals when omitted', function () {
+ $creationId = '019e0532-7b74-7369-b238-a5f2a93d12b7';
+
+ $this->actingAs($this->user)
+ ->get(route('app.posts.ai.loading', $creationId))
+ ->assertInertia(fn ($page) => $page
+ ->where('template', 'image_card')
+ ->where('applyBrandVisuals', true)
+ ->where('socialAccountId', null)
+ ->where('date', null)
);
});
@@ -275,6 +364,7 @@ it('defaults to the image_card template when none is given', function () {
->postJson(route('app.posts.ai.create'), [
'format' => 'instagram_feed',
'prompt' => 'a post about coffee',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertAccepted();
@@ -289,6 +379,7 @@ it('rejects an unknown template', function () {
'format' => 'instagram_feed',
'prompt' => 'x',
'template' => 'bogus',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertUnprocessable()
->assertJsonValidationErrors(['template']);
@@ -302,6 +393,7 @@ it('allows image_card without a social account', function () {
'format' => 'instagram_feed',
'prompt' => 'a post about coffee',
'template' => 'image_card',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertAccepted();
});
@@ -314,6 +406,7 @@ it('requires social_account_id when the template needsAccount', function () {
'format' => 'x_post',
'prompt' => 'a punchy take on productivity',
'template' => 'tweet_card',
+ 'creation_id' => Str::uuid()->toString(),
])
->assertUnprocessable()
->assertJsonValidationErrors(['social_account_id']);
diff --git a/tests/Feature/Ai/PostAiGenerateTest.php b/tests/Feature/Ai/PostAiGenerateTest.php
index a80f44e64..32ff52b84 100644
--- a/tests/Feature/Ai/PostAiGenerateTest.php
+++ b/tests/Feature/Ai/PostAiGenerateTest.php
@@ -9,6 +9,7 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\AiPromptRules;
use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
beforeEach(function () {
@@ -23,14 +24,14 @@ beforeEach(function () {
});
test('endpoint requires authentication', function () {
- $this->postJson(route('app.posts.ai.generate', $this->post), ['prompt' => 'hi'])
+ $this->postJson(route('app.posts.ai.generate', $this->post), ['prompt' => 'hi', 'generation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNAUTHORIZED);
});
test('endpoint validates prompt is required', function () {
Bus::fake();
$this->actingAs($this->user)
- ->postJson(route('app.posts.ai.generate', $this->post), [])
+ ->postJson(route('app.posts.ai.generate', $this->post), ['generation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['prompt']);
});
@@ -41,6 +42,7 @@ test('endpoint rejects a prompt longer than the maximum length', function () {
$this->actingAs($this->user)
->postJson(route('app.posts.ai.generate', $this->post), [
'prompt' => str_repeat('a', AiPromptRules::PROMPT_MAX_LENGTH + 1),
+ 'generation_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
->assertJsonValidationErrors(['prompt']);
@@ -48,28 +50,47 @@ test('endpoint rejects a prompt longer than the maximum length', function () {
Bus::assertNotDispatched(StreamPostContent::class);
});
+test('endpoint requires a valid generation_id', function (mixed $generationId) {
+ Bus::fake();
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.posts.ai.generate', $this->post), [
+ 'prompt' => 'hi',
+ 'generation_id' => $generationId,
+ ])
+ ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
+ ->assertJsonValidationErrors(['generation_id']);
+
+ Bus::assertNotDispatched(StreamPostContent::class);
+})->with([
+ 'missing' => [null],
+ 'not a uuid' => ['not-a-uuid'],
+]);
+
test('endpoint blocks access to other workspace posts', function () {
Bus::fake();
$otherWorkspace = Workspace::factory()->create();
$foreignPost = Post::factory()->create(['workspace_id' => $otherWorkspace->id]);
$this->actingAs($this->user)
- ->postJson(route('app.posts.ai.generate', $foreignPost), ['prompt' => 'hi'])
+ ->postJson(route('app.posts.ai.generate', $foreignPost), ['prompt' => 'hi', 'generation_id' => Str::uuid()->toString()])
->assertStatus(Response::HTTP_NOT_FOUND);
});
-test('endpoint dispatches StreamPostContent and returns generation id and channel', function () {
+test('endpoint dispatches StreamPostContent using the client-supplied generation id, so the frontend can subscribe before dispatch', function () {
Bus::fake();
+ $generationId = Str::uuid()->toString();
+
$response = $this->actingAs($this->user)
->postJson(route('app.posts.ai.generate', $this->post), [
'prompt' => 'Write a post about Mondays',
'current_content' => 'Old content',
+ 'generation_id' => $generationId,
])
->assertStatus(Response::HTTP_ACCEPTED);
- $generationId = $response->json('generation_id');
- expect($generationId)->toBeString()->not->toBeEmpty();
+ expect($response->json('generation_id'))->toBe($generationId);
expect($response->json('channel'))->toBe("user.{$this->user->id}.ai-gen.{$generationId}");
Bus::assertDispatched(StreamPostContent::class, function ($job) use ($generationId) {
diff --git a/tests/Feature/Ai/PostAiRegenerateMediaTest.php b/tests/Feature/Ai/PostAiRegenerateMediaTest.php
index 80dd81c66..d8b38ea01 100644
--- a/tests/Feature/Ai/PostAiRegenerateMediaTest.php
+++ b/tests/Feature/Ai/PostAiRegenerateMediaTest.php
@@ -12,6 +12,7 @@ use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
beforeEach(function () {
@@ -57,20 +58,22 @@ beforeEach(function () {
]);
});
-test('regenerate media dispatches async job and returns channel payload', function () {
+test('regenerate media dispatches async job using the client-supplied regeneration id', function () {
Bus::fake();
+ $regenerationId = Str::uuid()->toString();
+
$response = $this->actingAs($this->user)
->postJson(route('app.posts.ai.regenerate-media', [
'post' => $this->post->id,
'mediaId' => 'media-ai-1',
]), [
'instruction' => 'Replace ECP with ICP and keep the same visual style.',
+ 'regeneration_id' => $regenerationId,
])
->assertStatus(Response::HTTP_ACCEPTED);
- $regenerationId = $response->json('regeneration_id');
- expect($regenerationId)->toBeString()->not->toBeEmpty();
+ expect($response->json('regeneration_id'))->toBe($regenerationId);
expect($response->json('channel'))->toBe("user.{$this->user->id}.ai-media.{$regenerationId}");
Bus::assertDispatched(RegeneratePostMediaImage::class, function (RegeneratePostMediaImage $job) use ($regenerationId) {
@@ -82,6 +85,26 @@ test('regenerate media dispatches async job and returns channel payload', functi
});
});
+test('regenerate media requires a valid regeneration_id', function (mixed $regenerationId) {
+ Bus::fake();
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.posts.ai.regenerate-media', [
+ 'post' => $this->post->id,
+ 'mediaId' => 'media-ai-1',
+ ]), [
+ 'instruction' => 'Fix typo',
+ 'regeneration_id' => $regenerationId,
+ ])
+ ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
+ ->assertJsonValidationErrors(['regeneration_id']);
+
+ Bus::assertNotDispatched(RegeneratePostMediaImage::class);
+})->with([
+ 'missing' => [null],
+ 'not a uuid' => ['not-a-uuid'],
+]);
+
test('regenerate media rejects non ai media items', function () {
Bus::fake();
@@ -102,8 +125,10 @@ test('regenerate media rejects non ai media items', function () {
'mediaId' => 'media-static-1',
]), [
'instruction' => 'Change the title text',
+ 'regeneration_id' => Str::uuid()->toString(),
])
- ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
+ ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
+ ->assertJsonStructure(['errors' => ['instruction']]);
Bus::assertNotDispatched(RegeneratePostMediaImage::class);
});
@@ -117,6 +142,7 @@ test('regenerate media returns not found when media id is missing from post', fu
'mediaId' => 'missing-media-id',
]), [
'instruction' => 'Fix typo',
+ 'regeneration_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_NOT_FOUND);
@@ -134,8 +160,10 @@ test('regenerate media rejects finalized posts', function () {
'mediaId' => 'media-ai-1',
]), [
'instruction' => 'Fix typo',
+ 'regeneration_id' => Str::uuid()->toString(),
])
- ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
+ ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
+ ->assertJsonStructure(['errors' => ['instruction']]);
Bus::assertNotDispatched(RegeneratePostMediaImage::class);
});
@@ -149,6 +177,7 @@ test('regenerate media validates instruction is required', function () {
'mediaId' => 'media-ai-1',
]), [
'instruction' => ' ',
+ 'regeneration_id' => Str::uuid()->toString(),
])
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
@@ -183,6 +212,7 @@ test('regenerate media denies access when post is from another workspace', funct
'mediaId' => 'other-ai-media',
]), [
'instruction' => 'Fix typo',
+ 'regeneration_id' => Str::uuid()->toString(),
])
->assertNotFound();