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.

Merge main into feat/automations-module

Paulo Castellano21b14f7893ae
diff --cc app/Actions/Automation/Node/RunGenerateNode.php
index cec14a56b,000000000..96c8006ff
mode 100644,000000..100644
--- a/app/Actions/Automation/Node/RunGenerateNode.php
+++ b/app/Actions/Automation/Node/RunGenerateNode.php
@@@ -1,283 -1,0 +1,283 @@@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\Automation\Node;
+
+use App\Actions\Post\CreatePost;
+use App\Ai\Agents\PostContentGenerator;
+use App\Ai\Agents\PostContentHumanizer;
+use App\DataTransferObjects\Automation\NodeRunResult;
+use App\Enums\PostPlatform\ContentType;
+use App\Models\AutomationRun;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Services\Ai\RecordAiUsage;
+use App\Services\Automation\ExpressionResolver;
+use Illuminate\Support\Facades\Log;
+
+class RunGenerateNode
+{
+ public function __construct(
+ private ExpressionResolver $resolver,
+ ) {}
+
+ public function __invoke(AutomationRun $run, array $config): NodeRunResult
+ {
+ $context = $run->context ?? [];
+ $prompt = $this->resolver->resolve(data_get($config, 'prompt_template', ''), $context);
+
+ $accountsConfig = $this->resolveAccountsConfig($config);
+ ['format' => $format, 'slide_count' => $slideCount] = $this->deriveFormat($accountsConfig, $config);
+
+ $accountIds = array_values(array_filter(array_map(
+ fn ($a) => data_get($a, 'social_account_id'),
+ $accountsConfig,
+ )));
+
+ $workspace = $run->automation->workspace;
+
+ $activeAccounts = SocialAccount::query()
+ ->whereIn('id', $accountIds)
+ ->where('workspace_id', $workspace->id)
+ ->active()
+ ->get()
+ ->keyBy('id');
+
+ if ($accountIds !== [] && $activeAccounts->isEmpty()) {
+ Log::warning('RunGenerateNode: no active social accounts found, skipping account assignment', [
+ 'automation_id' => $run->automation_id,
+ 'social_account_ids' => $accountIds,
+ ]);
+ }
+
+ $agent = new PostContentGenerator(
+ workspace: $workspace,
+ format: $format,
+ slideCount: $slideCount,
+ );
+
+ $generatorResponse = $agent->prompt($prompt);
+
+ RecordAiUsage::recordText(
+ workspace: $workspace,
+ promptTokens: $generatorResponse->usage->promptTokens,
+ completionTokens: $generatorResponse->usage->completionTokens,
+ provider: (string) config('ai.default'),
+ model: (string) config('ai.default_text_model'),
+ metadata: ['agent' => 'post_generator', 'format' => $format, 'source' => 'automation'],
+ );
+
+ $structured = $generatorResponse->structured ?? [];
+
+ $structured = $this->humanize($workspace, $structured, $format);
+
+ $content = $format === 'carousel'
+ ? (string) data_get($structured, 'caption', '')
+ : (string) data_get($structured, 'content', '');
+
+ $user = $this->resolveUser($run);
+
+ $platforms = [];
+ foreach ($accountsConfig as $entry) {
+ $accountId = data_get($entry, 'social_account_id');
+ if (! $accountId || ! $activeAccounts->has($accountId)) {
+ if ($accountId) {
+ Log::warning('RunGenerateNode: account no longer active, skipping', [
+ 'automation_id' => $run->automation_id,
+ 'social_account_id' => $accountId,
+ ]);
+ }
+
+ continue;
+ }
+
+ $platforms[] = [
+ 'social_account_id' => $accountId,
+ 'content_type' => data_get($entry, 'content_type'),
+ 'meta' => data_get($entry, 'meta', []),
+ ];
+ }
+
+ // Dry runs do the AI work (so the user sees a real generation) but
+ // never persist a Post. Downstream nodes (Publish) read `is_dry_run`
+ // and skip their persistence too.
+ if ($run->is_dry_run) {
+ return NodeRunResult::completed(output: [
+ 'generated' => [
+ 'post_id' => null,
+ 'content' => $content,
+ 'dry_run' => true,
+ ],
+ ]);
+ }
+
+ $post = CreatePost::execute($workspace, $user, [
+ 'content' => $content,
+ 'media' => [],
+ 'platforms' => $platforms,
+ ]);
+
+ $run->update(['generated_post_id' => $post->id]);
+
+ return NodeRunResult::completed(output: [
+ 'generated' => [
+ 'post_id' => $post->id,
+ 'content' => $content,
+ 'post_url' => route('app.posts.show', $post->id),
+ ],
+ ]);
+ }
+
+ /**
+ * @param array<string, mixed> $structured
+ * @return array<string, mixed>
+ */
+ private function humanize(Workspace $workspace, array $structured, string $format): array
+ {
+ try {
+ $input = $format === 'carousel'
+ ? [
+ 'caption' => data_get($structured, 'caption', ''),
+ 'slides' => array_map(
+ fn ($s) => [
+ 'title' => data_get($s, 'title', ''),
+ 'body' => data_get($s, 'body', ''),
+ ],
+ data_get($structured, 'slides', []),
+ ),
+ ]
+ : [
+ 'content' => data_get($structured, 'content', ''),
+ 'image_title' => data_get($structured, 'image_title', ''),
+ 'image_body' => data_get($structured, 'image_body', ''),
+ ];
+
+ $humanizer = new PostContentHumanizer($workspace, $format);
+ $response = $humanizer->prompt(json_encode($input, JSON_UNESCAPED_UNICODE));
+ $humanized = $response->structured ?? [];
+
+ RecordAiUsage::recordText(
+ workspace: $workspace,
+ promptTokens: $response->usage->promptTokens,
+ completionTokens: $response->usage->completionTokens,
+ provider: (string) config('ai.default'),
+ model: (string) config('ai.default_text_model'),
+ metadata: ['agent' => 'post_humanizer', 'format' => $format, 'source' => 'automation'],
+ );
+
+ if ($format === 'carousel') {
+ $structured['caption'] = data_get($humanized, 'caption', $structured['caption'] ?? '');
+ $originalSlides = $structured['slides'] ?? [];
+ $humanizedSlides = data_get($humanized, 'slides', []);
+
+ foreach ($originalSlides as $i => $slide) {
+ if (isset($humanizedSlides[$i])) {
+ $originalSlides[$i]['title'] = data_get($humanizedSlides[$i], 'title', $slide['title'] ?? '');
+ $originalSlides[$i]['body'] = data_get($humanizedSlides[$i], 'body', $slide['body'] ?? '');
+ }
+ }
+
+ $structured['slides'] = $originalSlides;
+ } else {
+ $structured['content'] = data_get($humanized, 'content', $structured['content'] ?? '');
+ $structured['image_title'] = data_get($humanized, 'image_title', $structured['image_title'] ?? '');
+ $structured['image_body'] = data_get($humanized, 'image_body', $structured['image_body'] ?? '');
+ }
+ } catch (\Throwable $e) {
+ Log::warning('RunGenerateNode: PostContentHumanizer failed, using generator output as-is', [
+ 'error' => $e->getMessage(),
+ ]);
+ }
+
+ return $structured;
+ }
+
+ /**
+ * Derive the generator format and slide count from per-account content types.
+ *
+ * Carousel-capable content types:
- * - instagram_carousel (Instagram feed carousel)
++ * - instagram_feed (Instagram feed carousel = multi-image feed post)
+ * - linkedin_carousel (LinkedIn personal carousel PDF)
+ * - linkedin_page_carousel (LinkedIn page carousel PDF)
+ * - pinterest_carousel (Pinterest carousel pin)
+ * - tiktok_photo (TikTok photo carousel)
+ *
+ * When at least one account has a carousel-capable content type AND
+ * target_slide_count > 1, the generator is told to produce a carousel with
+ * that many slides. Otherwise it falls back to a single-post format.
+ *
+ * @param array<int, array{social_account_id: string, content_type: ?string, meta: array<string, mixed>}> $accountsConfig
+ * @param array<string, mixed> $config
+ * @return array{format: string, slide_count: int}
+ */
+ public function deriveFormat(array $accountsConfig, array $config): array
+ {
+ $carouselCapable = [
- ContentType::InstagramCarousel->value,
++ ContentType::InstagramFeed->value,
+ ContentType::LinkedInCarousel->value,
+ ContentType::LinkedInPageCarousel->value,
+ ContentType::PinterestCarousel->value,
+ ContentType::TikTokPhoto->value,
+ ];
+
+ $hasCarouselAccount = false;
+ foreach ($accountsConfig as $entry) {
+ if (in_array(data_get($entry, 'content_type'), $carouselCapable, strict: true)) {
+ $hasCarouselAccount = true;
+ break;
+ }
+ }
+
+ $targetSlideCount = (int) data_get($config, 'target_slide_count', 1);
+
+ if ($hasCarouselAccount && $targetSlideCount > 1) {
+ return ['format' => 'carousel', 'slide_count' => $targetSlideCount];
+ }
+
+ return ['format' => 'single', 'slide_count' => 1];
+ }
+
+ private function resolveUser(AutomationRun $run): User
+ {
+ if ($run->automation->user_id) {
+ return $run->automation->user;
+ }
+
+ return $run->automation->workspace->owner;
+ }
+
+ /**
+ * Read the current `accounts` shape and fall back to the legacy
+ * `social_account_ids` array so older automations keep running until
+ * the user re-opens and saves the node.
+ *
+ * @param array<string, mixed> $config
+ * @return array<int, array{social_account_id: string, content_type: ?string, meta: array<string, mixed>}>
+ */
+ private function resolveAccountsConfig(array $config): array
+ {
+ $accounts = data_get($config, 'accounts');
+
+ if (is_array($accounts)) {
+ return array_values(array_map(fn ($entry) => [
+ 'social_account_id' => (string) data_get($entry, 'social_account_id', ''),
+ 'content_type' => data_get($entry, 'content_type'),
+ 'meta' => (array) data_get($entry, 'meta', []),
+ ], $accounts));
+ }
+
+ $legacy = data_get($config, 'social_account_ids', []);
+
+ if (! is_array($legacy)) {
+ return [];
+ }
+
+ return array_values(array_map(fn ($id) => [
+ 'social_account_id' => (string) $id,
+ 'content_type' => null,
+ 'meta' => [],
+ ], $legacy));
+ }
+}
diff --cc resources/js/components/automations/config/GenerateNodeConfig.vue
index 9ec024565,000000000..a937e875d
mode 100644,000000..100644
--- a/resources/js/components/automations/config/GenerateNodeConfig.vue
+++ b/resources/js/components/automations/config/GenerateNodeConfig.vue
@@@ -1,337 -1,0 +1,337 @@@
+<script setup lang="ts">
+import { usePage } from '@inertiajs/vue3';
+import { IconCheck } from '@tabler/icons-vue';
+import { computed, ref, watch } from 'vue';
+
+import InputError from '@/components/InputError.vue';
+import FacebookSettings from '@/components/posts/editor/FacebookSettings.vue';
+import InstagramSettings from '@/components/posts/editor/InstagramSettings.vue';
+import LinkedInSettings from '@/components/posts/editor/LinkedInSettings.vue';
+import PinterestSettings from '@/components/posts/editor/PinterestSettings.vue';
+import TikTokSettings from '@/components/posts/editor/TikTokSettings.vue';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { Textarea } from '@/components/ui/textarea';
+import { ContentType } from '@/types/content-type';
+import { Platform } from '@/types/platform';
+import type { PinterestBoard } from '@/types';
+
+interface SocialAccount {
+ id: string;
+ platform: string;
+ display_name: string;
+ username: string;
+ avatar_url: string | null;
+}
+
+interface TikTokCreatorInfo {
+ creator_nickname: string | null;
+ creator_username: string | null;
+ creator_avatar_url: string | null;
+ privacy_level_options: string[];
+ comment_disabled: boolean;
+ duet_disabled: boolean;
+ stitch_disabled: boolean;
+ max_video_post_duration_sec: number | null;
+}
+
+interface GenerateAccount {
+ social_account_id: string;
+ content_type: string;
+ meta: Record<string, any>;
+}
+
+interface GenerateConfig {
+ accounts: GenerateAccount[];
+ target_slide_count?: number;
+ prompt_template: string;
+ image_source: 'ai' | 'unsplash' | 'none';
+}
+
+const props = defineProps<{
+ data: Record<string, unknown>;
+ errors?: Record<string, string>;
+}>();
+const emit = defineEmits<{ update: [Record<string, unknown>] }>();
+
+const page = usePage();
+
+const socialAccounts = computed<SocialAccount[]>(() => {
+ const raw = page.props.socialAccounts as { data?: SocialAccount[] } | SocialAccount[] | undefined;
+ if (!raw) return [];
+ return Array.isArray(raw) ? (raw as SocialAccount[]) : ((raw as { data: SocialAccount[] }).data ?? []);
+});
+
+const platformConfigs = computed<Record<string, any>>(() => {
+ const raw = page.props.platformConfigs as Record<string, any> | undefined;
+ return raw ?? {};
+});
+
+const pinterestBoards = computed<Record<string, PinterestBoard[]>>(() => {
+ const raw = page.props.pinterestBoards as Record<string, PinterestBoard[]> | undefined;
+ return raw ?? {};
+});
+
+const tiktokCreatorInfos = computed<Record<string, TikTokCreatorInfo>>(() => {
+ const raw = page.props.tiktokCreatorInfos as Record<string, TikTokCreatorInfo> | null | undefined;
+ return raw ?? {};
+});
+
+const defaultContentTypeFor = (platform: string): string => {
+ switch (platform) {
+ case Platform.Instagram:
+ case Platform.InstagramFacebook:
+ return ContentType.InstagramFeed;
+ case Platform.Facebook:
+ return ContentType.FacebookPost;
+ case Platform.LinkedIn:
+ return ContentType.LinkedInPost;
+ case Platform.LinkedInPage:
+ return ContentType.LinkedInPagePost;
+ case Platform.TikTok:
+ return ContentType.TikTokVideo;
+ case Platform.Pinterest:
+ return ContentType.PinterestPin;
+ case Platform.YouTube:
+ return ContentType.YouTubeShort;
+ case Platform.X:
+ return ContentType.XPost;
+ case Platform.Threads:
+ return ContentType.ThreadsPost;
+ case Platform.Bluesky:
+ return ContentType.BlueskyPost;
+ case Platform.Mastodon:
+ return ContentType.MastodonPost;
+ default:
+ return '';
+ }
+};
+
+const accountById = (id: string): SocialAccount | undefined =>
+ socialAccounts.value.find((a) => a.id === id);
+
+const normalizeAccountsFromData = (): GenerateAccount[] => {
+ const incoming = props.data.accounts;
+ if (Array.isArray(incoming)) {
+ return (incoming as any[]).map((a) => ({
+ social_account_id: String(a.social_account_id ?? ''),
+ content_type: typeof a.content_type === 'string' && a.content_type
+ ? a.content_type
+ : defaultContentTypeFor(accountById(String(a.social_account_id ?? ''))?.platform ?? ''),
+ meta: (a.meta as Record<string, any>) ?? {},
+ })).filter((a) => a.social_account_id);
+ }
+ // Backward-compat with the old shape (social_account_ids: string[]).
+ const legacyIds = props.data.social_account_ids;
+ if (Array.isArray(legacyIds)) {
+ return (legacyIds as string[]).map((id) => ({
+ social_account_id: id,
+ content_type: defaultContentTypeFor(accountById(id)?.platform ?? ''),
+ meta: {},
+ }));
+ }
+ return [];
+};
+
+const local = ref<GenerateConfig>({
+ accounts: normalizeAccountsFromData(),
+ target_slide_count: props.data.target_slide_count as number | undefined,
+ prompt_template: (props.data.prompt_template as string) ?? '',
+ image_source: (props.data.image_source as GenerateConfig['image_source']) ?? 'ai',
+});
+
+watch(local, (val) => emit('update', val), { deep: true });
+
+const isSelected = (accountId: string): boolean =>
+ local.value.accounts.some((a) => a.social_account_id === accountId);
+
+const toggleAccount = (account: SocialAccount) => {
+ if (isSelected(account.id)) {
+ local.value.accounts = local.value.accounts.filter((a) => a.social_account_id !== account.id);
+ return;
+ }
+ local.value.accounts = [
+ ...local.value.accounts,
+ {
+ social_account_id: account.id,
+ content_type: defaultContentTypeFor(account.platform),
+ meta: {},
+ },
+ ];
+};
+
+const selectedAccounts = computed(() =>
+ local.value.accounts
+ .map((entry) => {
+ const account = accountById(entry.social_account_id);
+ return account ? { entry, account } : null;
+ })
+ .filter((pair): pair is { entry: GenerateAccount; account: SocialAccount } => pair !== null),
+);
+
+const updateContentType = (accountId: string, value: string) => {
+ const idx = local.value.accounts.findIndex((a) => a.social_account_id === accountId);
+ if (idx === -1) return;
+ local.value.accounts[idx] = { ...local.value.accounts[idx], content_type: value };
+};
+
+const updateMeta = (accountId: string, value: Record<string, any>) => {
+ const idx = local.value.accounts.findIndex((a) => a.social_account_id === accountId);
+ if (idx === -1) return;
+ local.value.accounts[idx] = { ...local.value.accounts[idx], meta: value };
+};
+
+const getPublishConfig = (account: SocialAccount): Record<string, any> | null =>
+ platformConfigs.value[account.id]?.publishConfig ?? null;
+
+const getCreatorInfo = (account: SocialAccount): TikTokCreatorInfo | null =>
+ tiktokCreatorInfos.value[account.id] ?? null;
+
+const getBoards = (account: SocialAccount): PinterestBoard[] =>
+ pinterestBoards.value[account.id] ?? [];
+
- // Carousel-capable content types: instagram_carousel, linkedin_carousel,
++// Carousel-capable content types: instagram_feed, linkedin_carousel,
+// linkedin_page_carousel, pinterest_carousel, tiktok_photo.
+const carouselCapableContentTypes = new Set([
- ContentType.InstagramCarousel,
++ ContentType.InstagramFeed,
+ ContentType.LinkedInCarousel,
+ ContentType.LinkedInPageCarousel,
+ ContentType.PinterestCarousel,
+ ContentType.TikTokPhoto,
+]);
+
+const hasCarouselCapableAccount = computed(() =>
+ local.value.accounts.some((a) => carouselCapableContentTypes.has(a.content_type as ContentType)),
+);
+</script>
+
+<template>
+ <div class="space-y-4">
+ <div class="space-y-2">
+ <Label class="text-sm font-bold">{{ $t('automations.config.generate.social_accounts') }}</Label>
+ <InputError :message="errors?.accounts" />
+ <p v-if="socialAccounts.length === 0" class="text-xs text-foreground/60">
+ {{ $t('automations.config.generate.social_accounts_empty') }}
+ </p>
+ <div v-else class="space-y-2 px-1 pb-1">
+ <button
+ v-for="account in socialAccounts"
+ :key="account.id"
+ type="button"
+ class="relative flex w-full cursor-pointer items-center gap-2 rounded-xl border-2 border-foreground bg-card p-2.5 text-left text-sm shadow-2xs transition-all hover:bg-foreground/5"
+ :class="{ '!bg-violet-100 shadow-md': isSelected(account.id) }"
+ @click="toggleAccount(account)"
+ >
+ <span class="inline-flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-foreground bg-card shadow-2xs">
+ <img
+ v-if="account.avatar_url"
+ :src="account.avatar_url"
+ :alt="account.display_name"
+ class="size-full object-cover"
+ />
+ <span v-else class="text-xs font-bold text-foreground">{{ account.display_name.charAt(0).toUpperCase() }}</span>
+ </span>
+ <div class="min-w-0 flex-1">
+ <p class="truncate text-xs font-bold leading-tight text-foreground">{{ account.display_name }}</p>
+ <p class="truncate text-xs font-medium capitalize text-foreground/60">
+ {{ account.platform }}<span v-if="account.username"> · @{{ account.username }}</span>
+ </p>
+ </div>
+ <IconCheck
+ v-if="isSelected(account.id)"
+ class="absolute right-2 top-2 size-3.5 text-foreground"
+ stroke-width="3"
+ />
+ </button>
+ </div>
+ </div>
+
+ <div v-if="selectedAccounts.length > 0" class="space-y-3">
+ <template v-for="{ entry, account } in selectedAccounts" :key="account.id">
+ <InstagramSettings
+ v-if="account.platform === Platform.Instagram || account.platform === Platform.InstagramFacebook"
+ :social-account="account"
+ :content-type="entry.content_type"
+ :media="[]"
+ :meta="entry.meta"
+ :preview-only="true"
+ @update:content-type="updateContentType(account.id, $event)"
+ @update:meta="updateMeta(account.id, $event)"
+ />
+ <FacebookSettings
+ v-else-if="account.platform === Platform.Facebook"
+ :social-account="account"
+ :content-type="entry.content_type"
+ :media="[]"
+ :preview-only="true"
+ @update:content-type="updateContentType(account.id, $event)"
+ />
+ <TikTokSettings
+ v-else-if="account.platform === Platform.TikTok"
+ :social-account="account"
+ :publish-config="getPublishConfig(account)"
+ :creator-info="getCreatorInfo(account)"
+ :video-duration-sec="null"
+ :content-type="entry.content_type"
+ :meta="entry.meta"
+ :preview-only="true"
+ @update:content-type="updateContentType(account.id, $event)"
+ @update:meta="updateMeta(account.id, $event)"
+ />
+ <PinterestSettings
+ v-else-if="account.platform === Platform.Pinterest"
+ :social-account="account"
+ :content-type="entry.content_type"
+ :media="[]"
+ :boards="getBoards(account)"
+ :meta="entry.meta"
+ :preview-only="true"
+ @update:content-type="updateContentType(account.id, $event)"
+ @update:meta="updateMeta(account.id, $event)"
+ />
+ <LinkedInSettings
+ v-else-if="account.platform === Platform.LinkedIn || account.platform === Platform.LinkedInPage"
+ :social-account="account"
+ :platform="account.platform"
+ :content-type="entry.content_type"
+ :media="[]"
+ :preview-only="true"
+ @update:content-type="updateContentType(account.id, $event)"
+ />
+ </template>
+ </div>
+
+ <div v-if="hasCarouselCapableAccount">
+ <label class="mb-1 block text-sm font-medium">{{ $t('automations.config.generate.target_slide_count') }}</label>
+ <Input type="number" v-model.number="local.target_slide_count" placeholder="5" />
+ </div>
+
+ <div>
+ <label class="mb-1 block text-sm font-medium">{{ $t('automations.config.generate.prompt_template') }}</label>
+ <Textarea v-model="local.prompt_template" :rows="6" placeholder="Write a social media post about {{ trigger.title }}…" />
+ <InputError :message="errors?.prompt_template" class="mt-1" />
+ </div>
+
+ <div>
+ <label class="mb-1 block text-sm font-medium">{{ $t('automations.config.generate.image_source') }}</label>
+ <Select v-model="local.image_source">
+ <SelectTrigger class="w-full">
+ <SelectValue :placeholder="$t('automations.config.select_placeholder')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="ai">{{ $t('automations.config.generate.image_sources.ai') }}</SelectItem>
+ <SelectItem value="unsplash">{{ $t('automations.config.generate.image_sources.unsplash') }}</SelectItem>
+ <SelectItem value="none">{{ $t('automations.config.generate.image_sources.none') }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <InputError :message="errors?.image_source" class="mt-1" />
+ </div>
+ </div>
+</template>
diff --cc resources/js/components/posts/editor/FacebookSettings.vue
index cdd1a7859,00711fcb1..1f7352bd6
--- a/resources/js/components/posts/editor/FacebookSettings.vue
+++ b/resources/js/components/posts/editor/FacebookSettings.vue
@@@ -19,13 -20,13 +20,15 @@@ interface Props
socialAccount: SocialAccount | null;
contentType: string;
media: MediaItem[];
+ meta?: Record<string, any>;
disabled?: boolean;
+ previewOnly?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
disabled: false,
+ previewOnly: false,
+ meta: () => ({}),
});
const emit = defineEmits<{
@@@ -101,8 -118,27 +120,27 @@@ const warning = computed(() => getMedia
</div>
</div>
+ <div v-if="isFeed" class="space-y-2">
+ <p class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.facebook.aspect_label') }}</p>
+ <div class="flex flex-wrap gap-2">
+ <button
+ v-for="ratio in aspectRatios"
+ :key="ratio.value"
+ type="button"
+ class="cursor-pointer rounded-full border-2 px-3 py-1 text-xs font-bold uppercase tracking-widest transition-colors disabled:cursor-not-allowed disabled:opacity-50"
+ :class="selectedAspectRatio === ratio.value
+ ? 'border-foreground bg-violet-100 text-foreground shadow-2xs'
+ : 'border-foreground/30 text-foreground/70 hover:border-foreground hover:text-foreground'"
+ :disabled="disabled"
+ @click="pickAspectRatio(ratio.value)"
+ >
+ {{ $t(ratio.labelKey) }}
+ </button>
+ </div>
+ </div>
+
<p
- v-if="warning"
+ v-if="warning && !previewOnly"
class="flex items-start gap-2 rounded-lg border-2 border-foreground bg-rose-50 p-2 text-xs font-semibold text-rose-700"
>
<IconAlertTriangle class="mt-0.5 size-3.5 shrink-0" />
diff --cc tests/Feature/Automation/Node/GenerateNodeTest.php
index b803b6a7d,000000000..e2ee03459
mode 100644,000000..100644
--- a/tests/Feature/Automation/Node/GenerateNodeTest.php
+++ b/tests/Feature/Automation/Node/GenerateNodeTest.php
@@@ -1,132 -1,0 +1,133 @@@
+<?php
+
+use App\Actions\Automation\Node\RunGenerateNode;
+use App\Ai\Agents\PostContentGenerator;
+use App\Ai\Agents\PostContentHumanizer;
+use App\Enums\Post\Status as PostStatus;
++use App\Enums\PostPlatform\ContentType;
+use App\Models\AutomationRun;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\Workspace;
+
+it('creates a draft post and writes generated output to run context', function () {
+ PostContentGenerator::fake([
+ ['content' => 'Great post about Stripe Radar', 'image_title' => 'Stripe Radar', 'image_body' => 'Fraud prevention', 'image_keywords' => ['stripe', 'fraud']],
+ ]);
+
+ PostContentHumanizer::fake([
+ ['content' => 'Great post about Stripe Radar (humanized)', 'image_title' => 'Stripe Radar', 'image_body' => 'Fraud prevention'],
+ ]);
+
+ $run = AutomationRun::factory()->create([
+ 'context' => ['trigger' => ['title' => 'Stripe Radar update']],
+ ]);
+
+ $result = app(RunGenerateNode::class)($run, [
+ 'accounts' => [],
+ 'prompt_template' => 'Generate a post about: {{ trigger.title }}',
+ 'image_source' => 'none',
+ ]);
+
+ expect($result->status->value)->toBe('completed');
+ expect($result->output)->toHaveKey('generated');
+ expect($result->output['generated'])->toHaveKey('post_id');
+ expect($result->output['generated']['content'])->toBe('Great post about Stripe Radar (humanized)');
+
+ $run->refresh();
+ expect($run->generated_post_id)->not->toBeNull();
+
+ $post = Post::find($run->generated_post_id);
+ expect($post)->not->toBeNull();
+ expect($post->status)->toBe(PostStatus::Draft);
+});
+
+it('interpolates the prompt template before passing it to the generator', function () {
+ PostContentGenerator::fake([
+ ['content' => 'Interpolated content', 'image_title' => 'Title', 'image_body' => 'Body', 'image_keywords' => ['kw']],
+ ]);
+
+ PostContentHumanizer::fake([
+ ['content' => 'Interpolated content humanized', 'image_title' => 'Title', 'image_body' => 'Body'],
+ ]);
+
+ $run = AutomationRun::factory()->create([
+ 'context' => ['trigger' => ['topic' => 'AI Agents']],
+ ]);
+
+ app(RunGenerateNode::class)($run, [
+ 'accounts' => [],
+ 'prompt_template' => 'Write about {{ trigger.topic }}',
+ ]);
+
+ PostContentGenerator::assertPrompted(fn ($prompt) => $prompt->contains('Write about AI Agents'));
+});
+
+it('still creates a draft post when humanizer fails', function () {
+ PostContentGenerator::fake([
+ ['content' => 'Raw content', 'image_title' => 'Title', 'image_body' => 'Body', 'image_keywords' => ['kw']],
+ ]);
+
+ PostContentHumanizer::fake(fn () => throw new RuntimeException('Humanizer down'));
+
+ $run = AutomationRun::factory()->create([
+ 'context' => ['trigger' => ['title' => 'test']],
+ ]);
+
+ $result = app(RunGenerateNode::class)($run, [
+ 'accounts' => [],
+ 'prompt_template' => 'Write about {{ trigger.title }}',
+ ]);
+
+ expect($result->status->value)->toBe('completed');
+ expect($result->output['generated']['content'])->toBe('Raw content');
+
+ $run->refresh();
+ expect($run->generated_post_id)->not->toBeNull();
+});
+
+it('derives carousel format when a carousel-capable account is configured with target_slide_count > 1', function () {
+ $workspace = Workspace::factory()->create();
+ $account = SocialAccount::factory()->for($workspace)->create(['platform' => 'instagram']);
+
+ $action = app(RunGenerateNode::class);
+
+ $accountsConfig = [
- ['social_account_id' => (string) $account->id, 'content_type' => 'instagram_carousel', 'meta' => []],
++ ['social_account_id' => (string) $account->id, 'content_type' => ContentType::InstagramFeed->value, 'meta' => []],
+ ];
+
+ ['format' => $format, 'slide_count' => $slideCount] = $action->deriveFormat($accountsConfig, ['target_slide_count' => 5]);
+
+ expect($format)->toBe('carousel');
+ expect($slideCount)->toBe(5);
+});
+
+it('derives single format when carousel account has target_slide_count of 1', function () {
+ $workspace = Workspace::factory()->create();
+ $account = SocialAccount::factory()->for($workspace)->create(['platform' => 'instagram']);
+
+ $action = app(RunGenerateNode::class);
+
+ $accountsConfig = [
- ['social_account_id' => (string) $account->id, 'content_type' => 'instagram_carousel', 'meta' => []],
++ ['social_account_id' => (string) $account->id, 'content_type' => ContentType::InstagramFeed->value, 'meta' => []],
+ ];
+
+ ['format' => $format, 'slide_count' => $slideCount] = $action->deriveFormat($accountsConfig, ['target_slide_count' => 1]);
+
+ expect($format)->toBe('single');
+ expect($slideCount)->toBe(1);
+});
+
+it('derives single format when no carousel-capable account is configured', function () {
+ $action = app(RunGenerateNode::class);
+
+ $accountsConfig = [
- ['social_account_id' => '1', 'content_type' => 'x_post', 'meta' => []],
- ['social_account_id' => '2', 'content_type' => 'instagram_feed', 'meta' => []],
++ ['social_account_id' => '1', 'content_type' => ContentType::XPost->value, 'meta' => []],
++ ['social_account_id' => '2', 'content_type' => ContentType::InstagramReel->value, 'meta' => []],
+ ];
+
+ ['format' => $format, 'slide_count' => $slideCount] = $action->deriveFormat($accountsConfig, ['target_slide_count' => 5]);
+
+ expect($format)->toBe('single');
+ expect($slideCount)->toBe(1);
+});