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.

feat(posts): add regenerate_image option for background image handling

Paulo Castellano33e53f5bca62
diff --git a/app/Ai/Agents/PostImageRegenerator.php b/app/Ai/Agents/PostImageRegenerator.php
index 8e3b94b48..0e3b9179e 100644
--- a/app/Ai/Agents/PostImageRegenerator.php
+++ b/app/Ai/Agents/PostImageRegenerator.php
@@ -41,6 +41,9 @@ class PostImageRegenerator implements Agent, HasStructuredOutput
->items($schema->string())
->description('3-10 short keywords for image generation context.')
->required(),
+ 'regenerate_image' => $schema->boolean()
+ ->description('Whether the background image should be regenerated. Use false when only text/typo changes are needed and visual should stay the same.')
+ ->required(),
];
}
diff --git a/app/Jobs/Ai/RegeneratePostMediaImage.php b/app/Jobs/Ai/RegeneratePostMediaImage.php
index 397f1cac1..ac3ecba78 100644
--- a/app/Jobs/Ai/RegeneratePostMediaImage.php
+++ b/app/Jobs/Ai/RegeneratePostMediaImage.php
@@ -116,11 +116,12 @@ class RegeneratePostMediaImage implements ShouldQueue
* title: string,
* body: string,
* keywords: array<int, string>,
+ * background_path: string,
* language: string,
* width: int,
* height: int
* } $baseContext
- * @return array{title: string, body: string, keywords: array<int, string>}
+ * @return array{title: string, body: string, keywords: array<int, string>, regenerate_image: bool}
*/
private function regenerateSlideCopy(Workspace $workspace, Post $post, array $baseContext): array
{
@@ -154,12 +155,13 @@ class RegeneratePostMediaImage implements ShouldQueue
* title: string,
* body: string,
* keywords: array<int, string>,
+ * background_path: string,
* language: string,
* width: int,
* height: int
* } $baseContext
* @param array<string, mixed> $structured
- * @return array{title: string, body: string, keywords: array<int, string>}
+ * @return array{title: string, body: string, keywords: array<int, string>, regenerate_image: bool}
*/
private function mergeStructuredCopy(array $baseContext, array $structured): array
{
@@ -169,11 +171,12 @@ class RegeneratePostMediaImage implements ShouldQueue
'title' => trim((string) data_get($structured, 'title', $baseContext['title'])),
'body' => trim((string) data_get($structured, 'body', $baseContext['body'])),
'keywords' => $keywords !== [] ? $keywords : $baseContext['keywords'],
+ 'regenerate_image' => (bool) data_get($structured, 'regenerate_image', true),
];
}
/**
- * @param array{title: string, body: string, keywords: array<int, string>} $copy
+ * @param array{title: string, body: string, keywords: array<int, string>, regenerate_image: bool} $copy
* @param array{
* title: string,
* body: string,
@@ -196,6 +199,14 @@ class RegeneratePostMediaImage implements ShouldQueue
throw new RuntimeException('No social account available for image footer rendering.');
}
+ $reusedBackgroundPath = null;
+ if (! $copy['regenerate_image']) {
+ $reusedBackgroundPath = (string) data_get($baseContext, 'background_path', '');
+ if ($reusedBackgroundPath === '') {
+ $reusedBackgroundPath = null;
+ }
+ }
+
$rendered = app(TemplateImageGenerator::class)->render(
workspace: $workspace,
socialAccount: $socialAccount,
@@ -204,6 +215,7 @@ class RegeneratePostMediaImage implements ShouldQueue
imageKeywords: $copy['keywords'],
width: $baseContext['width'],
height: $baseContext['height'],
+ backgroundPath: $reusedBackgroundPath,
);
if (! $rendered) {
@@ -225,9 +237,11 @@ class RegeneratePostMediaImage implements ShouldQueue
array $rendered,
): array {
$renderedPath = $rendered['path'];
+ $newBackgroundPath = (string) data_get($rendered, 'source_meta.background_path', '');
+ $oldBackgroundPath = (string) data_get($target, 'source_meta.background_path', '');
try {
- return DB::transaction(function () use ($post, $rendered, $target, $workspace) {
+ $newMediaItem = DB::transaction(function () use ($post, $rendered, $target, $workspace) {
$newMediaItem = $this->buildAiMediaItem($workspace, $rendered);
$fresh = Post::query()->whereKey($post->id)->lockForUpdate()->firstOrFail();
@@ -245,8 +259,17 @@ class RegeneratePostMediaImage implements ShouldQueue
return $newMediaItem;
});
+
+ if ($oldBackgroundPath !== '' && $oldBackgroundPath !== $newBackgroundPath && Storage::exists($oldBackgroundPath)) {
+ Storage::delete($oldBackgroundPath);
+ }
+
+ return $newMediaItem;
} catch (Throwable $exception) {
$this->discardRenderedFile($renderedPath);
+ if ($newBackgroundPath !== '' && $newBackgroundPath !== $oldBackgroundPath && Storage::exists($newBackgroundPath)) {
+ Storage::delete($newBackgroundPath);
+ }
throw $exception;
}
@@ -265,6 +288,7 @@ class RegeneratePostMediaImage implements ShouldQueue
* title: string,
* body: string,
* keywords: array<int, string>,
+ * background_path: string,
* language: string,
* width: int,
* height: int
@@ -296,6 +320,7 @@ class RegeneratePostMediaImage implements ShouldQueue
'title' => $title,
'body' => $body,
'keywords' => $keywords,
+ 'background_path' => (string) data_get($sourceMeta, 'background_path', ''),
'language' => (string) data_get($sourceMeta, 'language', $workspace->content_language),
'width' => (int) data_get($sourceMeta, 'width', TemplateImageGenerator::DEFAULT_WIDTH),
'height' => (int) data_get($sourceMeta, 'height', TemplateImageGenerator::DEFAULT_HEIGHT),
diff --git a/app/Services/Image/TemplateImageGenerator.php b/app/Services/Image/TemplateImageGenerator.php
index 756eb8fd0..a33a424ef 100644
--- a/app/Services/Image/TemplateImageGenerator.php
+++ b/app/Services/Image/TemplateImageGenerator.php
@@ -50,6 +50,7 @@ class TemplateImageGenerator
array $imageKeywords,
int $width = self::DEFAULT_WIDTH,
int $height = self::DEFAULT_HEIGHT,
+ ?string $backgroundPath = null,
): ?array {
$this->width = $width;
$this->height = $height;
@@ -63,18 +64,33 @@ class TemplateImageGenerator
};
$language = $workspace->content_language;
- $imageData = $this->aiImage->generate(
- keywords: $imageKeywords,
- style: $imageStyle,
- orientation: $orientation,
- language: $language,
- brandColor: $workspace->brand_color,
- backgroundColor: $workspace->background_color,
- textColor: $workspace->text_color,
- brandDescription: $workspace->brand_description,
- );
- if ($imageData === null) {
- return null;
+ $generatedNewBackground = false;
+ $resolvedBackgroundPath = null;
+ $imageData = null;
+
+ if (is_string($backgroundPath) && trim($backgroundPath) !== '' && Storage::exists($backgroundPath)) {
+ $resolvedBackgroundPath = $backgroundPath;
+ $imageData = Storage::get($backgroundPath);
+ }
+
+ if (! is_string($imageData) || $imageData === '') {
+ $imageData = $this->aiImage->generate(
+ keywords: $imageKeywords,
+ style: $imageStyle,
+ orientation: $orientation,
+ language: $language,
+ brandColor: $workspace->brand_color,
+ backgroundColor: $workspace->background_color,
+ textColor: $workspace->text_color,
+ brandDescription: $workspace->brand_description,
+ );
+
+ if ($imageData === null) {
+ return null;
+ }
+
+ $generatedNewBackground = true;
+ $resolvedBackgroundPath = $this->storeBackgroundImage($imageData);
}
$manager = new ImageManager(Driver::class);
@@ -85,16 +101,18 @@ class TemplateImageGenerator
$filename = 'ai-images/'.uniqid('slide_', true).'.webp';
Storage::put($filename, (string) $canvas->encode(new WebpEncoder(quality: 85)));
- RecordAiUsage::recordImage(
- workspace: $workspace,
- provider: 'openai',
- model: AiImageClient::MODEL,
- metadata: [
- 'image_style' => $imageStyle->value,
- 'width' => $this->width,
- 'height' => $this->height,
- ],
- );
+ if ($generatedNewBackground) {
+ RecordAiUsage::recordImage(
+ workspace: $workspace,
+ provider: 'openai',
+ model: AiImageClient::MODEL,
+ metadata: [
+ 'image_style' => $imageStyle->value,
+ 'width' => $this->width,
+ 'height' => $this->height,
+ ],
+ );
+ }
RecordAiUsage::recordTemplate(
workspace: $workspace,
@@ -119,10 +137,22 @@ class TemplateImageGenerator
'brand_color' => $workspace->brand_color,
'background_color' => $workspace->background_color,
'text_color' => $workspace->text_color,
+ 'background_path' => $resolvedBackgroundPath,
],
];
}
+ private function storeBackgroundImage(string $imageData): string
+ {
+ $manager = new ImageManager(Driver::class);
+ $background = $manager->decodeBinary($imageData)->cover($this->width, $this->height);
+ $backgroundPath = 'ai-images/'.uniqid('bg_', true).'.webp';
+
+ Storage::put($backgroundPath, (string) $background->encode(new WebpEncoder(quality: 85)));
+
+ return $backgroundPath;
+ }
+
/**
* Pick the closest aspect ratio for the active canvas so the AI image
* generator returns a photo that doesn't need heavy cropping.
diff --git a/resources/views/prompts/post_image/regenerator.blade.php b/resources/views/prompts/post_image/regenerator.blade.php
index 1a4af529a..372bfbd96 100644
--- a/resources/views/prompts/post_image/regenerator.blade.php
+++ b/resources/views/prompts/post_image/regenerator.blade.php
@@ -6,6 +6,9 @@ Your job:
- Fix spelling and grammar when needed.
- Keep output concise and suitable for image overlays.
- Preserve intent and topic; only change what is needed.
+- Set `regenerate_image` to:
+ - `false` when changes are text-only (typos, wording, capitalization, punctuation, CTA wording) and the visual background should stay the same.
+ - `true` when the user asks to change visual style, scene, objects, mood, colors, composition, or anything that requires a new background image.
Return JSON only, following the schema.
diff --git a/tests/Unit/Services/Image/TemplateImageGeneratorTest.php b/tests/Unit/Services/Image/TemplateImageGeneratorTest.php
index 2abfa5e0a..7c3f806cc 100644
--- a/tests/Unit/Services/Image/TemplateImageGeneratorTest.php
+++ b/tests/Unit/Services/Image/TemplateImageGeneratorTest.php
@@ -81,10 +81,34 @@ test('renders a slide and stores webp when AI returns bytes', function () use ($
->toHaveKey('title', 'Hello World')
->toHaveKey('brand_color', '#0000ff')
->toHaveKey('background_color', '#ffffff')
- ->toHaveKey('text_color', '#000000');
+ ->toHaveKey('text_color', '#000000')
+ ->toHaveKey('background_path');
}
Image::assertGenerated(fn ($prompt) => $prompt->contains('kitchen')
&& $prompt->contains('BRAND COLOR PALETTE')
&& $prompt->contains('blue'));
})->skip(fn () => ! extension_loaded('gd'), 'GD extension required');
+
+test('reuses existing background path when provided', function () use ($minimalPng) {
+ if (! file_exists(base_path('resources/fonts/Inter-Bold.ttf'))) {
+ $this->markTestSkipped('Inter fonts not available — skipping render-dependent test.');
+ }
+
+ $backgroundPath = 'ai-images/reuse-bg.webp';
+ Storage::put($backgroundPath, $minimalPng());
+
+ $service = new TemplateImageGenerator(new BrandColorMapper, new AiImageClient);
+ $result = $service->render(
+ workspace: Workspace::factory()->make(),
+ socialAccount: SocialAccount::factory()->make(['username' => 'testuser', 'display_name' => 'Test User']),
+ title: 'Updated title',
+ body: 'Updated body',
+ imageKeywords: [],
+ backgroundPath: $backgroundPath,
+ );
+
+ expect($result)->not->toBeNull();
+ expect(data_get($result, 'source_meta.background_path'))->toBe($backgroundPath);
+ Image::assertNothingGenerated();
+})->skip(fn () => ! extension_loaded('gd'), 'GD extension required');