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.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Prevent duplicate imports of TryPost social posts (#394)
Paulo Castellano305b78f911cb
diff --git a/.ai/rules/post.md b/.ai/rules/post.mdindex 30e76d23f..1dcb773cd 100644--- a/.ai/rules/post.md+++ b/.ai/rules/post.md@@ -28,3 +28,9 @@ App\Actions\Post\ImportExternalPosts is the single path allowed to create Publis## PostApproval is the only approval gateEvery post write that can schedule, queue or publish passes the acting user to CreatePosts / UpdatePost so App\Support\PostApproval can store Status::PendingApproval. Do not gate in controllers, API or MCP tools, and do not pass an actor from system callers (ScheduleNextOccurrence), or approved recurring series start asking again. A pending queue request is never placed in the queue; ApprovePost replays it through UpdatePost as the approver. Appending media to a post (MCP/API attach) goes through AppendPostMedia, never Post::appendMedia directly from an entry point, so an approved post edited by a requester returns to approval. Approve, reject and any UpdatePost of a pending post run under PostApproval::whilePending (lock post-approval:{id}, re-entrant).++## Defer ambiguous captionless Instagram imports+When a captionless Instagram discovery has an unresolved TryPost candidate in the same channel, compatible content type and configured publication-time window, defer importing it without claiming either ID. Do not infer identity from empty captions or timestamps. The owner accepted that a genuine native post in that window may also wait. Exact-ID matches and provider-confirmed originals keep their normal behavior (2026-10-08).++## Instagram discovery can precede publish completion+Discovery can see a live Instagram post while PublishToSocialPlatform is still Publishing or Retrying after losing media_publish's response. Defer matching discoveries without assigning their IDs during that window too; Retrying requires an Instagram container checkpoint. Keep channel, content type, caption and time-window guards. Published-only matching leaves a duplicate-import race.diff --git a/app/Actions/Post/ImportExternalPosts.php b/app/Actions/Post/ImportExternalPosts.phpindex 563bb92c8..22e757c43 100644--- a/app/Actions/Post/ImportExternalPosts.php+++ b/app/Actions/Post/ImportExternalPosts.php@@ -18,7 +18,9 @@ use App\Models\PostPlatform;use App\Models\SocialAccount;use App\Services\Social\ContentSanitizer;use App\Support\PostHistoryRetention;+use App\Support\Social\PublishCheckpoint;use App\Support\Social\ThreadProgress;+use Carbon\CarbonImmutable;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Collection;use Illuminate\Support\Facades\Cache;@@ -148,10 +150,11 @@ class ImportExternalPostsprivate static function tryPostTarget(SocialAccount $account, AnalyticsPublication $publication): ?PostPlatform{- $remoteIds = array_values(array_filter([+ $remoteIds = collect([$publication->remote_id,$account->platform === Platform::Facebook ? data_get($publication->provider_metadata, 'video_id') : null,- ], fn (mixed $id): bool => is_string($id) && $id !== ''));+ $account->platform === Platform::Facebook ? data_get($publication->provider_metadata, 'photo_id') : null,+ ])->filter(fn (mixed $id): bool => is_string($id) && filled($id))->values()->all();return PostPlatform::query()->where('social_account_id', $account->id)@@ -181,22 +184,25 @@ class ImportExternalPosts* back (an Instagram container id, a TikTok publish_id). The one sent post* from this channel with the same text near the same time is that* publication: it takes over the remote id instead of a duplicate import.- * More than one such post is ambiguous, so the publication waits.+ * Multiple candidates, captionless Instagram posts and Instagram publishes+ * still in progress wait without claiming a remote id.*/private static function claimedBySentPost(SocialAccount $account, AnalyticsPublication $publication): bool{- $targets = self::sentPostsMatching($account, $publication);+ $targets = self::matchingTryPostTargets($account, $publication);if ($targets->isEmpty()) {return false;}- if ($targets->count() > 1) {+ if ($targets->count() > 1+ || blank(Str::squish((string) $publication->excerpt))+ || $targets->contains(fn (PostPlatform $target): bool => $target->status !== PostPlatformStatus::Published)) {if (! Cache::add("import-external-posts:ambiguous:{$publication->id}", true, now()->addDay())) {return true;}- Log::warning('External publication matches more than one TryPost post; not imported.', [+ Log::warning('External publication identity is ambiguous; not imported.', ['analytics_publication_id' => $publication->id,'post_platform_ids' => $targets->modelKeys(),]);@@ -224,12 +230,12 @@ class ImportExternalPosts/*** @return Collection<int, PostPlatform>*/- private static function sentPostsMatching(SocialAccount $account, AnalyticsPublication $publication): Collection+ private static function matchingTryPostTargets(SocialAccount $account, AnalyticsPublication $publication): Collection{$window = (int) config('trypost.external_posts.match_window_minutes');$text = Str::squish((string) $publication->excerpt);- if ($window < 1 || $text === '' || ! in_array($account->platform, self::PROVISIONAL_ID_PLATFORMS, true)) {+ if ($window < 1 || ! in_array($account->platform, self::PROVISIONAL_ID_PLATFORMS, true)) {return new Collection;}@@ -238,9 +244,8 @@ class ImportExternalPostsreturn PostPlatform::query()->where('social_account_id', $account->id)->enabled()- ->published()+ ->where(fn (Builder $query): Builder => self::matchingPublicationState($query, $account->platform, $publishedAt, $window))->whereIn('content_type', self::compatibleContentTypes(ContentType::fromPublication($account->platform, $publication->content_type)))- ->whereBetween('published_at', [$publishedAt->subMinutes($window), $publishedAt->addMinutes($window)])->whereHas('post', fn (Builder $post): Builder => $post->createdInTryPost()->where('workspace_id', $account->workspace_id))->where(fn (Builder $query): Builder => $query->whereDoesntHave('analyticsPublication')@@ -250,13 +255,37 @@ class ImportExternalPosts->whereColumn('analytics_publications.remote_id', 'post_platforms.platform_post_id')))->with(['post:id,content', 'analyticsPublication'])->get()- ->filter(fn (PostPlatform $target): bool => self::sameText((string) $target->post?->content, $text, $account->platform))+ ->filter(fn (PostPlatform $target): bool => self::sameText(+ $target->content_type->isCaptionless() ? '' : (string) $target->post?->content,+ $text,+ $account->platform,+ ))->values();}+ private static function matchingPublicationState(Builder $query, Platform $platform, CarbonImmutable $publishedAt, int $window): Builder+ {+ $interval = [$publishedAt->subMinutes($window), $publishedAt->addMinutes($window)];++ $query->where(fn (Builder $sent): Builder => $sent->published()->whereBetween('published_at', $interval));++ if (! in_array($platform, [Platform::Instagram, Platform::InstagramFacebook], true)) {+ return $query;+ }++ return $query->orWhere(fn (Builder $pending): Builder => $pending+ ->whereBetween('updated_at', $interval)+ ->where(fn (Builder $state): Builder => $state+ ->where('status', PostPlatformStatus::Publishing)+ ->orWhere(fn (Builder $retry): Builder => $retry+ ->where('status', PostPlatformStatus::Retrying)+ ->whereNotNull('error_context->'.PublishCheckpoint::INSTAGRAM_WORKFLOW.'->container_id'))));+ }+/*** Instagram reports a feed video TryPost published as a reel, so feed and* reel stand in for each other; a story only ever matches a story.+ * TikTok's video/list also returns photo posts without a media type.** @return list<ContentType>*/@@ -264,6 +293,7 @@ class ImportExternalPosts{return match ($type) {ContentType::InstagramFeed, ContentType::InstagramReel => [ContentType::InstagramFeed, ContentType::InstagramReel],+ ContentType::TikTokVideo => [ContentType::TikTokVideo, ContentType::TikTokPhoto],default => [$type],};}@@ -271,24 +301,25 @@ class ImportExternalPosts/*** Equal text, or a network excerpt that visibly ends in an ellipsis and* still carries enough of the caption to tell posts apart.+ * Empty Instagram captions are candidates for deferral only.*/private static function sameText(string $content, string $text, Platform $platform): bool{$sent = Str::squish(app(ContentSanitizer::class)->displayText($content, $platform));- if ($sent === '') {- return false;+ if (blank($sent)) {+ return blank($text) && in_array($platform, [Platform::Instagram, Platform::InstagramFacebook], true);}if ($sent === $text) {return true;}- $truncated = trim((string) preg_replace('/(?:\.\.\.|…)$/u', '', $text));+ $truncated = (string) Str::of($text)->chopEnd(['...', '…'])->trim();return $truncated !== $text- && mb_strlen($truncated) >= self::MIN_TRUNCATED_MATCH_LENGTH- && str_starts_with($sent, $truncated);+ && Str::length($truncated) >= self::MIN_TRUNCATED_MATCH_LENGTH+ && Str::startsWith($sent, $truncated);}private static function createPost(SocialAccount $account, AnalyticsPublication $publication): PostPlatformdiff --git a/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.phpindex a6620bf3d..6c8fa70ef 100644--- a/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php@@ -55,6 +55,7 @@ class FacebookPublicationCollector extends AbstractMetaPublicationCollector$permalink = data_get($row, 'permalink_url');$videoId = $this->isVideo($attachment) ? data_get($attachment, 'target.id') : null;+ $photoId = $this->isSinglePhotoPost($row, $attachment) ? data_get($attachment, 'target.id') : null;if (filled($videoId)) {$hydrated = $this->hydratePreview($account, (string) $videoId);@@ -70,7 +71,11 @@ class FacebookPublicationCollector extends AbstractMetaPublicationCollectorpermalink: $permalink,excerpt: data_get($row, 'message'),previewMetadata: $this->preview($previewUrl),- providerMetadata: filled($videoId) ? ['video_id' => (string) $videoId] : null,+ providerMetadata: match (true) {+ filled($videoId) => ['video_id' => (string) $videoId],+ filled($photoId) => ['photo_id' => (string) $photoId],+ default => null,+ },);}@@ -101,6 +106,17 @@ class FacebookPublicationCollector extends AbstractMetaPublicationCollectorreturn in_array($this->contentType($attachment), [PublicationContentType::Video, PublicationContentType::Reel], true);}+ /**+ * @param array<string, mixed> $row+ * @param array<string, mixed> $attachment+ */+ private function isSinglePhotoPost(array $row, array $attachment): bool+ {+ return data_get($row, 'status_type') === 'added_photos'+ && $this->contentType($attachment) === PublicationContentType::Image+ && blank(data_get($attachment, 'subattachments.data'));+ }+/** @return array<string, mixed> */private function hydratePreview(SocialAccount $account, string $videoId): array{diff --git a/app/Services/Social/ThreadsPublisher.php b/app/Services/Social/ThreadsPublisher.phpindex cfb2254f2..e2c4eddbf 100644--- a/app/Services/Social/ThreadsPublisher.php+++ b/app/Services/Social/ThreadsPublisher.php@@ -12,6 +12,7 @@ use App\Exceptions\Social\ThreadsPublishException;use App\Models\PostPlatform;use App\Services\Social\Concerns\HasSocialHttpClient;use App\Support\PostPlatformMetaRules;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Log;use Illuminate\Support\Sleep;@@ -351,22 +352,28 @@ class ThreadsPublisher$this->handleApiError($publishResponse);}- $mediaId = $publishResponse->json()['id'] ?? null;+ $mediaId = (string) $publishResponse->json('id');- if (! $mediaId) {+ if (blank($mediaId)) {throw new ThreadsPublishException(userMessage: 'Threads did not accept the post. Please publish again.',category: ErrorCategory::ServerError,);}- // Get permalink- $permalinkResponse = $this->socialHttp()->get("{$this->baseUrl}/{$mediaId}", [- 'fields' => 'permalink',- 'access_token' => $accessToken,- ]);+ try {+ $permalinkResponse = $this->socialHttp()->get("{$this->baseUrl}/{$mediaId}", [+ 'fields' => 'permalink',+ 'access_token' => $accessToken,+ ]);+ } catch (ConnectionException) {+ return [+ 'id' => $mediaId,+ 'url' => null,+ ];+ }- $permalink = $permalinkResponse->json()['permalink'] ?? null;+ $permalink = $permalinkResponse->json('permalink');return ['id' => $mediaId,diff --git a/app/Services/Social/TikTokPublisher.php b/app/Services/Social/TikTokPublisher.phpindex c0cd6650e..ced328f5e 100644--- a/app/Services/Social/TikTokPublisher.php+++ b/app/Services/Social/TikTokPublisher.php@@ -483,10 +483,9 @@ class TikTokPublisherprivate function completePublish(PostPlatform $postPlatform, string $publishId): array{$statusData = $this->waitForPublishStatus($publishId);- $postId = data_get($statusData, 'publicaly_available_post_id.0');- $postId = is_string($postId) && $postId !== '' ? $postId : null;+ $postId = (string) data_get($statusData, 'publicaly_available_post_id.0');- if ($postId === null) {+ if (blank($postId)) {$postId = app(TikTokAnalytics::class)->findVideoIdByCaption($postPlatform);}diff --git a/tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.phpindex c0318f955..9a458fb77 100644--- a/tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php@@ -139,6 +139,36 @@ test('facebook reads page-owned published posts and keeps a video when preview hHttp::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/feed'));});+test('facebook only keeps photo identity for a single photo attachment', function (array $attachment, ?array $metadata, string $statusType = 'added_photos') {+ Http::fake(['*/published_posts*' => Http::response(['data' => [[+ 'id' => 'page_post-1',+ 'status_type' => $statusType,+ 'created_time' => '2026-09-20T12:00:00+0000',+ 'attachments' => ['data' => [$attachment]],+ ]]])]);+ $account = SocialAccount::factory()->facebook()->create();++ $page = app(FacebookPublicationCollector::class)->page($account, null, CarbonImmutable::parse('2026-01-01', 'UTC'));++ expect($page->publications[0]->providerMetadata)->toBe($metadata);+ Http::assertSentCount(1);+})->with([+ 'photo' => [['media_type' => 'photo', 'target' => ['id' => 'photo-1']], ['photo_id' => 'photo-1']],+ 'missing photo id' => [['media_type' => 'photo'], null],+ 'shared photo' => [['media_type' => 'photo', 'target' => ['id' => 'photo-1']], null, 'shared_story'],+ 'link target' => [['media_type' => 'link', 'type' => 'share', 'target' => ['id' => 'photo-1']], null],+ 'album with one visible photo' => [[+ 'media_type' => 'photo',+ 'target' => ['id' => 'album-1'],+ 'subattachments' => ['data' => [['target' => ['id' => 'photo-1']]]],+ ], null],+ 'album target' => [[+ 'media_type' => 'photo',+ 'target' => ['id' => 'album-1'],+ 'subattachments' => ['data' => [['target' => ['id' => 'photo-1']], ['target' => ['id' => 'photo-2']]]],+ ], null],+]);+test('threads reads one owned post page and returns its cursor', function () {Http::fake(['*' => Http::response(['data' => [[diff --git a/tests/Feature/Jobs/SocialPublishingPipelineTest.php b/tests/Feature/Jobs/SocialPublishingPipelineTest.phpindex 1ed08e74a..eae68e05c 100644--- a/tests/Feature/Jobs/SocialPublishingPipelineTest.php+++ b/tests/Feature/Jobs/SocialPublishingPipelineTest.php@@ -2,6 +2,8 @@declare(strict_types=1);+use App\Actions\Analytics\UpsertAnalyticsPublication;+use App\Actions\Post\ImportExternalPosts;use App\Enums\Post\Status as PostStatus;use App\Enums\PostPlatform\ContentType;use App\Enums\PostPlatform\Status as PlatformStatus;@@ -15,6 +17,9 @@ use App\Models\Media;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;+use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;+use App\Services\Analytics\Collectors\Publications\InstagramPublicationCollector;+use App\Services\Analytics\Collectors\Publications\ThreadsPublicationCollector;use App\Services\Social\BlueskyPublisher;use App\Services\Social\Discord\DiscordPublisher;use App\Services\Social\FacebookPublisher;@@ -36,6 +41,7 @@ use Illuminate\Support\Facades\Exceptions;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Str;beforeEach(function () {$this->freezeTime();@@ -83,6 +89,135 @@ function scheduledPipelineTarget(Platform $platform): PostPlatform]);}+test('a published facebook photo is not imported again when publishing returned only the photo id', function () {+ $target = scheduledPipelineTarget(Platform::Facebook);+ $account = $target->socialAccount;+ $account->update(['scopes' => [...$account->scopes, 'pages_read_engagement']]);+ $media = Media::factory()->ownedByPost($target->post)->stored()->create(['size' => 100000]);+ $target->post->update(['media' => [$media->toArray()]]);+ $base = config('trypost.platforms.facebook.graph_api');++ Http::fake([+ "{$base}/{$account->platform_user_id}/photos" => Http::response(['id' => 'photo-123']),+ "{$base}/{$account->platform_user_id}/published_posts*" => Http::response(['data' => [[+ 'id' => 'page_post-123',+ 'status_type' => 'added_photos',+ 'message' => $target->post->content,+ 'created_time' => now()->toIso8601String(),+ 'attachments' => ['data' => [[+ 'type' => 'photo',+ 'media_type' => 'photo',+ 'target' => ['id' => 'photo-123'],+ ]]],+ ]]]),+ ]);++ (new PublishToSocialPlatform($target))->handle();++ expect($target->refresh()->status)->toBe(PlatformStatus::Published)+ ->and($target->platform_post_id)->toBe('photo-123');++ $page = app(FacebookPublicationCollector::class)->page($account, null, now()->subDay()->toImmutable());+ app(UpsertAnalyticsPublication::class)->external($account, $page->publications[0]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($target->post->refresh()->status)->toBe(PostStatus::Published);+ Http::assertSentCount(2);+ Exceptions::assertNothingReported();+});++test('a published threads post keeps its identity through a failed permalink lookup and later import', function () {+ $target = scheduledPipelineTarget(Platform::Threads);+ $account = $target->socialAccount;+ $account->update(['scopes' => [...$account->scopes, 'threads_basic']]);+ $base = config('trypost.platforms.threads.graph_api');++ Http::fake([+ "{$base}/{$account->platform_user_id}/threads" => Http::response(['id' => 'container-123']),+ "{$base}/container-123*" => Http::response(['status' => 'FINISHED']),+ "{$base}/{$account->platform_user_id}/threads_publish" => Http::response(['id' => 'post-123']),+ "{$base}/post-123*" => Http::failedConnection('Permalink connection lost'),+ "{$base}/{$account->platform_user_id}/threads?*" => Http::response(['data' => [[+ 'id' => 'post-123',+ 'media_type' => 'TEXT_POST',+ 'text' => $target->post->content,+ 'timestamp' => now()->toIso8601String(),+ ]]]),+ ]);++ (new PublishToSocialPlatform($target))->handle();++ expect($target->refresh()->status)->toBe(PlatformStatus::Published)+ ->and($target->platform_post_id)->toBe('post-123')+ ->and($target->platform_url)->toBeNull();++ $page = app(ThreadsPublicationCollector::class)->page($account, null, now()->subDay()->toImmutable());+ app(UpsertAnalyticsPublication::class)->external($account, $page->publications[0]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($target->post->refresh()->status)->toBe(PostStatus::Published);+ expect(Http::recorded(fn (Request $request): bool => $request->method() === 'POST'+ && Str::endsWith($request->url(), '/threads_publish')))->toHaveCount(1);+ Exceptions::assertNothingReported();+});++test('instagram does not duplicate a captionless publication after losing its media id', function (Platform $platform, ContentType $contentType) {+ $target = scheduledPipelineTarget($platform);+ $target->post->update(['content' => '']);+ $target->update([+ 'content_type' => $contentType,+ 'error_context' => ['instagram_workflow' => [+ 'stage' => 'final_container',+ 'container_id' => 'container-123',+ ]],+ ]);+ $account = $target->socialAccount;+ $account->update(['scopes' => [...$account->scopes, 'instagram_basic', 'instagram_business_basic']]);+ $base = $platform->instagramGraphBaseUrl();+ $story = $contentType === ContentType::InstagramStory;+ $discovered = [[+ 'id' => 'media-123',+ 'media_type' => 'IMAGE',+ 'timestamp' => now()->toIso8601String(),+ ]];++ Http::fake([+ "{$base}/container-123*" => Http::sequence()+ ->push(['status_code' => 'FINISHED'])+ ->push(['status_code' => 'PUBLISHED']),+ "{$base}/{$account->platform_user_id}/media_publish" => Http::failedConnection('Publish response lost'),+ "{$base}/{$account->platform_user_id}/media?*" => Http::response(['data' => $story ? [] : $discovered]),+ "{$base}/{$account->platform_user_id}/stories?*" => Http::response(['data' => $story ? $discovered : []]),+ ]);++ (new PublishToSocialPlatform($target))->handle();+ expect($target->refresh()->status)->toBe(PlatformStatus::Retrying);++ $page = app(InstagramPublicationCollector::class)->page($account, null, now()->subDay()->toImmutable());+ expect($page->publications)->toHaveCount(1);+ $publication = app(UpsertAnalyticsPublication::class)->external($account, $page->publications[0]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and($publication->refresh()->post_platform_id)->toBeNull();++ $this->travel(61)->seconds();+ (new PublishToSocialPlatform($target))->handle();+ expect($target->refresh()->status)->toBe(PlatformStatus::Published)+ ->and($target->platform_post_id)->toBe('container-123');++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($publication->refresh()->post_platform_id)->toBeNull()+ ->and($target->refresh()->platform_post_id)->toBe('container-123');+})->with([+ 'Instagram feed' => [Platform::Instagram, ContentType::InstagramFeed],+ 'Instagram story' => [Platform::Instagram, ContentType::InstagramStory],+ 'Instagram Facebook feed' => [Platform::InstagramFacebook, ContentType::InstagramFeed],+ 'Instagram Facebook story' => [Platform::InstagramFacebook, ContentType::InstagramStory],+]);+test('each network queue consumes scheduled posts and delayed retries through the worker', function (Platform $platform, string $publisherClass) {$retrying = scheduledPipelineTarget($platform);$broken = scheduledPipelineTarget($platform);diff --git a/tests/Feature/Posts/ImportExternalPostsTest.php b/tests/Feature/Posts/ImportExternalPostsTest.phpindex bac9d2de8..d1b0dc703 100644--- a/tests/Feature/Posts/ImportExternalPostsTest.php+++ b/tests/Feature/Posts/ImportExternalPostsTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Actions\Analytics\UpsertAnalyticsPublication;use App\Actions\Post\ImportExternalPosts;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;@@ -18,11 +19,13 @@ use App\Models\AnalyticsPublication;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;+use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;use App\Support\Social\ThreadProgress;use Carbon\CarbonImmutable;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Exceptions;+use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Queue;@@ -231,6 +234,43 @@ test('a facebook video already tracked by its trypost publication is left unlink->and($external->fresh()->post_platform_id)->toBeNull();});+test('a facebook photo discovered under its feed post id does not duplicate the original', function (bool $tracked) {+ $account = SocialAccount::factory()->facebook()->create();+ $original = sentByTryPost($account, 'photo-9', 'Our photo', now()->subHour()->toImmutable());++ if ($tracked) {+ externalPublication($account, [+ 'remote_id' => 'photo-9',+ 'post_platform_id' => $original->id,+ 'origin' => PublicationOrigin::TryPost,+ ]);+ }++ Http::fake([+ '*/published_posts*' => Http::response(['data' => [[+ 'id' => 'page_post-1',+ 'message' => 'Our photo',+ 'status_type' => 'added_photos',+ 'created_time' => now()->subHour()->toIso8601String(),+ 'attachments' => ['data' => [[+ 'media_type' => 'photo',+ 'type' => 'photo',+ 'target' => ['id' => 'photo-9'],+ ]]],+ ]]]),+ ]);++ $page = app(FacebookPublicationCollector::class)->page($account, null, now()->subDay()->toImmutable());+ $publication = app(UpsertAnalyticsPublication::class)->external($account, $page->publications[0]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($publication->fresh()->post_platform_id)->toBe($tracked ? null : $original->id);++ Http::assertSentCount(1);+})->with(['untracked original' => false, 'tracked original' => true]);+test('importing fires no post events and queues nothing', function () {Event::fake([PostCreated::class, PostStatusChanged::class]);$account = SocialAccount::factory()->instagram()->create();@@ -333,11 +373,19 @@ test('an instagram post trypost published under its container id is linked inste->and($tryPost->fresh()->platform_url)->toBe('https://www.instagram.com/p/media-1/');});-test('a tiktok post still keyed by its publish id is reconciled into the discovered video', function () {+test('a tiktok post still keyed by its publish id is reconciled into the discovered video', function (ContentType $contentType, string $publishId, string $ellipsis) {$account = SocialAccount::factory()->tiktok()->create();- $tryPost = sentByTryPost($account, 'v_pub_url~123', '<p>A long description that the network cuts short</p>', now()->subHour()->toImmutable());+ $tryPost = sentByTryPost($account, $publishId, '<p>A long description that the network cuts short</p>', now()->subHour()->toImmutable(), $contentType);+ $media = $contentType === ContentType::TikTokPhoto+ ? collect(range(1, 4))->map(fn (int $index): array => [+ 'id' => "photo-{$index}",+ 'url' => "https://cdn.example/photo-{$index}.jpg",+ 'mime_type' => 'image/jpeg',+ ])->all()+ : [['id' => 'video-1', 'url' => 'https://cdn.example/video.mp4', 'mime_type' => 'video/mp4']];+ $tryPost->post->update(['media' => $media]);$provisional = externalPublication($account, [- 'remote_id' => 'v_pub_url~123',+ 'remote_id' => $publishId,'post_platform_id' => $tryPost->id,'origin' => PublicationOrigin::TryPost,'provider_synced_at' => null,@@ -346,19 +394,29 @@ test('a tiktok post still keyed by its publish id is reconciled into the discove$discovered = externalPublication($account, ['remote_id' => '7300000000000000001','permalink' => 'https://www.tiktok.com/@trypost/video/7300000000000000001',- 'excerpt' => 'A long description that the network…',+ 'excerpt' => 'A long description that the network'.$ellipsis,'content_type' => PublicationContentType::Video,'provider_published_at' => now()->subHour()->addMinutes(5),]);- expect(ImportExternalPosts::execute($account))->toBe([])- ->and(Post::query()->imported()->count())->toBe(0)- ->and(AnalyticsPublication::query()->find($discovered->id))->toBeNull()- ->and($provisional->fresh()->remote_id)->toBe('7300000000000000001')- ->and($provisional->fresh()->post_platform_id)->toBe($tryPost->id)- ->and($tryPost->fresh()->platform_post_id)->toBe('7300000000000000001')- ->and($tryPost->fresh()->platform_url)->toBe('https://www.tiktok.com/@trypost/video/7300000000000000001');-});+ expect(ImportExternalPosts::execute($account))->toBe([]);++ $tryPost->refresh();+ $provisional->refresh();++ $this->assertModelMissing($discovered);++ expect(Post::query()->imported()->count())->toBe(0)+ ->and($provisional->remote_id)->toBe('7300000000000000001')+ ->and($provisional->post_platform_id)->toBe($tryPost->id)+ ->and($tryPost->content_type)->toBe($contentType)+ ->and($tryPost->post->media)->toEqual($media)+ ->and($tryPost->platform_post_id)->toBe('7300000000000000001')+ ->and($tryPost->platform_url)->toBe('https://www.tiktok.com/@trypost/video/7300000000000000001');+})->with([+ 'video' => [ContentType::TikTokVideo, 'v_pub_url~123'],+ 'photo carousel' => [ContentType::TikTokPhoto, 'p_pub_url~123'],+])->with(['three dots' => '...', 'unicode ellipsis' => '…']);test('a trypost target whose id the network already confirmed is never relinked by text', function () {$account = SocialAccount::factory()->instagram()->create();@@ -387,6 +445,26 @@ test('two trypost posts matching the same publication link neither and import noLog::shouldHaveReceived('warning')->once();});+test('a tiktok discovery matching both a photo and video waits instead of claiming either', function () {+ Log::spy();+ $account = SocialAccount::factory()->tiktok()->create();+ $photo = sentByTryPost($account, 'p_pub_url~123', 'Same caption', now()->subHour()->toImmutable(), ContentType::TikTokPhoto);+ $video = sentByTryPost($account, 'v_pub_url~123', 'Same caption', now()->subHour()->toImmutable(), ContentType::TikTokVideo);+ $publication = externalPublication($account, [+ 'remote_id' => '7694308097568836885',+ 'excerpt' => 'Same caption',+ 'content_type' => PublicationContentType::Video,+ 'provider_published_at' => now()->subHour(),+ ]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($publication->fresh()->post_platform_id)->toBeNull()+ ->and($photo->fresh()->platform_post_id)->toBe('p_pub_url~123')+ ->and($video->fresh()->platform_post_id)->toBe('v_pub_url~123');+ Log::shouldHaveReceived('warning')->once();+});+test('a trypost post outside the match window is not linked by text', function () {config()->set('trypost.external_posts.match_window_minutes', 120);$account = SocialAccount::factory()->instagram()->create();@@ -421,17 +499,114 @@ test('a caption-less trypost story is never taken over by a caption-less native->and($story->fresh()->platform_post_id)->toBe('story-container');});-test('two caption-less feed posts are not matched by their empty text', function () {+test('captionless instagram discoveries wait without claiming an unresolved post', function (?string $excerpt) {$account = SocialAccount::factory()->instagram()->create();$tryPost = sentByTryPost($account, 'container-1', '', now()->subHour()->toImmutable());- externalPublication($account, ['remote_id' => 'media-1', 'excerpt' => null, 'provider_published_at' => now()->subHour()]);+ $publication = externalPublication($account, ['remote_id' => 'media-1', 'excerpt' => $excerpt, 'provider_published_at' => now()->subHour()]);- ImportExternalPosts::execute($account);-- expect(Post::query()->imported()->count())->toBe(1)+ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($publication->refresh()->post_platform_id)->toBeNull()+ ->and($publication->post_dismissed_at)->toBeNull()->and($tryPost->fresh()->platform_post_id)->toBe('container-1');+})->with([null, '', ' ', "\u{00A0}"]);++test('a captionless discovery imports once the other instagram post has a confirmed identity', function () {+ $account = SocialAccount::factory()->instagram()->create();+ $original = sentByTryPost($account, 'media-ours', '', now()->subHour()->toImmutable());+ $tracked = externalPublication($account, [+ 'remote_id' => 'media-ours',+ 'post_platform_id' => $original->id,+ 'origin' => PublicationOrigin::TryPost,+ 'provider_synced_at' => null,+ ]);+ $native = externalPublication($account, ['remote_id' => 'media-native', 'excerpt' => null, 'provider_published_at' => now()->subHour()]);++ expect(ImportExternalPosts::execute($account))->toBe([]);++ $tracked->update(['provider_synced_at' => now()]);++ expect(ImportExternalPosts::execute($account))->toHaveCount(1)+ ->and(Post::query()->imported()->count())->toBe(1)+ ->and($native->fresh()->post_platform_id)->not->toBe($original->id)+ ->and($original->fresh()->platform_post_id)->toBe('media-ours');+});++test('captionless instagram deferral stays within the channel and time window', function (string $difference) {+ $account = SocialAccount::factory()->instagram()->create();+ $originalAccount = $difference === 'channel'+ ? SocialAccount::factory()->instagram()->create(['workspace_id' => $account->workspace_id])+ : $account;+ sentByTryPost($originalAccount, 'container-1', '', now()->subHour()->toImmutable());+ externalPublication($account, [+ 'remote_id' => 'media-1',+ 'excerpt' => null,+ 'provider_published_at' => $difference === 'time' ? now()->subHours(4) : now()->subHour(),+ ]);++ expect(ImportExternalPosts::execute($account))->toHaveCount(1)+ ->and(Post::query()->imported()->count())->toBe(1);+})->with(['channel', 'time']);++test('a captionless instagram discovery still links by its exact public id', function () {+ $account = SocialAccount::factory()->instagram()->create();+ $original = sentByTryPost($account, 'media-1', '', now()->subHour()->toImmutable());+ $publication = externalPublication($account, ['remote_id' => 'media-1', 'excerpt' => null, 'provider_published_at' => now()->subHour()]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($publication->fresh()->post_platform_id)->toBe($original->id);});+test('instagram discoveries wait for an in-flight publication without claiming its id', function (PostPlatformStatus $status, string $caption) {+ $account = SocialAccount::factory()->instagram()->create();+ $target = sentByTryPost($account, 'container-1', $caption, now()->toImmutable());+ $target->update([+ 'status' => $status,+ 'platform_post_id' => null,+ 'published_at' => null,+ 'error_context' => $status === PostPlatformStatus::Retrying+ ? ['instagram_workflow' => ['stage' => 'final_container', 'container_id' => 'container-1']]+ : null,+ ]);+ $publication = externalPublication($account, ['remote_id' => 'media-1', 'excerpt' => $caption, 'provider_published_at' => now()]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and($publication->refresh()->post_platform_id)->toBeNull()+ ->and($target->refresh()->platform_post_id)->toBeNull()+ ->and($target->status)->toBe($status);++ $target->update(['status' => PostPlatformStatus::Failed]);++ expect(ImportExternalPosts::execute($account))->toHaveCount(1)+ ->and($publication->refresh()->post_platform_id)->not->toBe($target->id);+})->with([PostPlatformStatus::Publishing, PostPlatformStatus::Retrying])->with(['', 'Our caption']);++test('an unrelated pending instagram target does not hold a native import', function (string $difference) {+ $account = SocialAccount::factory()->instagram()->create();+ $targetAccount = $difference === 'channel'+ ? SocialAccount::factory()->instagram()->create(['workspace_id' => $account->workspace_id])+ : $account;+ $target = sentByTryPost($targetAccount, 'container-1', '', now()->toImmutable());+ $target->update([+ 'status' => $difference === 'draft' ? PostPlatformStatus::Pending : PostPlatformStatus::Retrying,+ 'enabled' => $difference !== 'disabled',+ 'content_type' => $difference === 'type' ? ContentType::InstagramStory : ContentType::InstagramFeed,+ 'platform_post_id' => null,+ 'published_at' => null,+ 'error_context' => $difference === 'no container' ? null : ['instagram_workflow' => ['container_id' => 'container-1']],+ ]);+ externalPublication($account, [+ 'remote_id' => 'media-1',+ 'excerpt' => null,+ 'provider_published_at' => $difference === 'time' ? now()->subHours(4) : now(),+ ]);++ expect(ImportExternalPosts::execute($account))->toHaveCount(1)+ ->and($target->fresh()->platform_post_id)->toBeNull();+})->with(['channel', 'time', 'type', 'disabled', 'draft', 'no container']);+test('a trypost story is not taken over by a native feed post with the same caption', function () {$account = SocialAccount::factory()->instagram()->create();$story = sentByTryPost($account, 'story-container', 'Same caption', now()->subHour()->toImmutable(), ContentType::InstagramStory);diff --git a/tests/Feature/Services/Social/ThreadsPublisherTest.php b/tests/Feature/Services/Social/ThreadsPublisherTest.phpindex 5ec42b75f..ba79eb94f 100644--- a/tests/Feature/Services/Social/ThreadsPublisherTest.php+++ b/tests/Feature/Services/Social/ThreadsPublisherTest.php@@ -16,6 +16,7 @@ use App\Services\Social\ThreadsPublisher;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;use Illuminate\Support\Sleep;+use Illuminate\Support\Str;beforeEach(function () {Sleep::fake();@@ -75,6 +76,29 @@ test('threads publisher can publish text-only post', function () {});});+test('threads publisher keeps the published id when the permalink lookup fails', function (string $failure) {+ $base = config('trypost.platforms.threads.graph_api');++ Http::fake([+ "{$base}/123456789/threads" => Http::response(['id' => 'container-123']),+ "{$base}/container-123*" => Http::response(['status' => 'FINISHED']),+ "{$base}/123456789/threads_publish" => Http::response(['id' => 'post-123']),+ "{$base}/post-123*" => match ($failure) {+ 'connection' => Http::failedConnection(),+ 'http' => Http::response(['error' => ['message' => 'Unavailable']], 500),+ 'missing link' => Http::response([]),+ },+ ]);++ expect($this->publisher->publish($this->postPlatform))->toBe([+ 'id' => 'post-123',+ 'url' => null,+ ]);++ expect(Http::recorded(fn ($request): bool => $request->method() === 'POST'+ && Str::endsWith($request->url(), '/threads_publish')))->toHaveCount(1);+})->with(['connection', 'http', 'missing link']);+test('threads publisher can publish image post', function () {$this->post->update(['media' => [diff --git a/tests/Feature/Services/Social/TikTokPublisherTest.php b/tests/Feature/Services/Social/TikTokPublisherTest.phpindex 83706dcb9..f1b5d1f05 100644--- a/tests/Feature/Services/Social/TikTokPublisherTest.php+++ b/tests/Feature/Services/Social/TikTokPublisherTest.php@@ -89,7 +89,29 @@ test('tiktok publisher can publish video', function () {});});-test('tiktok publisher persists the public video url when status omits the post id', function () {+test('tiktok publisher keeps the public post id returned as an integer or string', function (int|string $postId) {+ $this->postPlatform->update(['error_context' => ['tiktok_publish_id' => 'p_pub_url~123']]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'data' => [+ 'status' => 'PUBLISH_COMPLETE',+ 'publicaly_available_post_id' => [$postId],+ ],+ ]),+ ]);++ $result = $this->publisher->publish($this->postPlatform->fresh());++ expect($result['id'])->toBe('7694308097568836885')+ ->and($result['url'])->toBe('https://www.tiktok.com/@tiktoker/video/7694308097568836885');+ Http::assertSentCount(1);+})->with([+ 'integer id' => 7694308097568836885,+ 'string id' => '7694308097568836885',+]);++test('tiktok publisher persists the public video url when status omits the post id', function (array $statusData) {$this->post->update(['content' => 'Construam produtos globais e faturem em dólar.','media' => [[@@ -109,7 +131,7 @@ test('tiktok publisher persists the public video url when status omits the post$this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PUBLISH_COMPLETE',- 'publicaly_available_post_id' => [],+ ...$statusData,],], 200),$this->api.'/video/list/*' => Http::response([@@ -129,7 +151,13 @@ test('tiktok publisher persists the public video url when status omits the postexpect($result['id'])->toBe('7682891910226234644')->and($result['url'])->toBe('https://www.tiktok.com/@tiktoker/video/7682891910226234644');-});+})->with([+ 'empty list' => [['publicaly_available_post_id' => []]],+ 'missing field' => [[]],+ 'null id' => [['publicaly_available_post_id' => [null]]],+ 'empty id' => [['publicaly_available_post_id' => ['']]],+ 'blank id' => [['publicaly_available_post_id' => [' ']]],+]);test('tiktok publisher does not report success before processing completes', function () {$this->post->update([