fix: subscribe to AI generation channel before dispatching the job (#269)
* fix: subscribe to AI generation channel before dispatching the job AiGenerateDialog posted the generate request and only subscribed to the broadcast channel once the response came back. Reverb's plain Channel (vendor/laravel/reverb/.../Channels/Channel.php) delivers broadcasts by iterating the in-memory connection list at send time only — no history, no replay. If the queued job started streaming text_delta/stream_end events before the private-channel subscribe handshake finished, those events were gone for good and the dialog hung on 'streaming' forever. Generate the generation_id client-side, await channel subscription confirmation (Echo's channel.subscribed(), backed by pusher:subscription_succeeded) before sending the generate request, and have the backend use the client-supplied id instead of minting its own. Related to #218. * fix: handle subscribe failure, dialog-close race, and i18n hardcoded strings Code review on the previous commit surfaced real gaps: - useAiStream only handled the subscribe-success path (.subscribed()). A definitive pusher:subscription_error (expired session, CSRF mismatch) fell through to the 5s timeout and was treated as success, reproducing the exact #218 hang via a different trigger. subscribe() now returns a boolean: true on confirm-or-ambiguous-timeout (proceed optimistically), false only on an explicit error (don't dispatch work nothing will ever hear). - AiGenerateDialog now bails without dispatching if the dialog is closed while awaiting subscription confirmation (up to 5s), and unsubscribes on a post-subscribe dispatch failure so stale listeners can't flip status to 'completed' after an error was already shown. - Extracted aiGenerationChannel() so the frontend has one place to update if the channel format changes, and cross-referenced the two remaining backend copies (PostAiGenerateController, StreamPostContent). - Replaced the two hardcoded English fallback error strings with i18n keys (posts.ai.generate.errors.*) across all 16 locales — this app only ships translated copy. - Simplified subscribe(): dropped a redundant "already settled" guard and the clearTimeout bookkeeping — Promise.resolve() already no-ops after the first call, so there was nothing to guard. * fix: subscribe before dispatch in AI post creation and image regeneration flows Extracts subscribePrivateChannel as a shared helper and applies the same subscribe-before-dispatch fix from the post edit flow (issue #218) to the other two flows that stream over private channels. Post creation wizard moves the StreamPostCreation dispatch out of AiPostWizard.vue and into Loading.vue, so the channel is subscribed before the job that broadcasts on it is dispatched — previously a full page navigation happened between dispatch and subscribe with no timeout fallback, so a lost event hung the page forever. * refactor: trim explanatory comments added in the subscribe-before-dispatch fix Rationale lives in the commit history, not scattered inline comments. * refactor: trim remaining explanatory comments from the subscribe-before-dispatch fix Same cleanup as the previous commit, applied to the files from the original post-edit-flow fix. * fix: dedup post-creation dispatch, surface field-level AI errors, harden edge cases Uses ShouldBeUnique on StreamPostCreation (scoped per-user) instead of an ad-hoc cache guard, matching the pattern already used by PublishToSocialPlatform and VerifyUpcomingPostConnections. Field-level validation errors (prompt/instruction) now render inline via InputError, matching how every other form in the app surfaces them, instead of a generic status banner. Also fixes a 422 response missing the `errors` key that Inertia's client silently swallows, adds error handling around the wizard's navigation to the loading page, and extracts the duplicated error-message parsing into a shared helper.
This commit is contained in:
parent
cc08fa65e1
commit
a1a9172448
34 changed files with 490 additions and 119 deletions
|
|
@ -10,7 +10,6 @@
|
|||
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 @@ public function start(StartPostCreationRequest $request): JsonResponse
|
|||
}
|
||||
}
|
||||
|
||||
$creationId = (string) Str::uuid();
|
||||
$creationId = $request->string('creation_id')->toString();
|
||||
|
||||
StreamPostCreation::dispatch(
|
||||
userId: $request->user()->id,
|
||||
|
|
@ -69,6 +68,10 @@ public function loading(Request $request, string $creationId): InertiaResponse
|
|||
'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),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@
|
|||
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 @@ public function generate(GeneratePostContentRequest $request, Post $post): JsonR
|
|||
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,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@
|
|||
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 @@ public function regenerate(RegeneratePostMediaImageRequest $request, Post $post,
|
|||
if (PostStatusRules::blocksEditing($post)) {
|
||||
return response()->json([
|
||||
'message' => PostStatusRules::editBlockedMessage(),
|
||||
'errors' => ['instruction' => [PostStatusRules::editBlockedMessage()]],
|
||||
], Response::HTTP_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
|
|
@ -45,10 +45,11 @@ public function regenerate(RegeneratePostMediaImageRequest $request, Post $post,
|
|||
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,
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ public function rules(): array
|
|||
return [
|
||||
'prompt' => ['required', 'string', 'max:'.AiPromptRules::PROMPT_MAX_LENGTH],
|
||||
'current_content' => ['nullable', 'string', 'max:10000'],
|
||||
'generation_id' => ['required', 'string', 'uuid'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ public function rules(): array
|
|||
{
|
||||
return [
|
||||
'instruction' => ['required', 'string', 'max:1000'],
|
||||
'regeneration_id' => ['required', 'string', 'uuid'],
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ public function rules(): array
|
|||
$allowedFormats[] = ContentType::CAROUSEL_FORMAT;
|
||||
|
||||
return [
|
||||
'creation_id' => ['required', 'string', 'uuid'],
|
||||
'format' => [
|
||||
'required',
|
||||
'string',
|
||||
|
|
|
|||
|
|
@ -24,16 +24,19 @@
|
|||
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 @@ public function __construct(
|
|||
$this->onQueue('ai');
|
||||
}
|
||||
|
||||
public function uniqueId(): string
|
||||
{
|
||||
return "{$this->userId}:{$this->creationId}";
|
||||
}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$workspace = Workspace::findOrFail($this->workspaceId);
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => 'استخدام هذا المحتوى',
|
||||
'retry' => 'إعادة المحاولة',
|
||||
'cancel' => 'إلغاء',
|
||||
'errors' => [
|
||||
'start_failed' => 'تعذّر بدء الإنشاء.',
|
||||
'generation_failed' => 'فشل الإنشاء بالذكاء الاصطناعي.',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => 'المراجعة بالذكاء الاصطناعي',
|
||||
|
|
|
|||
|
|
@ -237,6 +237,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => 'Χρήση αυτού του περιεχομένου',
|
||||
'retry' => 'Δοκιμάστε ξανά',
|
||||
'cancel' => 'Ακύρωση',
|
||||
'errors' => [
|
||||
'start_failed' => 'Δεν ήταν δυνατή η έναρξη της δημιουργίας.',
|
||||
'generation_failed' => 'Η δημιουργία με AI απέτυχε.',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => 'Έλεγχος με AI',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => 'この内容を使用',
|
||||
'retry' => 'もう一度試す',
|
||||
'cancel' => 'キャンセル',
|
||||
'errors' => [
|
||||
'start_failed' => '生成を開始できませんでした。',
|
||||
'generation_failed' => 'AI生成に失敗しました。',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => 'AI でレビュー',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => '이 콘텐츠 사용',
|
||||
'retry' => '다시 시도',
|
||||
'cancel' => '취소',
|
||||
'errors' => [
|
||||
'start_failed' => '생성을 시작할 수 없습니다.',
|
||||
'generation_failed' => 'AI 생성에 실패했습니다.',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => 'AI로 검토',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => 'Использовать этот контент',
|
||||
'retry' => 'Попробовать снова',
|
||||
'cancel' => 'Отмена',
|
||||
'errors' => [
|
||||
'start_failed' => 'Не удалось начать генерацию.',
|
||||
'generation_failed' => 'Не удалось сгенерировать с помощью ИИ.',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => 'Проверить с помощью ИИ',
|
||||
|
|
|
|||
|
|
@ -237,6 +237,10 @@
|
|||
'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',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => 'Використати цей вміст',
|
||||
'retry' => 'Спробувати знову',
|
||||
'cancel' => 'Скасувати',
|
||||
'errors' => [
|
||||
'start_failed' => 'Не вдалося розпочати генерацію.',
|
||||
'generation_failed' => 'Не вдалося згенерувати за допомогою AI.',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => 'Перевірити за допомогою AI',
|
||||
|
|
|
|||
|
|
@ -235,6 +235,10 @@
|
|||
'apply' => '使用此内容',
|
||||
'retry' => '重试',
|
||||
'cancel' => '取消',
|
||||
'errors' => [
|
||||
'start_failed' => '无法开始生成。',
|
||||
'generation_failed' => 'AI 生成失败。',
|
||||
],
|
||||
],
|
||||
'review' => [
|
||||
'button_tooltip' => '用 AI 校对',
|
||||
|
|
|
|||
|
|
@ -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">
|
||||
|
|
|
|||
|
|
@ -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">
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
18
resources/js/composables/echo/subscribePrivateChannel.ts
Normal file
18
resources/js/composables/echo/subscribePrivateChannel.ts
Normal file
|
|
@ -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); });
|
||||
});
|
||||
};
|
||||
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
|
|||
9
resources/js/lib/httpError.ts
Normal file
9
resources/js/lib/httpError.ts
Normal file
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
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 @@
|
|||
});
|
||||
|
||||
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 @@
|
|||
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 @@
|
|||
->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 @@
|
|||
->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 @@
|
|||
->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 @@
|
|||
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 @@
|
|||
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 @@
|
|||
'format' => 'instagram_carousel',
|
||||
'social_account_id' => $account->id,
|
||||
'image_count' => 5,
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertStatus(Response::HTTP_ACCEPTED);
|
||||
|
||||
|
|
@ -136,11 +159,12 @@
|
|||
'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 @@
|
|||
'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 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 @@
|
|||
->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 @@
|
|||
'prompt' => 'hello',
|
||||
'format' => 'x_post',
|
||||
'date' => '2026-06-15',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertAccepted();
|
||||
|
||||
|
|
@ -208,6 +279,7 @@
|
|||
'prompt' => 'hello',
|
||||
'format' => 'x_post',
|
||||
'apply_brand_visuals' => false,
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertAccepted();
|
||||
|
||||
|
|
@ -221,6 +293,7 @@
|
|||
->postJson(route('app.posts.ai.create'), [
|
||||
'prompt' => 'hello',
|
||||
'format' => 'x_post',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertAccepted();
|
||||
|
||||
|
|
@ -235,6 +308,7 @@
|
|||
'prompt' => 'hello',
|
||||
'format' => 'x_post',
|
||||
'date' => 'not-a-date',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['date']);
|
||||
|
|
@ -251,7 +325,7 @@
|
|||
$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 @@
|
|||
->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 @@
|
|||
->postJson(route('app.posts.ai.create'), [
|
||||
'format' => 'instagram_feed',
|
||||
'prompt' => 'a post about coffee',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertAccepted();
|
||||
|
||||
|
|
@ -289,6 +379,7 @@
|
|||
'format' => 'instagram_feed',
|
||||
'prompt' => 'x',
|
||||
'template' => 'bogus',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['template']);
|
||||
|
|
@ -302,6 +393,7 @@
|
|||
'format' => 'instagram_feed',
|
||||
'prompt' => 'a post about coffee',
|
||||
'template' => 'image_card',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertAccepted();
|
||||
});
|
||||
|
|
@ -314,6 +406,7 @@
|
|||
'format' => 'x_post',
|
||||
'prompt' => 'a punchy take on productivity',
|
||||
'template' => 'tweet_card',
|
||||
'creation_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['social_account_id']);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
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 @@
|
|||
});
|
||||
|
||||
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 @@
|
|||
$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 @@
|
|||
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) {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
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 @@
|
|||
]);
|
||||
});
|
||||
|
||||
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 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 @@
|
|||
'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 @@
|
|||
'mediaId' => 'missing-media-id',
|
||||
]), [
|
||||
'instruction' => 'Fix typo',
|
||||
'regeneration_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertStatus(Response::HTTP_NOT_FOUND);
|
||||
|
||||
|
|
@ -134,8 +160,10 @@
|
|||
'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 @@
|
|||
'mediaId' => 'media-ai-1',
|
||||
]), [
|
||||
'instruction' => ' ',
|
||||
'regeneration_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
|
||||
|
||||
|
|
@ -183,6 +212,7 @@
|
|||
'mediaId' => 'other-ai-media',
|
||||
]), [
|
||||
'instruction' => 'Fix typo',
|
||||
'regeneration_id' => Str::uuid()->toString(),
|
||||
])
|
||||
->assertNotFound();
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue