Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Report caught publish failures to Nightwatch (#350)

Paulo Castellano8ff11a07bd5c
diff --git a/app/Exceptions/PlatformUnavailableException.php b/app/Exceptions/PlatformUnavailableException.php
index f24671389..2bb930657 100644
--- a/app/Exceptions/PlatformUnavailableException.php
+++ b/app/Exceptions/PlatformUnavailableException.php
@@ -26,4 +26,15 @@ class PlatformUnavailableException extends Exception
) {
parent::__construct($message);
}
+
+ /**
+ * @return array<string, mixed>
+ */
+ public function context(): array
+ {
+ return array_filter([
+ 'http_status' => $this->httpStatus,
+ ...$this->context,
+ ], fn (mixed $value): bool => $value !== null);
+ }
}
diff --git a/app/Exceptions/Social/SocialPublishException.php b/app/Exceptions/Social/SocialPublishException.php
index 2af283821..70367e0ab 100644
--- a/app/Exceptions/Social/SocialPublishException.php
+++ b/app/Exceptions/Social/SocialPublishException.php
@@ -24,7 +24,7 @@ abstract class SocialPublishException extends RuntimeException
public function context(): array
{
return [
- 'platform' => static::platform(),
+ 'platform' => $this->platform(),
'category' => $this->category->value,
'platform_error_code' => $this->platformErrorCode,
'user_message' => $this->userMessage,
diff --git a/app/Exceptions/TokenExpiredException.php b/app/Exceptions/TokenExpiredException.php
index 6689b8f62..407eeb30f 100644
--- a/app/Exceptions/TokenExpiredException.php
+++ b/app/Exceptions/TokenExpiredException.php
@@ -14,4 +14,14 @@ class TokenExpiredException extends Exception
) {
parent::__construct($message);
}
+
+ /**
+ * @return array{platform_error_code: ?string}
+ */
+ public function context(): array
+ {
+ return [
+ 'platform_error_code' => $this->platformErrorCode,
+ ];
+ }
}
diff --git a/app/Jobs/PublishToSocialPlatform.php b/app/Jobs/PublishToSocialPlatform.php
index f281a90f3..68308e003 100644
--- a/app/Jobs/PublishToSocialPlatform.php
+++ b/app/Jobs/PublishToSocialPlatform.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Jobs;
+use App\Enums\Media\Type as MediaType;
use App\Enums\Notification\Channel;
use App\Enums\Notification\Type;
use App\Enums\PostPlatform\Status as PostPlatformStatus;
@@ -139,31 +140,19 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
$this->rescheduleForRetry($refreshError);
break;
} catch (Throwable $refreshError) {
- Log::error('Token refresh failed during publish retry', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
- 'error' => $refreshError->getMessage(),
+ $this->reportCaughtPublishFailure($refreshError, [
+ 'phase' => 'token_refresh',
]);
+ $this->failWithExpiredToken($e);
+ break;
}
}
- // All attempts exhausted or refresh failed
- Log::error('Token expired while publishing to social platform', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
- 'error' => $e->getMessage(),
- 'platform_error_code' => $e->platformErrorCode,
- ]);
-
- $this->markPlatformAsFailed($e->getMessage(), [
- 'category' => ErrorCategory::TokenExpired->value,
- 'platform_error_code' => $e->platformErrorCode,
- 'failed_at' => now()->toIso8601String(),
- ]);
- $this->postPlatform->socialAccount->markAsTokenExpired($e->getMessage());
+ $this->reportCaughtPublishFailure($e);
+ $this->failWithExpiredToken($e);
break;
} catch (SocialPublishException $e) {
- Log::error('Social publish failed: '.$e->userMessage);
+ $this->reportCaughtPublishFailure($e);
$this->markPlatformAsFailed($e->userMessage, [
'category' => $e->category->value,
'platform_error_code' => $e->platformErrorCode,
@@ -174,11 +163,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
]);
break;
} catch (Throwable $e) {
- Log::error('Failed to publish to social platform', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
- 'error' => $e->getMessage(),
- ]);
+ $this->reportCaughtPublishFailure($e);
$this->markPlatformAsFailed($this->safeFailureMessage($e), [
'category' => ErrorCategory::Unknown->value,
'failed_at' => now()->toIso8601String(),
@@ -248,10 +233,9 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
];
if ($retryCount > $maxRetries) {
- Log::warning('Publish retries exhausted: platform unavailable', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
- ...$context,
+ $this->reportCaughtPublishFailure($e, [
+ 'retry_count' => $retryCount,
+ 'max_retries' => $maxRetries,
]);
$this->markPlatformAsFailed(
@@ -284,6 +268,73 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
self::dispatch($this->postPlatform, $retryCount)->delay($nextAttemptAt);
}
+ /**
+ * Caught publish failures never reach Nightwatch unless we report() them.
+ * report() feeds Exceptions; the structured log carries post/platform ids
+ * Nightwatch's exception record does not. In-flight retries stay warnings.
+ *
+ * @param array<string, mixed> $context
+ */
+ private function reportCaughtPublishFailure(Throwable $e, array $context = []): void
+ {
+ Log::error('Social publish failed', [
+ ...(method_exists($e, 'context') ? $e->context() : []),
+ 'post_platform_id' => $this->postPlatform->id,
+ 'platform' => $this->postPlatform->platform->value,
+ 'content_type' => $this->postPlatform->content_type?->value,
+ 'exception' => $e::class,
+ 'message' => $e->getMessage(),
+ ...$context,
+ 'media' => $this->mediaSnapshot($this->postPlatform),
+ ]);
+
+ report($e);
+ }
+
+ /**
+ * Nightwatch's exception record is class/message/stack only. The
+ * structured log needs the media the platform tried to pull so a
+ * CDN miss can be told from an API rejection.
+ *
+ * @return list<array{url: ?string, mime_type: ?string, size: ?int, type: ?string}>
+ */
+ private function mediaSnapshot(PostPlatform $postPlatform): array
+ {
+ $media = $postPlatform->post?->media;
+
+ if (! is_array($media)) {
+ return [];
+ }
+
+ return array_values(array_map(function (mixed $item): array {
+ $item = is_array($item) ? $item : [];
+ $url = data_get($item, 'url');
+ $mimeType = data_get($item, 'mime_type');
+ $path = data_get($item, 'original_filename') ?? data_get($item, 'path');
+ $type = MediaType::classify(
+ is_string($mimeType) ? $mimeType : null,
+ is_string($path) ? $path : null,
+ );
+
+ return [
+ 'url' => is_string($url) ? $url : null,
+ 'mime_type' => is_string($mimeType) ? $mimeType : null,
+ 'size' => is_numeric(data_get($item, 'size')) ? (int) data_get($item, 'size') : null,
+ 'type' => $type?->value,
+ ];
+ }, $media));
+ }
+
+ private function failWithExpiredToken(TokenExpiredException $e): void
+ {
+ $this->markPlatformAsFailed($e->getMessage(), [
+ 'category' => ErrorCategory::TokenExpired->value,
+ 'platform_error_code' => $e->platformErrorCode,
+ 'failed_at' => now()->toIso8601String(),
+ ]);
+ $this->postPlatform->socialAccount->markAsTokenExpired($e->getMessage());
+ }
+
/**
* @param array<string, mixed>|null $context
*/
diff --git a/app/Services/Social/InstagramPublisher.php b/app/Services/Social/InstagramPublisher.php
index 21d97f21b..8be62d24b 100644
--- a/app/Services/Social/InstagramPublisher.php
+++ b/app/Services/Social/InstagramPublisher.php
@@ -353,7 +353,7 @@ class InstagramPublisher
{
$statusResponse = $this->sendGraphRequest(
fn (): Response => $this->socialHttp()->get("{$this->baseUrl}/{$containerId}", [
- 'fields' => 'status_code',
+ 'fields' => 'status_code,status',
'access_token' => $accessToken,
]),
$containerId,
@@ -368,19 +368,22 @@ class InstagramPublisher
throw $this->pendingContainerException($containerId, $workflow, $statusResponse->status());
}
- $status = ContainerStatus::tryFrom((string) ($statusResponse->json()['status_code'] ?? ''));
+ $statusCode = (string) ($statusResponse->json()['status_code'] ?? '');
+ $status = ContainerStatus::tryFrom($statusCode);
return match ($status) {
ContainerStatus::Finished, ContainerStatus::Published => $status,
- ContainerStatus::Error => throw new InstagramPublishException(
- userMessage: 'Instagram media processing failed',
- category: ErrorCategory::ServerError,
- ),
+ ContainerStatus::Error => throw $this->mediaProcessingFailedException($statusResponse),
ContainerStatus::Expired => throw new InstagramPublishException(
userMessage: 'Media container expired. Please try again in a few minutes.',
category: ErrorCategory::ServerError,
+ rawResponse: $this->redactResponseBody($statusResponse->body()),
+ ),
+ default => throw $this->pendingContainerException(
+ $containerId,
+ $workflow,
+ statusCode: $statusCode !== '' ? $statusCode : null,
),
- default => throw $this->pendingContainerException($containerId, $workflow),
};
}
@@ -466,17 +469,40 @@ class InstagramPublisher
/**
* @param array<string, mixed> $workflow
*/
- private function pendingContainerException(string $containerId, array $workflow, ?int $httpStatus = null): PlatformUnavailableException
+ private function pendingContainerException(string $containerId, array $workflow, ?int $httpStatus = null, ?string $statusCode = null): PlatformUnavailableException
{
+ $context = [PublishCheckpoint::INSTAGRAM_WORKFLOW => $workflow];
+
+ if (is_string($statusCode) && $statusCode !== '') {
+ $context[PublishCheckpoint::INSTAGRAM_STATUS] = $statusCode;
+ }
+
return new PlatformUnavailableException(
message: "Instagram is still processing container {$containerId}",
httpStatus: $httpStatus,
- context: [PublishCheckpoint::INSTAGRAM_WORKFLOW => $workflow],
+ context: $context,
retryDelaySeconds: self::STATUS_RETRY_DELAY_SECONDS,
maxRetries: self::STATUS_MAX_RETRIES,
);
}
+ private function mediaProcessingFailedException(Response $response): InstagramPublishException
+ {
+ $body = $this->redactResponseBody($response->body());
+
+ Log::error('Instagram media processing failed', [
+ 'status_code' => data_get($response->json(), 'status_code'),
+ 'status' => data_get($response->json(), 'status'),
+ 'body' => $body,
+ ]);
+
+ return new InstagramPublishException(
+ userMessage: 'Instagram media processing failed',
+ category: ErrorCategory::ServerError,
+ rawResponse: $body,
+ );
+ }
+
/**
* @param array<string, mixed> $parameters
*/
diff --git a/app/Services/Social/TikTokPublisher.php b/app/Services/Social/TikTokPublisher.php
index f5e9eabf5..73973997a 100644
--- a/app/Services/Social/TikTokPublisher.php
+++ b/app/Services/Social/TikTokPublisher.php
@@ -372,7 +372,8 @@ class TikTokPublisher
}
$data = $response->json();
- $status = PublishStatus::tryFrom((string) data_get($data, 'data.status', ''));
+ $statusValue = (string) data_get($data, 'data.status', '');
+ $status = PublishStatus::tryFrom($statusValue);
return match ($status) {
PublishStatus::PublishComplete => data_get($data, 'data', []),
@@ -380,7 +381,10 @@ class TikTokPublisher
(string) data_get($data, 'data.fail_reason', 'Unknown error'),
json_encode($data),
),
- default => throw $this->pendingPublishException($publishId),
+ default => throw $this->pendingPublishException(
+ $publishId,
+ status: $statusValue !== '' ? $statusValue : null,
+ ),
};
}
@@ -420,12 +424,18 @@ class TikTokPublisher
]);
}
- private function pendingPublishException(string $publishId, ?int $httpStatus = null): PlatformUnavailableException
+ private function pendingPublishException(string $publishId, ?int $httpStatus = null, ?string $status = null): PlatformUnavailableException
{
+ $context = [PublishCheckpoint::TIKTOK_PUBLISH_ID => $publishId];
+
+ if (is_string($status) && $status !== '') {
+ $context[PublishCheckpoint::TIKTOK_STATUS] = $status;
+ }
+
return new PlatformUnavailableException(
message: "TikTok is still processing publish_id {$publishId}",
httpStatus: $httpStatus,
- context: [PublishCheckpoint::TIKTOK_PUBLISH_ID => $publishId],
+ context: $context,
retryDelaySeconds: self::STATUS_RETRY_DELAY_SECONDS,
maxRetries: self::STATUS_MAX_RETRIES,
);
diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.php
index 6ef2c006a..cdb96b7c2 100644
--- a/app/Services/Social/XPublisher.php
+++ b/app/Services/Social/XPublisher.php
@@ -16,6 +16,7 @@ use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Sleep;
use Throwable;
class XPublisher
@@ -360,6 +361,8 @@ class XPublisher
private function waitForProcessing(string $mediaId, int $maxAttempts = 20): void
{
+ $lastProcessingInfo = null;
+
for ($i = 0; $i < $maxAttempts; $i++) {
// Official status endpoint: GET /2/media/upload?media_id=...&command=STATUS
// (not GET /2/media/{id} — that path is not the upload-status contract).
@@ -371,7 +374,7 @@ class XPublisher
if ($response->failed()) {
Log::error('X media status check error', ['body' => $this->redactResponseBody($response->body())]);
- sleep(3);
+ Sleep::for(3)->seconds();
continue;
}
@@ -385,6 +388,7 @@ class XPublisher
return;
}
+ $lastProcessingInfo = $processingInfo;
$state = data_get($processingInfo, 'state', 'unknown');
if ($state === 'succeeded') {
@@ -405,15 +409,21 @@ class XPublisher
);
}
- // Wait before checking again
- $waitTime = (int) data_get($processingInfo, 'check_after_secs', 3);
- sleep(max(0, $waitTime));
+ Sleep::for(max(0, (int) data_get($processingInfo, 'check_after_secs', 3)))->seconds();
}
+ $rawResponse = is_array($lastProcessingInfo) ? json_encode($lastProcessingInfo) : null;
+
+ Log::error('X media processing timed out', [
+ 'media_id' => $mediaId,
+ 'processing_info' => $lastProcessingInfo,
+ ]);
+
throw new XPublishException(
userMessage: 'X media processing timed out. Please try again.',
category: ErrorCategory::ServerError,
platformErrorCode: 'media-processing-timeout',
+ rawResponse: $rawResponse,
);
}
diff --git a/app/Support/Social/PublishCheckpoint.php b/app/Support/Social/PublishCheckpoint.php
index 6862d77e9..328777e54 100644
--- a/app/Support/Social/PublishCheckpoint.php
+++ b/app/Support/Social/PublishCheckpoint.php
@@ -13,10 +13,14 @@ final class PublishCheckpoint
{
public const string TIKTOK_PUBLISH_ID = 'tiktok_publish_id';
+ public const string TIKTOK_STATUS = 'tiktok_status';
+
public const string TIKTOK_DERIVATIVE_PATHS = 'tiktok_derivative_paths';
public const string INSTAGRAM_WORKFLOW = 'instagram_workflow';
+ public const string INSTAGRAM_STATUS = 'instagram_status';
+
/**
* @param array<string, mixed>|null $context
*/
@@ -38,6 +42,16 @@ final class PublishCheckpoint
return is_array($paths) ? $paths : [];
}
+ /**
+ * @param array<string, mixed>|null $context
+ */
+ public static function tiktokStatus(?array $context): ?string
+ {
+ $value = data_get($context, self::TIKTOK_STATUS);
+
+ return is_string($value) && $value !== '' ? $value : null;
+ }
+
/**
* @param array<string, mixed>|null $context
* @return array<string, mixed>|null
@@ -48,4 +62,14 @@ final class PublishCheckpoint
return is_array($workflow) && $workflow !== [] ? $workflow : null;
}
+
+ /**
+ * @param array<string, mixed>|null $context
+ */
+ public static function instagramStatus(?array $context): ?string
+ {
+ $value = data_get($context, self::INSTAGRAM_STATUS);
+
+ return is_string($value) && $value !== '' ? $value : null;
+ }
}
diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.php
index 652a0c557..c6ef6d3f8 100644
--- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php
+++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php
@@ -12,6 +12,7 @@ use App\Enums\UserWorkspace\Role;
use App\Events\PostPlatformStatusUpdated;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
+use App\Exceptions\Social\InstagramPublishException;
use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
use App\Jobs\PublishToSocialPlatform;
@@ -29,11 +30,14 @@ use App\Services\Social\LinkedInPublisher;
use App\Services\Social\PinterestPublisher;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldBeUnique;
+use Illuminate\Log\Events\MessageLogged;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Exceptions;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
@@ -211,6 +215,174 @@ test('publish keeps the vetted user message from a publish exception', function
expect($this->postPlatform->error_message)->toBe('LinkedIn rejected this post.');
});
+test('publish reports caught publish exceptions so Nightwatch sees them', function (LinkedInPublishException $exception) {
+ Event::fake();
+ Exceptions::fake();
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow($exception);
+
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ (new PublishToSocialPlatform($this->postPlatform))->handle();
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(LinkedInPublishException::class);
+ $this->postPlatform->refresh();
+ expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
+ ->and($this->postPlatform->error_message)->toBe($exception->userMessage);
+})->with([
+ 'server error' => fn () => new LinkedInPublishException(
+ userMessage: 'LinkedIn could not process the media.',
+ category: ErrorCategory::ServerError,
+ platformErrorCode: 'media-processing-timeout',
+ rawResponse: '{"status":"ERROR"}',
+ ),
+ 'content policy' => fn () => new LinkedInPublishException(
+ userMessage: 'LinkedIn rejected this post.',
+ category: ErrorCategory::ContentPolicy,
+ ),
+]);
+
+test('publish reports unexpected errors so Nightwatch sees them', function () {
+ Event::fake();
+ Exceptions::fake();
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow(new TypeError('API Error'));
+
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ (new PublishToSocialPlatform($this->postPlatform))->handle();
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(TypeError::class);
+ $this->postPlatform->refresh();
+ expect($this->postPlatform->error_message)->toBe('An unexpected error occurred while publishing. Please try again.');
+});
+
+test('publish reports token expiry so Nightwatch sees it', function () {
+ Event::fake();
+ Exceptions::fake();
+ Mail::fake();
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow(new TokenExpiredException('Token expired', '401'));
+
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ (new PublishToSocialPlatform($this->postPlatform))->handle();
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(TokenExpiredException::class);
+});
+
+test('publish reports a failed token refresh once', function () {
+ Event::fake();
+ Exceptions::fake();
+ Mail::fake();
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow(new TokenExpiredException('Token expired', '190'));
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ $verifier = Mockery::mock(ConnectionVerifier::class);
+ $verifier->shouldReceive('verify')->andThrow(new TokenExpiredException('Refresh failed'));
+ $this->app->instance(ConnectionVerifier::class, $verifier);
+
+ (new PublishToSocialPlatform($this->postPlatform))->handle();
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (TokenExpiredException $e): bool => $e->getMessage() === 'Refresh failed');
+ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+});
+
+test('publish does not report a platform-unavailable retry', function () {
+ Bus::fake([PublishToSocialPlatform::class]);
+ Event::fake();
+ Exceptions::fake();
+ Mail::fake();
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow(
+ new PlatformUnavailableException('LinkedIn 503', 503)
+ );
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ (new PublishToSocialPlatform($this->postPlatform))->handle();
+
+ Exceptions::assertNothingReported();
+ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying);
+});
+
+test('publish log includes media so Nightwatch can tell a CDN miss from an API rejection', function () {
+ Exceptions::fake();
+
+ $this->post->update([
+ 'media' => [[
+ 'url' => 'https://cdn.trypost.it/media/2026-01/clip.mp4',
+ 'mime_type' => 'video/mp4',
+ 'size' => 4_194_304,
+ 'path' => 'media/2026-01/clip.mp4',
+ 'original_filename' => 'clip.mp4',
+ ]],
+ ]);
+
+ $logs = [];
+ Log::listen(function (MessageLogged $event) use (&$logs): void {
+ $logs[] = $event;
+ });
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow(
+ new InstagramPublishException(
+ userMessage: 'Instagram media processing failed',
+ category: ErrorCategory::ServerError,
+ rawResponse: '{"status":"ERROR","detail":"download failed"}',
+ )
+ );
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+
+ $entry = collect($logs)->first(
+ fn (MessageLogged $event): bool => $event->message === 'Social publish failed'
+ );
+
+ expect($entry)->not->toBeNull()
+ ->and($entry->level)->toBe('error')
+ ->and(data_get($entry->context, 'platform'))->toBe('linkedin')
+ ->and(data_get($entry->context, 'media.0.url'))->toBe('https://cdn.trypost.it/media/2026-01/clip.mp4')
+ ->and(data_get($entry->context, 'media.0.mime_type'))->toBe('video/mp4')
+ ->and(data_get($entry->context, 'media.0.size'))->toBe(4_194_304)
+ ->and(data_get($entry->context, 'media.0.type'))->toBe('video')
+ ->and(data_get($entry->context, 'content_type'))->toBe('linkedin_post')
+ ->and(data_get($entry->context, 'raw_response'))->toBe('{"status":"ERROR","detail":"download failed"}');
+});
+
+test('publish reports when platform-unavailable retries are exhausted', function () {
+ Bus::fake([PublishToSocialPlatform::class]);
+ Event::fake();
+ Exceptions::fake();
+ Mail::fake();
+
+ $publisher = Mockery::mock(LinkedInPublisher::class);
+ $publisher->shouldReceive('publish')->andThrow(
+ new PlatformUnavailableException('TikTok is still processing publish_id pub_stuck', 503)
+ );
+ $this->app->instance(LinkedInPublisher::class, $publisher);
+
+ $this->postPlatform->update([
+ 'error_context' => ['retry_count' => PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES],
+ ]);
+
+ (new PublishToSocialPlatform($this->postPlatform))->handle();
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(PlatformUnavailableException::class);
+ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+});
+
test('publish never leaks a raw internal error to the failure record (and the email)', function () {
Event::fake();
diff --git a/tests/Feature/Services/Social/InstagramPublisherTest.php b/tests/Feature/Services/Social/InstagramPublisherTest.php
index 2a71ae499..a71097da0 100644
--- a/tests/Feature/Services/Social/InstagramPublisherTest.php
+++ b/tests/Feature/Services/Social/InstagramPublisherTest.php
@@ -494,6 +494,7 @@ test('instagram publisher resumes a processing carousel child without recreating
'child_container_ids' => ['child-1', 'child-2'],
'processing_child_container_ids' => ['child-2'],
],
+ 'instagram_status' => 'IN_PROGRESS',
])->and($exception->retryDelaySeconds)->toBe(10)
->and($exception->maxRetries)->toBe(90);
@@ -652,11 +653,19 @@ test('instagram publisher handles media processing error', function () {
], 200),
'https://graph.instagram.com/v25.0/container-123*' => Http::response([
'status_code' => 'ERROR',
+ 'status' => 'Media download has failed. Please check the video URL.',
], 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform))
- ->toThrow(Exception::class, 'Instagram media processing failed');
+ ->toThrow(function (InstagramPublishException $exception): void {
+ expect($exception->getMessage())->toBe('Instagram media processing failed')
+ ->and($exception->rawResponse)->toContain('Media download has failed')
+ ->and($exception->rawResponse)->toContain('ERROR');
+ });
+
+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'container-123')
+ && str_contains((string) data_get($request->data(), 'fields', ''), 'status'));
});
test('instagram publisher resumes media processing without creating another container', function () {
@@ -697,6 +706,7 @@ test('instagram publisher resumes media processing without creating another cont
'stage' => 'final_container',
'container_id' => 'container-123',
],
+ 'instagram_status' => 'IN_PROGRESS',
])->and($exception->retryDelaySeconds)->toBe(10)
->and($exception->maxRetries)->toBe(90);
@@ -739,6 +749,7 @@ test('instagram publisher does not publish a container that never finishes proce
'stage' => 'final_container',
'container_id' => 'container-123',
],
+ 'instagram_status' => 'IN_PROGRESS',
]);
});
@@ -1007,11 +1018,17 @@ test('instagram publisher fails a resumed container that reports ERROR', functio
]);
Http::fake([
- 'https://graph.instagram.com/v25.0/container-123*' => Http::response(['status_code' => 'ERROR'], 200),
+ 'https://graph.instagram.com/v25.0/container-123*' => Http::response([
+ 'status_code' => 'ERROR',
+ 'status' => 'Media download has failed. Please check the video URL.',
+ ], 200),
]);
expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
- ->toThrow(InstagramPublishException::class, 'Instagram media processing failed');
+ ->toThrow(function (InstagramPublishException $exception): void {
+ expect($exception->getMessage())->toBe('Instagram media processing failed')
+ ->and($exception->rawResponse)->toContain('Media download has failed');
+ });
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/media_publish'));
Http::assertNotSent(fn ($request) => $request->method() === 'POST' && str_contains($request->url(), '/media'));
diff --git a/tests/Feature/Services/Social/TikTokPublisherTest.php b/tests/Feature/Services/Social/TikTokPublisherTest.php
index 8adeb204d..310ac30b7 100644
--- a/tests/Feature/Services/Social/TikTokPublisherTest.php
+++ b/tests/Feature/Services/Social/TikTokPublisherTest.php
@@ -106,7 +106,10 @@ test('tiktok publisher does not report success before processing completes', fun
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(function (PlatformUnavailableException $exception): void {
- expect($exception->context)->toBe(['tiktok_publish_id' => 'pub_processing'])
+ expect($exception->context)->toBe([
+ 'tiktok_publish_id' => 'pub_processing',
+ 'tiktok_status' => 'PROCESSING_DOWNLOAD',
+ ])
->and($exception->retryDelaySeconds)->toBe(30)
->and($exception->maxRetries)->toBe(120);
});
diff --git a/tests/Feature/Services/Social/XPublisherTest.php b/tests/Feature/Services/Social/XPublisherTest.php
index 8d050ea3a..2989c9b76 100644
--- a/tests/Feature/Services/Social/XPublisherTest.php
+++ b/tests/Feature/Services/Social/XPublisherTest.php
@@ -16,6 +16,7 @@ use App\Services\Social\XPublisher;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Sleep;
/**
* Official X upload STATUS: GET /2/media/upload?media_id=...&command=STATUS
@@ -1116,6 +1117,67 @@ test('x publisher fails when media processing reports failed', function () {
->toThrow(XPublishException::class, 'X could not process the uploaded media');
});
+test('x publisher times out media processing with the last status payload', function () {
+ Sleep::fake();
+
+ $this->post->update([
+ 'media' => [
+ [
+ 'id' => 'test-media-video',
+ 'path' => 'media/2026-01/clip.mp4',
+ 'url' => 'https://example.com/media/2026-01/clip.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'clip.mp4',
+ ],
+ ],
+ ]);
+
+ Http::fake(function ($request) {
+ $url = $request->url();
+
+ if (str_contains($url, '/2/media/upload/initialize')) {
+ return Http::response(['data' => ['id' => 'media_proc_timeout']], 200);
+ }
+
+ if (str_contains($url, '/append')) {
+ return Http::response(null, 204);
+ }
+
+ if (str_contains($url, '/finalize')) {
+ return Http::response([
+ 'data' => [
+ 'id' => 'media_proc_timeout',
+ 'processing_info' => ['state' => 'pending', 'check_after_secs' => 0],
+ ],
+ ], 200);
+ }
+
+ if (isXMediaUploadStatusRequest($request)) {
+ return Http::response([
+ 'data' => [
+ 'processing_info' => [
+ 'state' => 'in_progress',
+ 'check_after_secs' => 0,
+ 'progress_percent' => 40,
+ ],
+ ],
+ ], 200);
+ }
+
+ return Http::response('fake-video-content', 200);
+ });
+
+ expect(fn () => $this->publisher->publish($this->postPlatform))
+ ->toThrow(function (XPublishException $exception): void {
+ expect($exception->getMessage())->toBe('X media processing timed out. Please try again.')
+ ->and($exception->platformErrorCode)->toBe('media-processing-timeout')
+ ->and($exception->rawResponse)->toContain('in_progress')
+ ->and($exception->rawResponse)->toContain('40');
+ });
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/tweets'));
+});
+
test('x publisher fails when tweet rejects invalid media ids', function () {
$this->post->update([
'media' => [
diff --git a/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php b/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php
index ff9db9e40..b4e345073 100644
--- a/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php
+++ b/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php
@@ -2,8 +2,10 @@
declare(strict_types=1);
+use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\SocialPublishException;
+use App\Exceptions\TokenExpiredException;
// Concrete implementation for testing the abstract class
class TestPlatformException extends SocialPublishException
@@ -56,6 +58,31 @@ test('context returns null for optional fields when not provided', function () {
]);
});
+test('platform unavailable context includes http status and checkpoint keys', function () {
+ $exception = new PlatformUnavailableException(
+ message: 'TikTok is still processing publish_id pub_stuck',
+ httpStatus: 503,
+ context: [
+ 'tiktok_publish_id' => 'pub_stuck',
+ 'tiktok_status' => 'PROCESSING_DOWNLOAD',
+ ],
+ );
+
+ expect($exception->context())->toBe([
+ 'http_status' => 503,
+ 'tiktok_publish_id' => 'pub_stuck',
+ 'tiktok_status' => 'PROCESSING_DOWNLOAD',
+ ]);
+});
+
+test('token expired context includes the platform error code', function () {
+ $exception = new TokenExpiredException('Token expired', '190');
+
+ expect($exception->context())->toBe([
+ 'platform_error_code' => '190',
+ ]);
+});
+
test('exception message matches user message', function () {
$exception = new TestPlatformException(
userMessage: 'Rate limit exceeded.',
diff --git a/tests/Unit/Support/Social/PublishCheckpointTest.php b/tests/Unit/Support/Social/PublishCheckpointTest.php
index 3c154fe80..b650ffd4c 100644
--- a/tests/Unit/Support/Social/PublishCheckpointTest.php
+++ b/tests/Unit/Support/Social/PublishCheckpointTest.php
@@ -20,6 +20,14 @@ test('tiktokDerivativePaths returns an array or an empty list', function () {
->and(PublishCheckpoint::tiktokDerivativePaths(null))->toBe([]);
});
+test('tiktokStatus reads a non-empty status', function () {
+ expect(PublishCheckpoint::tiktokStatus([
+ PublishCheckpoint::TIKTOK_STATUS => 'PROCESSING_DOWNLOAD',
+ ]))->toBe('PROCESSING_DOWNLOAD')
+ ->and(PublishCheckpoint::tiktokStatus(['tiktok_status' => '']))->toBeNull()
+ ->and(PublishCheckpoint::tiktokStatus(null))->toBeNull();
+});
+
test('instagramWorkflow returns a non-empty array when present', function () {
$workflow = ['stage' => 'final_container', 'container_id' => 'c1'];
@@ -29,3 +37,11 @@ test('instagramWorkflow returns a non-empty array when present', function () {
->and(PublishCheckpoint::instagramWorkflow(['instagram_workflow' => []]))->toBeNull()
->and(PublishCheckpoint::instagramWorkflow(null))->toBeNull();
});
+
+test('instagramStatus reads a non-empty status', function () {
+ expect(PublishCheckpoint::instagramStatus([
+ PublishCheckpoint::INSTAGRAM_STATUS => 'IN_PROGRESS',
+ ]))->toBe('IN_PROGRESS')
+ ->and(PublishCheckpoint::instagramStatus(['instagram_status' => '']))->toBeNull()
+ ->and(PublishCheckpoint::instagramStatus(null))->toBeNull();
+});