refactor: migrate PostAssistantController to SDK Agent + tools

Controller now delegates to SocialMediaAssistant::prompt() and reads
generated attachments from AttachmentCollector (request-scoped). The
three preg_match branches for [GENERATE_IMAGE/VIDEO/AUDIO] commands
are gone — the LLM invokes tools directly with typed parameters.

Deleted:
- app/Services/Ai/GeminiTextGenerationService.php
- app/Services/Ai/TextGenerationService.php  (OpenAI alternative)
- app/Services/Ai/ImageGenerationService.php
- app/Services/Ai/AudioGenerationService.php
- app/Services/Ai/Contracts/TextGenerationInterface.php

Kept: VideoGenerationService (wrapped by GenerateVideo tool since
Veo is not in the SDK's provider matrix) and IntentDetector.

Tests now fake the agent via SocialMediaAssistant::fake() with either
canned text or a callable that simulates tool side-effects by pushing
directly into AttachmentCollector.
This commit is contained in:
Paulo Castellano 2026-04-16 09:59:10 -03:00
parent 3599d32af4
commit e3f80b91d4
8 changed files with 82 additions and 608 deletions

View file

@ -4,20 +4,16 @@
namespace App\Http\Controllers\App;
use App\Ai\Agents\SocialMediaAssistant;
use App\Ai\Tools\AttachmentCollector;
use App\Enums\Ai\Intent;
use App\Enums\Ai\Orientation;
use App\Enums\Ai\UsageType;
use App\Features\AiImagesLimit;
use App\Features\AiVideosLimit;
use App\Http\Requests\App\Assistant\StoreAssistantMessageRequest;
use App\Models\AiMessage;
use App\Models\AiUsageLog;
use App\Models\Post;
use App\Services\Ai\AudioGenerationService;
use App\Services\Ai\Contracts\TextGenerationInterface;
use App\Services\Ai\ImageGenerationService;
use App\Services\Ai\IntentDetector;
use App\Services\Ai\VideoGenerationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
@ -46,10 +42,7 @@ public function store(
StoreAssistantMessageRequest $request,
Post $post,
IntentDetector $intentDetector,
TextGenerationInterface $textService,
ImageGenerationService $imageService,
AudioGenerationService $audioService,
VideoGenerationService $videoService,
AttachmentCollector $collector,
): JsonResponse {
$workspace = $request->user()->currentWorkspace;
@ -67,10 +60,8 @@ public function store(
'content' => $prompt,
]);
$imageUrl = null;
if ($request->hasFile('image')) {
$media = $workspace->addMedia($request->file('image'), 'assets');
$imageUrl = $media->url;
$userMessage->update([
'attachments' => [['id' => $media->id, 'path' => $media->path, 'url' => $media->url, 'type' => 'image', 'mime_type' => $media->mime_type]],
@ -95,41 +86,15 @@ public function store(
}
try {
$previousMessages = $post->aiMessages()
->whereIn('role', ['user', 'assistant'])
->where('id', '!=', $userMessage->id)
->oldest()
->limit(20)
->get();
$imagesInThread = $post->aiMessages()
->where('role', 'assistant')
->get()
->sum(fn ($m) => collect($m->attachments ?? [])->where('type', 'image')->count());
$imagesInThread = 0;
$videosInThread = 0;
$history = $previousMessages
->map(function (AiMessage $m) use (&$imagesInThread, &$videosInThread) {
$content = $m->content;
if ($m->role === 'assistant' && ! empty($m->attachments)) {
$attachmentTypes = collect($m->attachments)
->groupBy('type')
->map(fn ($group) => count($group));
$counts = [];
foreach ($attachmentTypes as $type => $count) {
$counts[] = "{$count} {$type}";
if ($type === 'image') {
$imagesInThread += $count;
} elseif ($type === 'video') {
$videosInThread += $count;
}
}
$content .= "\n\n[This assistant message attached: ".implode(', ', $counts).']';
}
return ['role' => $m->role, 'content' => $content];
})
->all();
$videosInThread = $post->aiMessages()
->where('role', 'assistant')
->get()
->sum(fn ($m) => collect($m->attachments ?? [])->where('type', 'video')->count());
$imageLimit = (int) Feature::for($workspace->account)->value(AiImagesLimit::class);
$imageUsed = AiUsageLog::monthlyCount($workspace->account_id, UsageType::Image);
@ -152,75 +117,30 @@ public function store(
$promptWithState = "{$stateContext}\n{$prompt}";
$responseContent = $textService->generate($promptWithState, $history, $workspace, $imageUrl);
$collector->clear();
$response = (new SocialMediaAssistant(
workspace: $workspace,
post: $post,
userId: $request->user()->id,
))->prompt($promptWithState);
$responseContent = $response->text;
$attachments = $collector->all();
$attachments = [];
$generatedIntent = $intent->value;
$limitReached = false;
// Build rich context from conversation history for media generation
$conversationContext = collect($history)
->map(fn (array $m) => "{$m['role']}: {$m['content']}")
->implode("\n\n");
$buildMediaPrompt = function (string $captionText) use ($prompt, $conversationContext): string {
$parts = [$prompt];
if ($conversationContext) {
$parts[] = "Conversation context:\n{$conversationContext}";
foreach ($attachments as $attachment) {
if (isset($attachment['type'])) {
$generatedIntent = $attachment['type'];
break;
}
if ($captionText) {
$parts[] = "Caption generated for this post:\n{$captionText}";
}
return implode("\n\n", $parts);
};
if (preg_match('/\[GENERATE_IMAGE:(vertical|horizontal)\]/', $responseContent, $matches)) {
$orientation = Orientation::tryFrom(data_get($matches, 1, 'vertical')) ?? Orientation::Vertical;
$limit = Feature::for($workspace->account)->value(AiImagesLimit::class);
$used = AiUsageLog::monthlyCount($workspace->account_id, UsageType::Image);
if ($used >= $limit) {
$responseContent = __('assistant.limit_reached_images');
$limitReached = true;
} else {
$captionText = trim(preg_replace('/\[GENERATE_IMAGE:(vertical|horizontal)\]/', '', $responseContent));
$mediaPrompt = $buildMediaPrompt($captionText);
$result = $imageService->generate($mediaPrompt, $workspace, $request->user()->id, $post->id, $orientation);
$responseContent = $captionText ?: __('assistant.image_generated');
$attachments = [$result];
$generatedIntent = 'image';
}
} elseif (preg_match('/\[GENERATE_VIDEO:(vertical|horizontal)\]/', $responseContent, $matches)) {
$orientation = Orientation::tryFrom(data_get($matches, 1, 'vertical')) ?? Orientation::Vertical;
$limit = Feature::for($workspace->account)->value(AiVideosLimit::class);
$used = AiUsageLog::monthlyCount($workspace->account_id, UsageType::Video);
if ($used >= $limit) {
$responseContent = __('assistant.limit_reached_videos');
$limitReached = true;
} else {
$captionText = trim(preg_replace('/\[GENERATE_VIDEO:(vertical|horizontal)\]/', '', $responseContent));
$mediaPrompt = $buildMediaPrompt($captionText);
$result = $videoService->generate($mediaPrompt, $workspace, $request->user()->id, $post->id, $orientation);
$responseContent = $captionText ?: __('assistant.video_generated');
$attachments = [$result];
$generatedIntent = 'video';
}
} elseif (str_contains($responseContent, '[GENERATE_AUDIO]')) {
$result = $audioService->generate($prompt, $workspace, $request->user()->id, $post->id);
$responseContent = __('assistant.audio_generated');
$attachments = [$result];
$generatedIntent = 'audio';
}
$assistantMessage = $post->aiMessages()->create([
'role' => 'assistant',
'content' => $responseContent,
'attachments' => $attachments,
'metadata' => array_filter(['intent' => $generatedIntent, 'limit_reached' => $limitReached ?: null]),
'metadata' => ['intent' => $generatedIntent],
]);
return response()->json([

View file

@ -25,9 +25,6 @@
use App\Models\Workspace;
use App\Models\WorkspaceHashtag;
use App\Models\WorkspaceLabel;
use App\Services\Ai\Contracts\TextGenerationInterface;
use App\Services\Ai\GeminiTextGenerationService;
use App\Services\Ai\TextGenerationService;
use App\Socialite\InstagramProvider;
use App\Socialite\LinkedInPageExtendSocialite;
use Carbon\CarbonImmutable;
@ -74,14 +71,6 @@ public function register(): void
$this->app->register(TelescopeServiceProvider::class);
}
$this->app->bind(
TextGenerationInterface::class,
fn () => match (config('trypost.ai.text_provider')) {
'openai' => new TextGenerationService,
default => new GeminiTextGenerationService,
},
);
$this->app->scoped(AttachmentCollector::class);
}

View file

@ -1,96 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Enums\Ai\UsageType;
use App\Models\AiUsageLog;
use App\Models\Workspace;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class AudioGenerationService
{
private string $baseUrl = 'https://api.elevenlabs.io/v1';
private string $apiKey;
public function __construct()
{
$this->apiKey = config('services.elevenlabs.api_key') ?? '';
}
/**
* @return array{id: string, path: string, url: string, mime_type: string, type: string}
*/
public function generate(string $text, Workspace $workspace, ?string $userId = null, ?string $postId = null, ?string $voiceId = null): array
{
if (empty($this->apiKey)) {
throw new \RuntimeException('ElevenLabs API key is not configured. Please set ELEVENLABS_API_KEY in your .env file.');
}
$voiceId ??= config('services.elevenlabs.default_voice') ?? 'EXAVITQu4vr4xnSDxMaL';
$response = Http::timeout(120)
->withHeaders([
'xi-api-key' => $this->apiKey,
'Accept' => 'audio/mpeg',
])
->post("{$this->baseUrl}/text-to-speech/{$voiceId}", [
'text' => $text,
'model_id' => 'eleven_multilingual_v2',
'voice_settings' => [
'stability' => 0.5,
'similarity_boost' => 0.75,
],
]);
if ($response->failed()) {
Log::error('AudioGenerationService failed', ['body' => $response->body()]);
throw new \RuntimeException('Failed to generate audio. Please try again.');
}
$audioContent = $response->body();
return DB::transaction(function () use ($audioContent, $text, $workspace, $userId, $postId) {
$filename = Str::uuid().'.mp3';
$path = 'medias/'.$filename;
Storage::put($path, $audioContent);
$media = $workspace->media()->create([
'group_id' => Str::uuid()->toString(),
'collection' => 'assets',
'type' => 'video',
'path' => $path,
'original_filename' => 'ai-generated.mp3',
'mime_type' => 'audio/mpeg',
'size' => strlen($audioContent),
'order' => 0,
'meta' => ['ai_generated' => true, 'text' => Str::limit($text, 200)],
]);
AiUsageLog::create([
'account_id' => $workspace->account_id,
'workspace_id' => $workspace->id,
'user_id' => $userId,
'post_id' => $postId,
'type' => UsageType::Audio,
'provider' => 'elevenlabs',
]);
return [
'id' => $media->id,
'path' => $media->path,
'url' => $media->url,
'mime_type' => 'audio/mpeg',
'type' => 'audio',
];
});
}
}

View file

@ -1,15 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai\Contracts;
use App\Models\Workspace;
interface TextGenerationInterface
{
/**
* @param array<int, array{role: string, content: string}> $history
*/
public function generate(string $prompt, array $history = [], ?Workspace $workspace = null, ?string $imageUrl = null): string;
}

View file

@ -1,86 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Models\Workspace;
use App\Services\Ai\Contracts\TextGenerationInterface;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class GeminiTextGenerationService implements TextGenerationInterface
{
private string $apiKey;
private string $model = 'gemini-2.5-flash-lite';
public function __construct()
{
$this->apiKey = config('services.gemini.api_key') ?? '';
}
/**
* @param array<int, array{role: string, content: string}> $history
*/
public function generate(string $prompt, array $history = [], ?Workspace $workspace = null, ?string $imageUrl = null): string
{
if (empty($this->apiKey)) {
throw new \RuntimeException('Gemini API key is not configured. Please set GEMINI_API_KEY in your .env file.');
}
$systemPrompt = view('prompts.assistant.system', [
'brand_name' => $workspace?->name ?? '',
'brand_description' => $workspace?->brand_description ?? '',
'brand_website' => $workspace?->brand_website ?? '',
'tone' => $workspace?->brand_tone ?? 'professional',
'voice_notes' => $workspace?->brand_voice_notes ?? '',
'locale' => app()->getLocale(),
])->render();
$contents = [];
// Add history
foreach ($history as $message) {
$contents[] = [
'role' => data_get($message, 'role') === 'assistant' ? 'model' : 'user',
'parts' => [['text' => data_get($message, 'content')]],
];
}
// Add current prompt
$parts = [['text' => $prompt]];
if ($imageUrl) {
$imageResponse = Http::timeout(30)->get($imageUrl);
if ($imageResponse->successful()) {
$parts[] = [
'inlineData' => [
'mimeType' => $imageResponse->header('Content-Type', 'image/jpeg'),
'data' => base64_encode($imageResponse->body()),
],
];
}
}
$contents[] = ['role' => 'user', 'parts' => $parts];
$response = Http::timeout(60)
->post("https://generativelanguage.googleapis.com/v1beta/models/{$this->model}:generateContent?key={$this->apiKey}", [
'systemInstruction' => ['parts' => [['text' => $systemPrompt]]],
'contents' => $contents,
'generationConfig' => [
'maxOutputTokens' => 2048,
'temperature' => 0.7,
],
]);
if ($response->failed()) {
Log::error('GeminiTextGenerationService failed', ['body' => $response->body()]);
throw new \RuntimeException('Failed to generate text. Please try again.');
}
return data_get($response->json(), 'candidates.0.content.parts.0.text', '');
}
}

View file

@ -1,133 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Enums\Ai\Orientation;
use App\Enums\Ai\UsageType;
use App\Models\AiUsageLog;
use App\Models\Workspace;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class ImageGenerationService
{
private string $baseUrl = 'https://generativelanguage.googleapis.com/v1beta';
private string $model = 'gemini-2.5-flash-image';
private string $apiKey;
public function __construct()
{
$this->apiKey = config('services.gemini.api_key') ?? '';
}
/**
* @return array{id: string, path: string, url: string, mime_type: string, type: string}
*/
public function generate(string $prompt, Workspace $workspace, ?string $userId = null, ?string $postId = null, Orientation $orientation = Orientation::Vertical): array
{
if (empty($this->apiKey)) {
throw new \RuntimeException('Gemini API key is not configured. Please set GEMINI_API_KEY in your .env file.');
}
$aspectRatio = $orientation->aspectRatio();
$fullPrompt = view('prompts.assistant.image', [
'prompt' => $prompt,
'brand_name' => $workspace->name ?? '',
'tone' => $workspace->brand_tone ?? 'professional',
'aspect_ratio' => $aspectRatio,
])->render();
$response = Http::timeout(120)
->post("{$this->baseUrl}/models/{$this->model}:generateContent?key={$this->apiKey}", [
'contents' => [['parts' => [['text' => $fullPrompt]]]],
'generationConfig' => ['responseModalities' => ['TEXT', 'IMAGE']],
]);
if ($response->failed()) {
Log::error('ImageGenerationService failed', ['body' => $response->body()]);
throw new \RuntimeException('Failed to generate image. Please try again.');
}
$imageData = $this->extractImageFromResponse($response->json());
if (! $imageData) {
Log::warning('ImageGenerationService: no image in response', [
'response' => $response->json(),
]);
throw new \RuntimeException('No image was generated. Try a different prompt.');
}
return DB::transaction(function () use ($imageData, $prompt, $workspace, $userId, $postId) {
$extension = $this->getExtension(data_get($imageData, 'mimeType', 'image/png'));
$mimeType = data_get($imageData, 'mimeType', 'image/png');
$decoded = base64_decode(data_get($imageData, 'data'));
$filename = Str::uuid().'.'.$extension;
$path = 'medias/'.$filename;
Storage::put($path, $decoded);
$media = $workspace->media()->create([
'group_id' => Str::uuid()->toString(),
'collection' => 'assets',
'type' => 'image',
'path' => $path,
'original_filename' => 'ai-generated.'.$extension,
'mime_type' => $mimeType,
'size' => strlen($decoded),
'order' => 0,
'meta' => ['ai_generated' => true, 'prompt' => Str::limit($prompt, 200)],
]);
AiUsageLog::create([
'account_id' => $workspace->account_id,
'workspace_id' => $workspace->id,
'user_id' => $userId,
'post_id' => $postId,
'type' => UsageType::Image,
'provider' => 'gemini',
]);
return [
'id' => $media->id,
'path' => $media->path,
'url' => $media->url,
'mime_type' => $mimeType,
'type' => 'image',
];
});
}
private function extractImageFromResponse(array $response): ?array
{
$parts = data_get($response, 'candidates.0.content.parts', []);
foreach ($parts as $part) {
if (data_get($part, 'inlineData')) {
return data_get($part, 'inlineData');
}
}
return null;
}
private function getExtension(string $mimeType): string
{
return match ($mimeType) {
'image/jpeg' => 'jpg',
'image/webp' => 'webp',
'image/gif' => 'gif',
default => 'png',
};
}
}

View file

@ -1,76 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Services\Ai;
use App\Models\Workspace;
use App\Services\Ai\Contracts\TextGenerationInterface;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TextGenerationService implements TextGenerationInterface
{
private string $apiKey;
private string $baseUrl = 'https://api.openai.com/v1';
public function __construct()
{
$this->apiKey = config('services.openai.api_key') ?? '';
}
/**
* @param array<int, array{role: string, content: string}> $history
*/
public function generate(string $prompt, array $history = [], ?Workspace $workspace = null, ?string $imageUrl = null): string
{
if (empty($this->apiKey)) {
throw new \RuntimeException('OpenAI API key is not configured. Please set OPENAI_API_KEY in your .env file.');
}
$systemPrompt = view('prompts.assistant.system', [
'brand_name' => $workspace?->name ?? '',
'brand_description' => $workspace?->brand_description ?? '',
'brand_website' => $workspace?->brand_website ?? '',
'tone' => $workspace?->brand_tone ?? 'professional',
'voice_notes' => $workspace?->brand_voice_notes ?? '',
'locale' => app()->getLocale(),
])->render();
if ($imageUrl) {
$userContent = [
['type' => 'text', 'text' => $prompt],
['type' => 'image_url', 'image_url' => ['url' => $imageUrl]],
];
} else {
$userContent = $prompt;
}
$messages = [
[
'role' => 'system',
'content' => $systemPrompt,
],
...$history,
['role' => 'user', 'content' => $userContent],
];
$response = Http::timeout(60)
->withToken($this->apiKey)
->post("{$this->baseUrl}/chat/completions", [
'model' => 'gpt-4o',
'messages' => $messages,
'max_tokens' => 2048,
'temperature' => 0.7,
]);
if ($response->failed()) {
Log::error('TextGenerationService failed', ['body' => $response->body()]);
throw new \RuntimeException('Failed to generate text. Please try again.');
}
return data_get($response->json(), 'choices.0.message.content', '');
}
}

View file

@ -2,6 +2,8 @@
declare(strict_types=1);
use App\Ai\Agents\SocialMediaAssistant;
use App\Ai\Tools\AttachmentCollector;
use App\Enums\User\Setup;
use App\Enums\UserWorkspace\Role;
use App\Models\AiMessage;
@ -9,10 +11,6 @@
use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Ai\AudioGenerationService;
use App\Services\Ai\Contracts\TextGenerationInterface;
use App\Services\Ai\ImageGenerationService;
use App\Services\Ai\VideoGenerationService;
beforeEach(function () {
$this->user = User::factory()->create(['setup' => Setup::Completed]);
@ -25,8 +23,7 @@
'user_id' => $this->user->id,
]);
$this->mock(AudioGenerationService::class);
$this->mock(VideoGenerationService::class);
app(AttachmentCollector::class)->clear();
});
test('index returns ai messages for a post', function () {
@ -63,11 +60,8 @@
$response->assertForbidden();
});
test('store creates user and assistant messages for text intent', function () {
$this->mock(TextGenerationInterface::class)
->shouldReceive('generate')
->once()
->andReturn('Here is a great caption for your post!');
test('store creates user and assistant messages from agent response', function () {
SocialMediaAssistant::fake(['Here is a great caption for your post!']);
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
@ -93,16 +87,12 @@
]);
});
test('store creates user and assistant messages for image intent', function () {
$this->mock(TextGenerationInterface::class)
->shouldReceive('generate')
->once()
->andReturn('[GENERATE_IMAGE:vertical]');
test('store surfaces attachments pushed by tools into the AiMessage', function () {
// Simulate the agent invoking generate_image — it would push to collector.
$collector = app(AttachmentCollector::class);
$this->mock(ImageGenerationService::class)
->shouldReceive('generate')
->once()
->andReturn([
SocialMediaAssistant::fake(function () use ($collector) {
$collector->push([
'id' => 'test-media-id',
'path' => 'medias/test.png',
'url' => 'https://example.com/medias/test.png',
@ -110,16 +100,18 @@
'type' => 'image',
]);
return 'Generated a vertical image and attached it to the post.';
});
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
'body' => 'Generate an image of a sunset on the beach',
]);
$response->assertCreated();
$response->assertJsonPath('user_message.role', 'user');
$response->assertJsonPath('assistant_message.role', 'assistant');
$response->assertJsonPath('assistant_message.attachments.0.id', 'test-media-id');
$response->assertJsonPath('assistant_message.attachments.0.type', 'image');
$response->assertJsonPath('assistant_message.metadata.intent', 'image');
});
test('store validates body is required', function () {
@ -146,7 +138,7 @@
$response->assertForbidden();
});
test('store blocks prohibited content', function () {
test('store blocks prohibited content via IntentDetector', function () {
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
'body' => 'Create porn content for my post',
@ -161,11 +153,6 @@
'role' => 'user',
'content' => 'Create porn content for my post',
]);
$this->assertDatabaseHas('ai_messages', [
'post_id' => $this->post->id,
'role' => 'assistant',
]);
});
test('store blocks drug related content', function () {
@ -179,10 +166,7 @@
});
test('store allows safe content through', function () {
$this->mock(TextGenerationInterface::class)
->shouldReceive('generate')
->once()
->andReturn('Here is your caption!');
SocialMediaAssistant::fake(['Here is your caption!']);
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
@ -194,59 +178,10 @@
$response->assertJsonPath('assistant_message.metadata.intent', 'text');
});
test('store enforces image generation limit', function () {
$account = $this->workspace->account;
$this->mock(TextGenerationInterface::class)
->shouldReceive('generate')
->once()
->andReturn('[GENERATE_IMAGE:vertical]');
for ($i = 0; $i < 50; $i++) {
AiUsageLog::factory()->image()->create([
'account_id' => $account->id,
'workspace_id' => $this->workspace->id,
]);
}
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
'body' => 'Generate an image of a sunset',
]);
$response->assertCreated();
$response->assertJsonPath('assistant_message.metadata.limit_reached', true);
});
test('store enforces video generation limit', function () {
$account = $this->workspace->account;
$this->mock(TextGenerationInterface::class)
->shouldReceive('generate')
->once()
->andReturn('[GENERATE_VIDEO:vertical]');
for ($i = 0; $i < 10; $i++) {
AiUsageLog::factory()->video()->create([
'account_id' => $account->id,
'workspace_id' => $this->workspace->id,
]);
}
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
'body' => 'Create a video about coffee',
]);
$response->assertCreated();
$response->assertJsonPath('assistant_message.metadata.limit_reached', true);
});
test('store handles service exception gracefully', function () {
$this->mock(TextGenerationInterface::class)
->shouldReceive('generate')
->once()
->andThrow(new RuntimeException('API quota exceeded'));
test('store handles agent exception gracefully', function () {
SocialMediaAssistant::fake(function () {
throw new RuntimeException('API quota exceeded');
});
$response = $this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
@ -255,4 +190,40 @@
$response->assertCreated();
$response->assertJsonPath('assistant_message.content', 'API quota exceeded');
$response->assertJsonPath('assistant_message.metadata.error', true);
});
test('session state block reports current attachment count and remaining quota', function () {
// Seed existing attachments in the thread
AiMessage::factory()->create([
'post_id' => $this->post->id,
'role' => 'assistant',
'attachments' => [
['id' => 'm1', 'type' => 'image'],
['id' => 'm2', 'type' => 'image'],
],
]);
// Pre-existing monthly usage records
AiUsageLog::factory()->image()->count(2)->create([
'account_id' => $this->workspace->account_id,
'workspace_id' => $this->workspace->id,
]);
$capturedPrompt = null;
SocialMediaAssistant::fake(function ($prompt) use (&$capturedPrompt) {
$capturedPrompt = (string) $prompt;
return 'ok';
});
$this->actingAs($this->user)
->postJson(route('app.posts.assistant.store', $this->post), [
'body' => 'Write about coffee',
]);
expect($capturedPrompt)
->toContain('Session state')
->toContain('Images already generated in this conversation: 2')
->toContain('Monthly quota remaining:');
});