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
Wait for TikTok to confirm a publish before failing it (#443)
Paulo Castellano18252b4372ed
diff --git a/.ai/rules/tiktok.md b/.ai/rules/tiktok.mdindex ba6e2cfcb..4afff9fe0 100644--- a/.ai/rules/tiktok.md+++ b/.ai/rules/tiktok.md@@ -10,3 +10,6 @@ paths:## TikTok video ids come only from the status fetchNever infer a TikTok post's video id from video/list (caption prefix, create_time window): it handed each post of a same-caption series the previous post's video (17 posts, October 2026). TikTok reports `publicaly_available_post_id` only after moderation (minutes to hours, seen weeks later); until then the post keeps its publish_id and the profile url. `PublishToSocialPlatform` dispatches `ResolveTikTokVideoId` (through `TikTokPublisher::publicVideoId()`) a minute after the publish; `social:resolve-tiktok-video-ids` (every 15 minutes) asks again for slower reviews, for 30 days. The resolver and the metrics job write the id through `AssignTikTokVideoId`, which also moves the analytics publication. The only other writer is `ImportExternalPosts::claimedBySentPost` (exact text, single candidate in the match window, deferred when ambiguous); for TikTok it only claims for a post without a numeric video id (still on its publish_id, or released by the one-off repair run in October 2026), never one whose numeric id TikTok already reported. Only posts public to everyone are asked: TikTok never reports an id for followers, friends or private posts. A video another TryPost post holds is refused (`LogicException` from `reconcileRemoteId`); the resolver logs it once a day instead of failing, and such a post needs a manual fix (the one-off `tiktok:repair-video-ids` ran in production in October 2026 and was removed).++## A refused TikTok status fetch is not a failed publish+TikTok answered status/fetch with 400 `invalid_params` / `invalid_publish_id` for publish_ids it published in the same second (two posts, October 2026: marked failed, one reposted by hand and duplicated). After /init/ accepts a publish, a refused status fetch (not 429/5xx, not a dead token, not a Permission or ContentPolicy refusal, which fail at once) is checked again until `STATUS_UNCONFIRMED_SECONDS` (5 minutes after `tiktok_init_at`), then fails with `TikTokPublishException::unconfirmed()` asking the user to check the profile. Never send the post again (/init/) from that path. Status checks run at 5 s, 30 s, 1 min, then every minute after `tiktok_init_at` until the hour window closes; a content rejection arrives as a FAILED status with its fail_reason.diff --git a/app/Exceptions/Social/TikTokPublishException.php b/app/Exceptions/Social/TikTokPublishException.phpindex dcad7eab7..9d0732059 100644--- a/app/Exceptions/Social/TikTokPublishException.php+++ b/app/Exceptions/Social/TikTokPublishException.php@@ -89,6 +89,21 @@ class TikTokPublishException extends SocialPublishException))->withNetworkReset($response)->asNetworkRejectionIf(in_array($errorCode, self::USER_REJECTION_CODES, true));}+ /**+ * TikTok kept refusing the status of a publish it had accepted. It has+ * published such posts anyway, so the user checks the profile before+ * sending the post again.+ */+ public static function unconfirmed(self $refusal): static+ {+ return new static(+ userMessage: 'TikTok did not confirm this post. Check your TikTok profile before publishing it again.',+ category: ErrorCategory::Unknown,+ platformErrorCode: $refusal->platformErrorCode,+ rawResponse: $refusal->rawResponse,+ );+ }+public static function fromFailReason(string $failReason, ?string $rawResponse = null): static{[$message, $category] = match ($failReason) {diff --git a/app/Jobs/PublishToSocialPlatform.php b/app/Jobs/PublishToSocialPlatform.phpindex 90110b27b..7d98c7da8 100644--- a/app/Jobs/PublishToSocialPlatform.php+++ b/app/Jobs/PublishToSocialPlatform.php@@ -399,6 +399,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue...Arr::except($previousContext, [PublishCheckpoint::TIKTOK_PUBLISH_ID,PublishCheckpoint::TIKTOK_STATUS,+ PublishCheckpoint::TIKTOK_INIT_AT,PublishCheckpoint::TIKTOK_DERIVATIVE_PATHS,PublishCheckpoint::X_MEDIA,]),diff --git a/app/Services/Social/TikTokPublisher.php b/app/Services/Social/TikTokPublisher.phpindex c6e499d8d..fca6116c8 100644--- a/app/Services/Social/TikTokPublisher.php+++ b/app/Services/Social/TikTokPublisher.php@@ -19,12 +19,15 @@ use App\Services\Social\Concerns\HasSocialHttpClient;use App\Support\PostPlatformMetaRules;use App\Support\Social\PublishCheckpoint;use App\Support\Social\TikTokPhotoDerivativeCleaner;+use Carbon\CarbonImmutable;+use Carbon\CarbonInterface;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Sleep;use Illuminate\Support\Str;use Throwable;@@ -32,9 +35,31 @@ class TikTokPublisher{use HasSocialHttpClient;- private const int STATUS_RETRY_DELAY_SECONDS = 30;+ /**+ * When the status is checked, in seconds after TikTok accepted the+ * publish: the first checks come early, then one a minute until the+ * window closes. TikTok may not know a publish_id it has just returned+ * yet, so the first check waits a few seconds.+ */+ private const array STATUS_CHECKS_SECONDS = [5, 30, 60];++ private const int STATUS_CHECK_INTERVAL_SECONDS = 60;++ private const int STATUS_WINDOW_SECONDS = 3600;- private const int STATUS_MAX_RETRIES = 120;+ /**+ * The status checks after the first, which runs in the publish itself:+ * the two other early checks, then one a minute until the window closes.+ */+ private const int STATUS_MAX_RETRIES = 2 + (self::STATUS_WINDOW_SECONDS - self::STATUS_CHECKS_SECONDS[2]) / self::STATUS_CHECK_INTERVAL_SECONDS;++ /**+ * How long a status fetch TikTok refuses still counts as TikTok not knowing+ * the publish yet. It refused publish_ids it published in the same second+ * (October 2026), so a refusal fails the post only after this, and never+ * sends it again.+ */+ private const int STATUS_UNCONFIRMED_SECONDS = 300;private string $baseUrl;@@ -66,6 +91,7 @@ class TikTokPublisher$post,$pendingPublishId,PublishCheckpoint::tiktokDerivativePaths($post->error_context),+ PublishCheckpoint::tiktokInitAt($post->error_context) ?? $this->rememberPublishId($post, $pendingPublishId),);}@@ -245,9 +271,11 @@ class TikTokPublisher$publishId = $this->requirePublishId(data_get($data, 'data.publish_id'));- $this->rememberPublishId($post, $publishId);+ $initAt = $this->rememberPublishId($post, $publishId);++ $this->waitForFirstStatusCheck();- return $this->completePublish($post, $publishId);+ return $this->completePublish($post, $publishId, $initAt);}private function publishPhotos(Post $post, $mediaCollection, ?string $content): array@@ -305,14 +333,16 @@ class TikTokPublisher$publishId = $this->requirePublishId(data_get($response->json(), 'data.publish_id'));- $this->rememberPublishId($post, $publishId, $derivatives);+ $initAt = $this->rememberPublishId($post, $publishId, $derivatives);} catch (Throwable $e) {app(TikTokPhotoDerivativeCleaner::class)->cleanupPaths($derivatives);throw $e;}- return $this->completePublishWithCleanup($post, $publishId, $derivatives);+ $this->waitForFirstStatusCheck();++ return $this->completePublishWithCleanup($post, $publishId, $derivatives, $initAt);}/**@@ -398,7 +428,15 @@ class TikTokPublisher}}- private function waitForPublishStatus(string $publishId): array+ /**+ * A refused status fetch is not a failed publish: TikTok has refused+ * publish_ids it went on to publish. It is checked again until+ * STATUS_UNCONFIRMED_SECONDS, then fails without sending the post again.+ * Only a refusal the user must fix (permissions, an account barred from+ * posting) fails at once. A rejected post comes back as a FAILED status+ * with its fail_reason.+ */+ private function waitForPublishStatus(string $publishId, CarbonInterface $initAt): array{$response = $this->getHttpClient()->post("{$this->baseUrl}/post/publish/status/fetch/", [@@ -406,11 +444,21 @@ class TikTokPublisher]);if ($response->failed()) {- if ($response->status() !== 429 && ! $response->serverError()) {- $this->handleApiError($response);+ if ($response->status() === 429 || $response->serverError()) {+ throw $this->pendingPublishException($publishId, $initAt, $response->status());+ }++ $refusal = TikTokPublishException::fromApiResponse($response);++ if (in_array($refusal->category, [ErrorCategory::Permission, ErrorCategory::ContentPolicy], true)) {+ throw $refusal;+ }++ if ($this->secondsSince($initAt) < self::STATUS_UNCONFIRMED_SECONDS) {+ throw $this->pendingPublishException($publishId, $initAt, $response->status());}- throw $this->pendingPublishException($publishId, $response->status());+ throw TikTokPublishException::unconfirmed($refusal);}$data = $response->json();@@ -425,6 +473,7 @@ class TikTokPublisher),default => throw $this->pendingPublishException($publishId,+ $initAt,status: $statusValue !== '' ? $statusValue : null,),};@@ -446,15 +495,20 @@ class TikTokPublisher/*** Persist the publish_id before status polling so a crash after /init/- * can resume without creating a second publish.+ * can resume without creating a second publish, with the moment the status+ * checks are timed from. A resume whose checkpoint has no such moment+ * (written before it existed, or reset by posts:retry) starts it there.** @param list<string> $derivatives*/- private function rememberPublishId(Post $post, string $publishId, array $derivatives = []): void+ private function rememberPublishId(Post $post, string $publishId, array $derivatives = []): CarbonImmutable{+ $initAt = CarbonImmutable::now();+$context = [...($post->error_context ?? []),PublishCheckpoint::TIKTOK_PUBLISH_ID => $publishId,+ PublishCheckpoint::TIKTOK_INIT_AT => $initAt->toIso8601String(),];if ($derivatives !== []) {@@ -464,9 +518,16 @@ class TikTokPublisher$post->writePublication(['error_context' => $context,]);++ return $initAt;+ }++ private function waitForFirstStatusCheck(): void+ {+ Sleep::for(self::STATUS_CHECKS_SECONDS[0])->seconds();}- private function pendingPublishException(string $publishId, ?int $httpStatus = null, ?string $status = null): PlatformUnavailableException+ private function pendingPublishException(string $publishId, CarbonInterface $initAt, ?int $httpStatus = null, ?string $status = null): PlatformUnavailableException{$context = [PublishCheckpoint::TIKTOK_PUBLISH_ID => $publishId];@@ -478,11 +539,26 @@ class TikTokPublishermessage: "TikTok is still processing publish_id {$publishId}",httpStatus: $httpStatus,context: $context,- retryDelaySeconds: self::STATUS_RETRY_DELAY_SECONDS,+ retryDelaySeconds: $this->secondsUntilNextStatusCheck($initAt),maxRetries: self::STATUS_MAX_RETRIES,);}+ private function secondsUntilNextStatusCheck(CarbonInterface $initAt): int+ {+ $elapsed = $this->secondsSince($initAt);++ $next = collect(self::STATUS_CHECKS_SECONDS)->first(fn (int $seconds): bool => $seconds > $elapsed)+ ?? (intdiv($elapsed, self::STATUS_CHECK_INTERVAL_SECONDS) + 1) * self::STATUS_CHECK_INTERVAL_SECONDS;++ return max(1, $next - $elapsed);+ }++ private function secondsSince(CarbonInterface $moment): int+ {+ return max(0, (int) $moment->diffInSeconds(now()));+ }+/*** Finish an in-flight publish and prune hosted photos only when TikTok* confirmed the attempt is dead, or when it completed. Resumable@@ -492,12 +568,12 @@ class TikTokPublisher* @param array<array-key, mixed> $derivatives* @return array<string, mixed>*/- private function completePublishWithCleanup(Post $post, string $publishId, array $derivatives): array+ private function completePublishWithCleanup(Post $post, string $publishId, array $derivatives, CarbonInterface $initAt): array{$retainDerivatives = true;try {- $result = $this->completePublish($post, $publishId);+ $result = $this->completePublish($post, $publishId, $initAt);$retainDerivatives = false;return $result;@@ -516,9 +592,9 @@ class TikTokPublisher}}- private function completePublish(Post $post, string $publishId): array+ private function completePublish(Post $post, string $publishId, CarbonInterface $initAt): array{- $statusData = $this->waitForPublishStatus($publishId);+ $statusData = $this->waitForPublishStatus($publishId, $initAt);$postId = $this->videoIdFrom($statusData);return [diff --git a/app/Support/Social/PublishCheckpoint.php b/app/Support/Social/PublishCheckpoint.phpindex 773bf7cb4..8b18573d8 100644--- a/app/Support/Social/PublishCheckpoint.php+++ b/app/Support/Social/PublishCheckpoint.php@@ -4,6 +4,8 @@ declare(strict_types=1);namespace App\Support\Social;+use Carbon\CarbonImmutable;+/*** Shared keys and readers for in-flight publish checkpoints on* posts.error_context. Used by the publishers, the TikTok@@ -15,6 +17,8 @@ final class PublishCheckpointpublic const string TIKTOK_STATUS = 'tiktok_status';+ public const string TIKTOK_INIT_AT = 'tiktok_init_at';+public const string TIKTOK_DERIVATIVE_PATHS = 'tiktok_derivative_paths';public const string INSTAGRAM_WORKFLOW = 'instagram_workflow';@@ -33,6 +37,22 @@ final class PublishCheckpointreturn is_string($value) && $value !== '' ? $value : null;}+ /**+ * When TikTok accepted the publish, which the status checks are timed from.+ *+ * @param array<string, mixed>|null $context+ */+ public static function tiktokInitAt(?array $context): ?CarbonImmutable+ {+ $value = data_get($context, self::TIKTOK_INIT_AT);++ if (blank($value) || ! is_string($value)) {+ return null;+ }++ return rescue(fn (): CarbonImmutable => CarbonImmutable::parse($value), null, report: false);+ }+/*** @param array<string, mixed>|null $context* @return array<array-key, mixed>diff --git a/tests/Feature/Commands/RetryFailedPostTest.php b/tests/Feature/Commands/RetryFailedPostTest.phpindex 2787daa65..4d2ef759c 100644--- a/tests/Feature/Commands/RetryFailedPostTest.php+++ b/tests/Feature/Commands/RetryFailedPostTest.php@@ -20,6 +20,7 @@ use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Mail;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Sleep;beforeEach(function () {Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);@@ -453,6 +454,8 @@ test('it starts over when the failure category is not resumable', function (?str]);test('a TikTok retry after a remote FAILED starts a new publish', function () {+ Sleep::fake();+$account = SocialAccount::factory()->tiktok()->create(['workspace_id' => $this->workspace->id,'username' => 'tiktoker',diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.phpindex a6c14bb2f..bbc628a8a 100644--- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php+++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php@@ -43,6 +43,7 @@ use App\Support\Social\GoogleBusinessDerivativeCleaner;use Carbon\Carbon;use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Database\Events\QueryExecuted;+use Illuminate\Http\Client\Request;use Illuminate\Log\Events\MessageLogged;use Illuminate\Queue\Middleware\WithoutOverlapping;use Illuminate\Support\Facades\Bus;@@ -1399,6 +1400,7 @@ test('tiktok photo publish resumes after a status-fetch token expiry without a sEvent::fake();Mail::fake();Storage::fake();+ Sleep::fake();$account = SocialAccount::factory()->tiktok()->create(['workspace_id' => $this->workspace->id,@@ -1468,6 +1470,96 @@ test('tiktok photo publish resumes after a status-fetch token expiry without a s->toHaveCount(1);});+test('a tiktok publish whose status TikTok refuses right after accepting it waits for the next check instead of failing', function () {+ Event::fake();+ Queue::fake();+ $this->freezeSecond();+ Sleep::fake(syncWithCarbon: true);+ $acceptedAt = now();++ $account = SocialAccount::factory()->tiktok()->create([+ 'workspace_id' => $this->workspace->id,+ 'username' => 'tiktoker',+ 'token_expires_at' => now()->addDay(),+ ]);+ $this->post->update([+ 'media' => [[+ 'id' => 'video',+ 'path' => 'media/2026-01/video.mp4',+ 'url' => 'https://example.com/media/2026-01/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]],+ ]);+ $platform = publishJobRetarget($this->post, $account, [+ 'content_type' => ContentType::TikTokVideo,+ 'publish_status' => PlatformStatus::Pending,+ 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],+ ]);++ $api = config('trypost.platforms.tiktok.api');++ Http::fake([+ $api.'/post/publish/video/init/' => Http::response(['data' => ['publish_id' => 'pub_not_known_yet']]),+ $api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ (new PublishToSocialPlatform($platform))->handle();++ $platform->refresh();++ expect($platform->publish_status)->toBe(PlatformStatus::Retrying)+ ->and($platform->status)->not->toBe(PostStatus::Failed)+ ->and(data_get($platform->error_context, 'tiktok_publish_id'))->toBe('pub_not_known_yet')+ ->and(data_get($platform->error_context, 'tiktok_init_at'))->not->toBeNull();++ Mail::assertNothingQueued();+ Mail::assertNothingSent();+ Queue::assertPushed(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $acceptedAt->addSeconds(30)->equalTo($job->delay));+});++test('a tiktok publish TikTok still refuses to report five minutes after accepting it fails without being sent again', function () {+ Event::fake();+ Queue::fake();+ $this->freezeSecond();++ $account = SocialAccount::factory()->tiktok()->create([+ 'workspace_id' => $this->workspace->id,+ 'username' => 'tiktoker',+ 'token_expires_at' => now()->addDay(),+ ]);+ $platform = publishJobRetarget($this->post, $account, [+ 'content_type' => ContentType::TikTokVideo,+ 'publish_status' => PlatformStatus::Retrying,+ 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_never_confirmed',+ 'tiktok_init_at' => now()->subMinutes(5)->toIso8601String(),+ ],+ ]);++ $api = config('trypost.platforms.tiktok.api');++ Http::fake([+ $api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ (new PublishToSocialPlatform($platform))->handle();++ $platform->refresh();++ expect($platform->publish_status)->toBe(PlatformStatus::Failed)+ ->and($platform->error_message)->toBe('TikTok did not confirm this post. Check your TikTok profile before publishing it again.')+ ->and(data_get($platform->error_context, 'platform_error_code'))->toBe('invalid_params');++ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/init/'));+ Queue::assertNotPushed(PublishToSocialPlatform::class);+});+test('pinterest media status 401 marks the account token expired and notifies to reconnect', function () {Event::fake();Queue::fake();diff --git a/tests/Feature/Jobs/SocialPublishingPipelineTest.php b/tests/Feature/Jobs/SocialPublishingPipelineTest.phpindex a51396c6b..b7e4e554a 100644--- a/tests/Feature/Jobs/SocialPublishingPipelineTest.php+++ b/tests/Feature/Jobs/SocialPublishingPipelineTest.php@@ -40,6 +40,7 @@ use Illuminate\Support\Facades\Exceptions;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Sleep;use Illuminate\Support\Str;beforeEach(function () {@@ -284,6 +285,8 @@ test('each network queue consumes scheduled posts and delayed retries through th]);test('the TikTok worker publishes through the real publisher and token refresh flow', function (string $scenario) {+ Sleep::fake();+$affected = scheduledPipelineTarget(Platform::TikTok);$affected->socialAccount->update(['token_expires_at' => now()->subMinute(), 'refresh_token' => 'affected-refresh']);$refreshCalls = 0;diff --git a/tests/Feature/Services/Social/TikTokPublisherTest.php b/tests/Feature/Services/Social/TikTokPublisherTest.phpindex 9b7bb80ba..a82d16961 100644--- a/tests/Feature/Services/Social/TikTokPublisherTest.php+++ b/tests/Feature/Services/Social/TikTokPublisherTest.php@@ -15,10 +15,14 @@ use App\Models\Workspace;use App\Services\Media\MediaOptimizer;use App\Services\Social\TikTokPublisher;use Illuminate\Http\Client\ConnectionException;+use Illuminate\Http\Client\Request;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Sleep;beforeEach(function () {+ Sleep::fake(syncWithCarbon: true);+$this->user = User::factory()->create();$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);@@ -166,8 +170,8 @@ test('tiktok publisher does not report success before processing completes', fun'tiktok_publish_id' => 'pub_processing','tiktok_status' => 'PROCESSING_DOWNLOAD',])- ->and($exception->retryDelaySeconds)->toBe(30)- ->and($exception->maxRetries)->toBe(120);+ ->and($exception->retryDelaySeconds)->toBe(25)+ ->and($exception->maxRetries)->toBe(61);});expect($this->post->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_processing');@@ -449,6 +453,210 @@ test('tiktok publisher retries a rate-limited status fetch without creating a duHttp::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));});+test('tiktok publisher checks the status five seconds after TikTok accepts the publish', function () {+ $this->freezeSecond();+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/test-video.mp4',+ 'url' => 'https://example.com/media/2026-01/test-video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'test-video.mp4',+ ]],+ ]);+ $acceptedAt = now()->toIso8601String();++ Http::fake([+ $this->api.'/post/publish/video/init/' => Http::response(['data' => ['publish_id' => 'pub_checked_later']]),+ $this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PUBLISH_COMPLETE']]),+ ]);++ $this->publisher->publish($this->post);++ Sleep::assertSequence([Sleep::for(5)->seconds()]);+ expect($this->post->fresh()->error_context)->toMatchArray([+ 'tiktok_publish_id' => 'pub_checked_later',+ 'tiktok_init_at' => $acceptedAt,+ ]);+});++test('tiktok publisher waits for a publish TikTok refuses to report right after accepting it', function () {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-video',+ 'path' => 'media/2026-01/test-video.mp4',+ 'url' => 'https://example.com/media/2026-01/test-video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'test-video.mp4',+ ]],+ ]);++ Http::fake([+ $this->api.'/post/publish/video/init/' => Http::response(['data' => ['publish_id' => 'pub_not_known_yet']]),+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->post))+ ->toThrow(function (PlatformUnavailableException $exception): void {+ expect($exception->httpStatus)->toBe(400)+ ->and($exception->context['tiktok_publish_id'] ?? null)->toBe('pub_not_known_yet')+ ->and($exception->retryDelaySeconds)->toBe(25);+ });++ expect(Http::recorded(fn (Request $request): bool => str_contains($request->url(), '/init/')))->toHaveCount(1);+});++test('tiktok publisher checks the status at 5 s, 30 s, 1 min and then every minute after TikTok accepted the publish', function (int $secondsSinceAccepted, int $secondsUntilNextCheck) {+ $this->freezeSecond();+ $this->post->update([+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_existing',+ 'tiktok_init_at' => now()->subSeconds($secondsSinceAccepted)->toIso8601String(),+ ],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_UPLOAD']]),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->retryDelaySeconds)->toBe($secondsUntilNextCheck));+})->with([+ 'just accepted' => [0, 5],+ 'at 5 s' => [5, 25],+ 'at 30 s' => [30, 30],+ 'at 1 min' => [60, 60],+ 'past 1 min' => [75, 45],+ 'at 2 min' => [120, 60],+ 'at 10 min' => [600, 60],+]);++test('tiktok publisher keeps checking a refused status until five minutes after TikTok accepted the publish', function (int $secondsSinceAccepted, int $secondsUntilNextCheck) {+ $this->freezeSecond();+ $this->post->update([+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_existing',+ 'tiktok_init_at' => now()->subSeconds($secondsSinceAccepted)->toIso8601String(),+ ],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->retryDelaySeconds)->toBe($secondsUntilNextCheck));++ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/init/'));+})->with([+ 'at 30 s' => [30, 30],+ 'at 1 min' => [60, 60],+ 'at 4 min' => [240, 60],+ 'just before 5 min' => [299, 1],+]);++test('tiktok publisher fails a publish TikTok still refuses to report five minutes after accepting it, without sending it again', function () {+ $this->freezeSecond();+ $this->post->update([+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_existing',+ 'tiktok_init_at' => now()->subMinutes(5)->toIso8601String(),+ ],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(function (TikTokPublishException $exception): void {+ expect($exception->userMessage)->toBe('TikTok did not confirm this post. Check your TikTok profile before publishing it again.')+ ->and($exception->platformErrorCode)->toBe('invalid_params');+ });++ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/init/'));+});++test('tiktok publisher fails at once when TikTok refuses the status for a reason only the user can fix', function (string $code, string $message) {+ $this->freezeSecond();+ $this->post->update([+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_existing',+ 'tiktok_init_at' => now()->subSeconds(30)->toIso8601String(),+ ],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => $code, 'message' => $code],+ ], 403),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(fn (TikTokPublishException $exception) => expect($exception->userMessage)->toBe($message));+})->with([+ 'missing permissions' => ['scope_not_authorized', 'Missing required permissions. Please reconnect with all scopes.'],+ 'account barred from posting' => ['spam_risk_user_banned_from_posting', 'Account is banned from posting.'],+]);++test('tiktok publisher keeps checking a status refused with a code that only names the request', function (string $code) {+ $this->freezeSecond();+ $this->post->update([+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_existing',+ 'tiktok_init_at' => now()->subSeconds(30)->toIso8601String(),+ ],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => $code, 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(PlatformUnavailableException::class);+})->with(['invalid_params', 'invalid_param', 'invalid_publish_id', 'rate_limit_exceeded']);++test('tiktok publisher times a publish checkpointed without its start from the resume', function () {+ $this->post->update([+ 'error_context' => ['tiktok_publish_id' => 'pub_from_before'],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->retryDelaySeconds)->toBe(5));+});++test('tiktok publisher keeps timing a resumed publish from its first resume when the checkpoint had no start', function () {+ $this->freezeSecond();+ $this->post->update([+ 'error_context' => ['tiktok_publish_id' => 'pub_from_before'],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_UPLOAD']]),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(PlatformUnavailableException::class);+ expect($this->post->fresh()->error_context['tiktok_init_at'] ?? null)->toBe(now()->toIso8601String());++ $this->travel(30)->seconds();++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->retryDelaySeconds)->toBe(30));+});+test('tiktok publisher keeps photo derivatives while pending and prunes them on completion', function () {Storage::fake();$derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';@@ -481,6 +689,34 @@ test('tiktok publisher keeps photo derivatives while pending and prunes them onHttp::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));});+test('tiktok publisher keeps photo derivatives while TikTok refuses the status, since it may still pull them', function () {+ $this->freezeSecond();+ Storage::fake();+ $derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';+ Storage::put($derivativePath, 'image');++ $this->post->update([+ 'error_context' => [+ 'tiktok_publish_id' => 'pub_existing',+ 'tiktok_init_at' => now()->subMinute()->toIso8601String(),+ 'tiktok_derivative_paths' => [$derivativePath],+ ],+ ]);++ Http::fake([+ $this->api.'/post/publish/status/fetch/' => Http::response([+ 'error' => ['code' => 'invalid_params', 'message' => 'invalid_publish_id'],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(function (PlatformUnavailableException $exception) use ($derivativePath): void {+ expect($exception->context['tiktok_derivative_paths'] ?? null)->toBe([$derivativePath]);+ });++ Storage::assertExists($derivativePath);+});+test('tiktok publisher can publish photos', function () {$this->post->update(['media' => [