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
Fix the production errors reported in Nightwatch (#390)
Paulo Castellano1f114d46c4f4
diff --git a/app/Enums/X/MediaProcessingState.php b/app/Enums/X/MediaProcessingState.phpnew file mode 100644index 000000000..bfbe6b7f9--- /dev/null+++ b/app/Enums/X/MediaProcessingState.php@@ -0,0 +1,23 @@+<?php++declare(strict_types=1);++namespace App\Enums\X;++/**+ * Media upload `processing_info.state` values.+ *+ * @see https://docs.x.com/x-api/media/media-upload-status+ */+enum MediaProcessingState: string+{+ case Pending = 'pending';+ case InProgress = 'in_progress';+ case Succeeded = 'succeeded';+ case Failed = 'failed';++ public function isProcessing(): bool+ {+ return $this === self::Pending || $this === self::InProgress;+ }+}diff --git a/app/Exceptions/Social/ContentLimitException.php b/app/Exceptions/Social/ContentLimitException.phpnew file mode 100644index 000000000..64d45c382--- /dev/null+++ b/app/Exceptions/Social/ContentLimitException.php@@ -0,0 +1,45 @@+<?php++declare(strict_types=1);++namespace App\Exceptions\Social;++use App\Enums\SocialAccount\Platform;+use LogicException;++/**+ * The post (or a thread reply) does not fit the target account's limit at+ * publish time. Raised before any request, so it never wraps a response.+ */+final class ContentLimitException extends SocialPublishException+{+ public function __construct(+ public readonly Platform $target,+ string $userMessage,+ ) {+ parent::__construct(+ userMessage: $userMessage,+ category: ErrorCategory::ContentPolicy,+ platformErrorCode: 'content_too_long',+ );+ }++ public static function exceeds(Platform $platform, int $max, int $provided): self+ {+ return new self($platform, __('posts.errors.content_too_long', [+ 'platform' => $platform->label(),+ 'max' => $max,+ 'provided' => $provided,+ ]));+ }++ public static function fromApiResponse(mixed $response): static+ {+ throw new LogicException('A content limit is measured before any request is sent.');+ }++ public function platform(): string+ {+ return $this->target->value;+ }+}diff --git a/app/Exceptions/Social/DiscordPublishException.php b/app/Exceptions/Social/DiscordPublishException.phpindex 3aac85d07..424075bee 100644--- a/app/Exceptions/Social/DiscordPublishException.php+++ b/app/Exceptions/Social/DiscordPublishException.php@@ -18,12 +18,12 @@ class DiscordPublishException extends SocialPublishException// Missing access / missing permissions: the bot can't see or post in the channel.if (in_array($code, [50001, 50013], true) || $status === 403) {- return new static(+ return (new static(userMessage: "The bot can't post in this channel. Make sure it has access and permission to send messages there.",category: ErrorCategory::Permission,platformErrorCode: (string) $code,rawResponse: $rawResponse,- );+ ))->asNetworkRejection();}// Unknown channel — it was deleted or the id is stale.@@ -38,12 +38,12 @@ class DiscordPublishException extends SocialPublishException// Attachment too large.if ($code === 40005 || $status === 413) {- return new static(+ return (new static(userMessage: "A media file exceeds Discord's upload size limit.",category: ErrorCategory::MediaFormat,platformErrorCode: (string) $code,rawResponse: $rawResponse,- );+ ))->asNetworkRejectionIf($code === 40005);}// 401: the configured bot token is invalid (operator-level misconfiguration).diff --git a/app/Exceptions/Social/ErrorCategory.php b/app/Exceptions/Social/ErrorCategory.phpindex fa36c0396..f166d7e8b 100644--- a/app/Exceptions/Social/ErrorCategory.php+++ b/app/Exceptions/Social/ErrorCategory.php@@ -25,6 +25,14 @@ enum ErrorCategory: string};}+ public function needsUserAction(): bool+ {+ return match ($this) {+ self::MediaFormat, self::RateLimit, self::Permission, self::ContentPolicy => true,+ default => false,+ };+ }+/*** @param array<string, mixed>|null $context*/diff --git a/app/Exceptions/Social/FacebookPublishException.php b/app/Exceptions/Social/FacebookPublishException.phpindex 24425b18f..f9ce485e8 100644--- a/app/Exceptions/Social/FacebookPublishException.php+++ b/app/Exceptions/Social/FacebookPublishException.php@@ -4,7 +4,9 @@ declare(strict_types=1);namespace App\Exceptions\Social;+use App\Enums\SocialAccount\Platform;use App\Exceptions\TokenExpiredException;+use App\Services\Social\Meta\GraphError;use Illuminate\Http\Client\Response;class FacebookPublishException extends SocialPublishException@@ -23,6 +25,24 @@ class FacebookPublishException extends SocialPublishException*/private const string FACEBOOK_URL_SUBCODE = '1609008';+ /**+ * Graph codes the Video API error reference documents as the Page's own+ * file (size, length, format) plus the duplicate post and the account's+ * own limits. 6000 ("retry and report bug", and what finishing an empty+ * session of ours returns), 1363042 (fixed with a valid token), the+ * upload-session failures, "no video file" (our request), editing a video+ * (ours), every code missing from Meta's references and the app-level+ * limits 4, 32, 341 and 613 stay reported.+ *+ * @see https://developers.facebook.com/documentation/video-api/reference/error-codes+ *+ * @var list<int>+ */+ private const array USER_REJECTION_CODES = [+ 1363023, 1363022, 1363031, 1363032, 1363024, 1363025, 1363026, 506,+ ...GraphError::ACCOUNT_RATE_LIMIT_CODES,+ ];+public function __construct(string $userMessage,ErrorCategory $category,@@ -33,12 +53,39 @@ class FacebookPublishException extends SocialPublishExceptionparent::__construct($userMessage, $category, $platformErrorCode, $rawResponse);}+ /**+ * A resumable upload (rupload) failure Meta asks to retry: a 5xx or a+ * failure flagged retriable.+ */+ public static function isRetryableUpload(Response $response): bool+ {+ return $response->serverError()+ || data_get($response->json(), 'debug_info.retriable') === true;+ }+public static function fromApiResponse(mixed $response): static{/** @var Response $response */$body = $response->json();$rawResponse = $response->body();+ if (data_get($body, 'error') === null && filled(data_get($body, 'debug_info'))) {+ $uploadErrorType = data_get($body, 'debug_info.type');++ [$message, $category] = match ($uploadErrorType) {+ 'ProcessingFailedError' => [__('posts.errors.facebook.processing_failed'), ErrorCategory::MediaFormat],+ 'PartialRequestError', 'OffsetInvalidError' => [__('posts.errors.facebook.upload_incomplete'), ErrorCategory::ServerError],+ default => [__('posts.errors.unrecognized_error', ['platform' => Platform::Facebook->label()]), ErrorCategory::Unknown],+ };++ return new static(+ userMessage: $message,+ category: $category,+ platformErrorCode: is_string($uploadErrorType) && $uploadErrorType !== '' ? $uploadErrorType : null,+ rawResponse: $rawResponse,+ );+ }+$errorCode = data_get($body, 'error.code');$errorSubcode = data_get($body, 'error.error_subcode');$errorMessage = data_get($body, 'error.message', 'An unknown Facebook error occurred.');@@ -71,13 +118,8 @@ class FacebookPublishException extends SocialPublishException1363041 => ['Upload session expired. Please try again.', ErrorCategory::ServerError],1363021 => ['Problem during video upload. Please try again.', ErrorCategory::ServerError],1363005 => ['No permission to edit this video.', ErrorCategory::Permission],- 1363047 => ['Reel encoding issue. Please try a different video.', ErrorCategory::MediaFormat],1609008 => ['Video format not supported for Reels.', ErrorCategory::MediaFormat],- 1609010 => ['Reel encoding requirements not met.', ErrorCategory::MediaFormat],1366046 => ['Reels require a video.', ErrorCategory::ContentPolicy],- 2061006 => ['Video is too short for this format.', ErrorCategory::MediaFormat],- 1390008 => ['Caption is too long.', ErrorCategory::ContentPolicy],- 1346003 => ['Thumbnail is incompatible.', ErrorCategory::ContentPolicy],1349125 => ['Rate limit exceeded. Try again later.', ErrorCategory::RateLimit],4, 32, 341, 613, 80001 => ['Too many API calls. Please try again later.', ErrorCategory::RateLimit],17 => ['User call limit reached.', ErrorCategory::RateLimit],@@ -91,7 +133,7 @@ class FacebookPublishException extends SocialPublishExceptionplatformErrorCode: $errorCode !== null ? (string) $errorCode : null,rawResponse: $rawResponse,platformErrorSubcode: $errorSubcode !== null ? (string) $errorSubcode : null,- ))->withNetworkReset($response);+ ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($errorCode, self::USER_REJECTION_CODES, true));}/**diff --git a/app/Exceptions/Social/InstagramPublishException.php b/app/Exceptions/Social/InstagramPublishException.phpindex d60503858..a9865d636 100644--- a/app/Exceptions/Social/InstagramPublishException.php+++ b/app/Exceptions/Social/InstagramPublishException.php@@ -10,6 +10,44 @@ use Illuminate\Http\Client\Response;class InstagramPublishException extends SocialPublishException{+ private const int MEDIA_NOT_READY_SUBCODE = 2207027;++ /**+ * Subcodes Instagram documents as caused by the user's media, caption,+ * tags, cover offset, account or daily limit. 2207005 (its documented+ * fix is a permission or token), 2207023 (the media_type we send), the+ * product tag subcodes (we never send product tags) and every server+ * subcode stay reported.+ *+ * @var list<int>+ */+ private const array USER_REJECTION_SUBCODES = [+ 2207026, 2207004, 2207009, 2207057, 2207010, 2207028, 2207051,+ 2207040, 2207042, 2207050,+ ];++ /**+ * media_publish answered that the container is not publishable yet: the+ * documented action is to wait for FINISHED and publish again.+ */+ public static function isMediaNotReady(Response $response): bool+ {+ return (int) $response->json('error.error_subcode') === self::MEDIA_NOT_READY_SUBCODE;+ }++ /**+ * A documented subcode whose fix is the user's, not a wait. Instagram+ * sends some of them under Graph codes that are otherwise transient (1+ * and 4), so this is checked before retrying.+ */+ public static function isDocumentedRejection(Response $response): bool+ {+ $subcode = $response->json('error.error_subcode');+ $mapped = self::forSubcode(is_numeric($subcode) ? (int) $subcode : null);++ return $mapped !== null && $mapped[1] !== ErrorCategory::ServerError;+ }+public static function fromApiResponse(mixed $response): static{/** @var Response $response */@@ -28,7 +66,34 @@ class InstagramPublishException extends SocialPublishException);}- [$message, $category] = match ($errorSubcode) {+ $subcode = is_numeric($errorSubcode) ? (int) $errorSubcode : null;+ $mapped = self::forSubcode($subcode);++ [$message, $category] = $mapped+ ?? (in_array($errorCode, GraphError::RATE_LIMIT_CODES, true)+ ? ['Too many API calls. Please try again later.', ErrorCategory::RateLimit]+ : [$errorUserMsg ?? $errorMessage, ErrorCategory::Unknown]);++ $causedByUser = $mapped !== null+ ? in_array($subcode, self::USER_REJECTION_SUBCODES, true)+ : in_array($errorCode, GraphError::ACCOUNT_RATE_LIMIT_CODES, true);++ return (new static(+ userMessage: $message,+ category: $category,+ platformErrorCode: $errorSubcode !== null ? (string) $errorSubcode : ($category === ErrorCategory::RateLimit && $errorCode !== null ? (string) $errorCode : null),+ rawResponse: $rawResponse,+ ))->withNetworkReset($response)->asNetworkRejectionIf($causedByUser);+ }++ /**+ * The user message and category Instagram's documented error subcodes map to.+ *+ * @return array{string, ErrorCategory}|null+ */+ private static function forSubcode(?int $subcode): ?array+ {+ return match ($subcode) {2207026 => ['Unsupported video format. Please upload MP4 or MOV.', ErrorCategory::MediaFormat],2207005 => ['Unsupported image format.', ErrorCategory::MediaFormat],2207004 => ['Image is too large (max 8MB).', ErrorCategory::MediaFormat],@@ -53,18 +118,25 @@ class InstagramPublishException extends SocialPublishException2207040 => ['Too many tags (max 20).', ErrorCategory::ContentPolicy],2207042 => ['Daily publishing limit reached. Please try again tomorrow.', ErrorCategory::RateLimit],2207050 => ['Instagram account is restricted or inactive. Please check the Instagram app.', ErrorCategory::Permission],- 2207081 => ["This account doesn't support Trial Reels.", ErrorCategory::Permission],- default => in_array($errorCode, GraphError::RATE_LIMIT_CODES, true)- ? ['Too many API calls. Please try again later.', ErrorCategory::RateLimit]- : [$errorUserMsg ?? $errorMessage, ErrorCategory::Unknown],+ default => null,};+ }- return (new static(- userMessage: $message,- category: $category,- platformErrorCode: $errorSubcode !== null ? (string) $errorSubcode : ($category === ErrorCategory::RateLimit && $errorCode !== null ? (string) $errorCode : null),+ /**+ * A container that reached status_code ERROR. Only a status that is a+ * bare error subcode is mapped; any other status is free text.+ */+ public static function fromContainerStatus(mixed $status, ?string $rawResponse): self+ {+ $subcode = is_int($status) || (is_string($status) && ctype_digit(trim($status))) ? (int) $status : null;+ $mapped = self::forSubcode($subcode);++ return (new self(+ userMessage: $mapped[0] ?? __('posts.errors.instagram.processing_failed'),+ category: $mapped[1] ?? ErrorCategory::Unknown,+ platformErrorCode: $subcode !== null ? (string) $subcode : null,rawResponse: $rawResponse,- ))->withNetworkReset($response);+ ))->asNetworkRejectionIf(in_array($subcode, self::USER_REJECTION_SUBCODES, true));}public function platform(): stringdiff --git a/app/Exceptions/Social/LinkedInPublishException.php b/app/Exceptions/Social/LinkedInPublishException.phpindex bbcd4d208..60220e4df 100644--- a/app/Exceptions/Social/LinkedInPublishException.php+++ b/app/Exceptions/Social/LinkedInPublishException.php@@ -4,11 +4,22 @@ declare(strict_types=1);namespace App\Exceptions\Social;+use App\Enums\SocialAccount\Platform;use App\Exceptions\TokenExpiredException;use Illuminate\Http\Client\Response;class LinkedInPublishException extends SocialPublishException{+ /**+ * Statuses LinkedIn documents as caused by the member: 403 ACCESS_DENIED+ * is the scope the member granted or their company page role. 422+ * (semantic errors in the fields we send) and 429 (member or+ * application limits) stay reported.+ *+ * @var list<int>+ */+ private const array USER_REJECTION_STATUSES = [403];+public static function fromApiResponse(mixed $response): static{/** @var Response $response */@@ -25,45 +36,36 @@ class LinkedInPublishException extends SocialPublishException);}- if (str_contains((string) $rawResponse, 'Unable to obtain activity')) {- return new static(- userMessage: 'LinkedIn server error. Please try again.',- category: ErrorCategory::ServerError,+ if ($statusCode === 429) {+ return (new static(+ userMessage: 'LinkedIn rate limit reached. Please try again later.',+ category: ErrorCategory::RateLimit,platformErrorCode: (string) $statusCode,rawResponse: $rawResponse,- );+ ))->withNetworkReset($response);}- if (str_contains((string) $rawResponse, 'resource is forbidden')) {+ if ($response->serverError()) {return new static(- userMessage: 'Not authorized to post to this account.',- category: ErrorCategory::Permission,+ userMessage: __('posts.errors.linkedin.server_error'),+ category: ErrorCategory::ServerError,platformErrorCode: (string) $statusCode,rawResponse: $rawResponse,);}- if ($statusCode === 429) {- return (new static(- userMessage: 'LinkedIn rate limit reached. Please try again later.',- category: ErrorCategory::RateLimit,- platformErrorCode: (string) $statusCode,- rawResponse: $rawResponse,- ))->withNetworkReset($response);- }-[$message, $category] = match ($statusCode) {403 => ['Not authorized to post to this account.', ErrorCategory::Permission],422 => ['Invalid post data. Please check your content.', ErrorCategory::ContentPolicy],- default => [$errorMessage ?? 'An unknown LinkedIn error occurred.', ErrorCategory::Unknown],+ default => [self::providerMessage($response, 'message') ?? __('posts.errors.unrecognized_error', ['platform' => Platform::LinkedIn->label()]), ErrorCategory::Unknown],};- return new static(+ return (new static(userMessage: $message,category: $category,platformErrorCode: (string) $statusCode,rawResponse: $rawResponse,- );+ ))->asNetworkRejectionIf(in_array($statusCode, self::USER_REJECTION_STATUSES, true));}public function platform(): stringdiff --git a/app/Exceptions/Social/MastodonPublishException.php b/app/Exceptions/Social/MastodonPublishException.phpindex b6e85e0a6..b98b7ddec 100644--- a/app/Exceptions/Social/MastodonPublishException.php+++ b/app/Exceptions/Social/MastodonPublishException.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Exceptions\Social;+use App\Enums\SocialAccount\Platform;use App\Exceptions\TokenExpiredException;use Illuminate\Http\Client\Response;@@ -45,8 +46,8 @@ class MastodonPublishException extends SocialPublishExceptionif ($status === 422) {return new static(- userMessage: 'Media validation failed.',- category: ErrorCategory::MediaFormat,+ userMessage: self::providerMessage($response, 'error') ?? __('posts.errors.unrecognized_error', ['platform' => Platform::Mastodon->label()]),+ category: ErrorCategory::Unknown,platformErrorCode: (string) $status,rawResponse: $rawResponse,);diff --git a/app/Exceptions/Social/PinterestPublishException.php b/app/Exceptions/Social/PinterestPublishException.phpindex b1e26ee8f..14fae8e94 100644--- a/app/Exceptions/Social/PinterestPublishException.php+++ b/app/Exceptions/Social/PinterestPublishException.php@@ -24,12 +24,12 @@ class PinterestPublishException extends SocialPublishException}if ($status === 403) {- return new static(+ return (new static(userMessage: 'Not authorized to create pins on this board.',category: ErrorCategory::Permission,platformErrorCode: (string) $status,rawResponse: $rawResponse,- );+ ))->asNetworkRejection();}if ($status === 429) {@@ -96,12 +96,12 @@ class PinterestPublishException extends SocialPublishExceptionpublic static function fromProcessingStatus(string $status, ?string $rawResponse = null): static{if ($status === 'failed') {- return new static(+ return (new static(userMessage: 'Media processing failed. Please try a different file.',category: ErrorCategory::MediaFormat,platformErrorCode: null,rawResponse: $rawResponse,- );+ ))->asNetworkRejection();}return new static(diff --git a/app/Exceptions/Social/SocialPublishException.php b/app/Exceptions/Social/SocialPublishException.phpindex 0e7ac91c8..dc32e107c 100644--- a/app/Exceptions/Social/SocialPublishException.php+++ b/app/Exceptions/Social/SocialPublishException.php@@ -17,6 +17,8 @@ abstract class SocialPublishException extends RuntimeException*/public ?CarbonInterface $retryAt = null;+ private bool $rejectedByNetwork = false;+public function __construct(public readonly string $userMessage,public readonly ErrorCategory $category,@@ -45,6 +47,33 @@ abstract class SocialPublishException extends RuntimeExceptionreturn $this->category === ErrorCategory::RateLimit;}+ /**+ * Set by a provider mapper on a documented rejection code: the network+ * refused the post and only the user can fix it. Our own failures+ * (downloads, storage, configuration, invariants) are never marked.+ */+ public function asNetworkRejection(): static+ {+ return $this->asNetworkRejectionIf(true);+ }++ /**+ * Marks the exception only when the mapper lists its documented code as+ * caused by the user's own content, media, account or grants. A code+ * caused by our app, request or credentials stays reported.+ */+ public function asNetworkRejectionIf(bool $causedByUser): static+ {+ $this->rejectedByNetwork = $causedByUser && $this->category->needsUserAction();++ return $this;+ }++ public function isNetworkRejection(): bool+ {+ return $this->rejectedByNetwork;+ }+/*** Reads the network's reset time from a limit refusal.*/@@ -57,6 +86,36 @@ abstract class SocialPublishException extends RuntimeExceptionreturn $this;}+ /**+ * The provider's own explanation for an error we do not map, read from+ * its documented message fields in order. Display only: never classify+ * by it. A 5xx body is never shown.+ */+ protected static function providerMessage(Response $response, string ...$paths): ?string+ {+ if ($response->serverError()) {+ return null;+ }++ foreach ($paths as $path) {+ $message = self::filledMessage(data_get($response->json(), $path));++ if ($message !== null) {+ return $message;+ }+ }++ return null;+ }++ /**+ * A provider message worth showing: a string with text in it.+ */+ protected static function filledMessage(mixed $message): ?string+ {+ return is_string($message) && filled($message) ? $message : null;+ }+abstract public static function fromApiResponse(mixed $response): static;abstract public function platform(): string;diff --git a/app/Exceptions/Social/ThreadsPublishException.php b/app/Exceptions/Social/ThreadsPublishException.phpindex 2daad6ec5..8644cd101 100644--- a/app/Exceptions/Social/ThreadsPublishException.php+++ b/app/Exceptions/Social/ThreadsPublishException.php@@ -42,7 +42,7 @@ class ThreadsPublishException extends SocialPublishExceptioncategory: ErrorCategory::RateLimit,platformErrorCode: (string) $statusCode,rawResponse: $rawResponse,- ))->withNetworkReset($response);+ ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($errorCode, GraphError::ACCOUNT_RATE_LIMIT_CODES, true));}if ($statusCode >= 500) {diff --git a/app/Exceptions/Social/TikTokPublishException.php b/app/Exceptions/Social/TikTokPublishException.phpindex 7f61c9e63..dcad7eab7 100644--- a/app/Exceptions/Social/TikTokPublishException.php+++ b/app/Exceptions/Social/TikTokPublishException.php@@ -9,6 +9,43 @@ use Illuminate\Http\Client\Response;class TikTokPublishException extends SocialPublishException{+ /**+ * Error codes TikTok documents as caused by the creator's grants, file or+ * account limits. rate_limit_exceeded is per user access_token. App+ * audit, domain verification, the client's active user cap, invalid+ * params, privacy options we must honor and the MEDIA_UPLOAD app version+ * check (we only send DIRECT_POST) stay reported.+ *+ * @var list<string>+ */+ private const array USER_REJECTION_CODES = [+ 'scope_not_authorized',+ 'scope_permission_missed',+ 'rate_limit_exceeded',+ 'invalid_file_upload',+ 'spam_risk_too_many_posts',+ 'spam_risk_too_many_pending_share',+ 'spam_risk_user_banned_from_posting',+ ];++ /**+ * Post status fail reasons caused by the creator's media, text or account.+ * publish_cancelled (a developer cancel) and spam_risk (a request flagged+ * without naming the cause) stay reported.+ *+ * @var list<string>+ */+ private const array USER_FAIL_REASONS = [+ 'file_format_check_failed',+ 'duration_check_failed',+ 'frame_rate_check_failed',+ 'picture_size_check_failed',+ 'auth_removed',+ 'spam_risk_too_many_posts',+ 'spam_risk_user_banned_from_posting',+ 'spam_risk_text',+ ];+public static function fromApiResponse(mixed $response): static{/** @var Response $response */@@ -49,7 +86,7 @@ class TikTokPublishException extends SocialPublishExceptioncategory: $category,platformErrorCode: $errorCode !== null ? (string) $errorCode : null,rawResponse: $rawResponse,- ))->withNetworkReset($response);+ ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($errorCode, self::USER_REJECTION_CODES, true));}public static function fromFailReason(string $failReason, ?string $rawResponse = null): static@@ -71,12 +108,12 @@ class TikTokPublishException extends SocialPublishExceptiondefault => [$failReason, ErrorCategory::Unknown],};- return new static(+ return (new static(userMessage: $message,category: $category,platformErrorCode: $failReason,rawResponse: $rawResponse,- );+ ))->asNetworkRejectionIf(in_array($failReason, self::USER_FAIL_REASONS, true));}public function platform(): stringdiff --git a/app/Exceptions/Social/XPublishException.php b/app/Exceptions/Social/XPublishException.phpindex c67eee54e..c066d447f 100644--- a/app/Exceptions/Social/XPublishException.php+++ b/app/Exceptions/Social/XPublishException.php@@ -4,11 +4,23 @@ declare(strict_types=1);namespace App\Exceptions\Social;+use App\Enums\SocialAccount\Platform;use App\Exceptions\TokenExpiredException;use Illuminate\Http\Client\Response;class XPublishException extends SocialPublishException{+ /**+ * Problem types X documents as caused by the account itself:+ * not-authorized-for-resource is "No access to private/protected+ * content". invalid-request (our request), resource-not-found (an id we+ * sent), client-forbidden (our app's enrollment), usage-capped (our app's+ * cap) and rate-limit-exceeded (per user or per app) stay reported.+ *+ * @var list<string>+ */+ private const array USER_REJECTION_TYPES = ['not-authorized-for-resource'];+public static function fromApiResponse(mixed $response): static{/** @var Response $response */@@ -29,50 +41,6 @@ class XPublishException extends SocialPublishException);}- if (str_contains((string) $rawResponse, 'invalid URL')) {- return new static(- userMessage: 'Post contains an invalid URL.',- category: ErrorCategory::ContentPolicy,- platformErrorCode: $typeSuffix ?: null,- rawResponse: $rawResponse,- );- }-- if (str_contains((string) $rawResponse, 'video longer than 2 minutes')) {- return new static(- userMessage: 'Video exceeds the 2-minute limit.',- category: ErrorCategory::MediaFormat,- platformErrorCode: $typeSuffix ?: null,- rawResponse: $rawResponse,- );- }-- $firstErrorMessage = (string) data_get($body, 'errors.0.message', '');-- if (- str_contains((string) $rawResponse, 'media IDs are invalid')- || str_contains($firstErrorMessage, 'media IDs are invalid')- ) {- return new static(- userMessage: 'X rejected the attached media. Please re-upload and try again.',- category: ErrorCategory::MediaFormat,- platformErrorCode: $typeSuffix ?: null,- rawResponse: $rawResponse,- );- }-- if (- str_contains((string) $rawResponse, 'Request body must be a JSON object')- || str_contains($firstErrorMessage, 'Request body must be a JSON object')- ) {- return new static(- userMessage: 'X rejected the media upload request. Please try again.',- category: ErrorCategory::ServerError,- platformErrorCode: $typeSuffix ?: null,- rawResponse: $rawResponse,- );- }-if ($statusCode === 413) {return new static(userMessage: 'Media chunk rejected by X (payload too large).',@@ -107,7 +75,7 @@ class XPublishException extends SocialPublishException'client-forbidden' => ['App not enrolled or lacks required access.', ErrorCategory::Permission],'not-authorized-for-resource' => ['Not authorized for this resource.', ErrorCategory::Permission],'resource-not-found' => ['Resource not found.', ErrorCategory::ContentPolicy],- default => [$detail ?: $title ?: 'An unknown X error occurred.', ErrorCategory::Unknown],+ default => [self::providerMessage($response, 'detail', 'title') ?? __('posts.errors.unrecognized_error', ['platform' => Platform::X->label()]), ErrorCategory::Unknown],};return (new static(@@ -115,7 +83,7 @@ class XPublishException extends SocialPublishExceptioncategory: $category,platformErrorCode: $typeSuffix ?: null,rawResponse: $rawResponse,- ))->withNetworkReset($response);+ ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($typeSuffix, self::USER_REJECTION_TYPES, true));}public function platform(): stringdiff --git a/app/Exceptions/Social/YouTubePublishException.php b/app/Exceptions/Social/YouTubePublishException.phpindex 715b6d102..c225c2d8e 100644--- a/app/Exceptions/Social/YouTubePublishException.php+++ b/app/Exceptions/Social/YouTubePublishException.php@@ -4,12 +4,42 @@ declare(strict_types=1);namespace App\Exceptions\Social;+use App\Enums\SocialAccount\Platform;use App\Exceptions\TokenExpiredException;use Google\Service\Exception as GoogleServiceException;use Illuminate\Http\Client\Response;class YouTubePublishException extends SocialPublishException{+ /** @var list<string> */+ private const array SERVER_ERROR_REASONS = ['backendError', 'internalError'];++ /**+ * The statuses the resumable upload guide says to retry. A 501 or any+ * other 5xx is permanent, so retrying it only uploads the video again.+ *+ * @see https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol+ *+ * @var list<int>+ */+ private const array RETRYABLE_SERVER_STATUSES = [500, 502, 503, 504];++ /**+ * Reasons YouTube documents as caused by the user's title, description+ * or channel limits. Metadata we build or never send (category, tags,+ * publishAt, recording details, game rating, filename, media body), the+ * license and privacy values we send, an undescribed `forbidden`,+ * failedPrecondition and the project quota and rate limits stay reported.+ *+ * @var list<string>+ */+ private const array USER_REJECTION_REASONS = [+ 'invalidTitle',+ 'invalidDescription',+ 'uploadLimitExceeded',+ 'uploadRateLimitExceeded',+ ];+public static function fromApiResponse(mixed $response): static{/** @var Response $response */@@ -26,17 +56,14 @@ class YouTubePublishException extends SocialPublishException);}- [$message, $category] = self::mapReasonToMessageAndCategory(- reason: $reason,- fallbackMessage: $fallbackMessage,- );+ [$message, $category] = self::mapReasonToMessageAndCategory($reason, self::providerMessage($response, 'error.message'));return (new static(userMessage: $message,category: $category,platformErrorCode: $reason,rawResponse: $rawResponse,- ))->withNetworkReset($response);+ ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($reason, self::USER_REJECTION_REASONS, true));}public static function fromGoogleException(GoogleServiceException $e): static@@ -52,17 +79,31 @@ class YouTubePublishException extends SocialPublishException);}+ if (self::isServerError($e)) {+ return new static(+ userMessage: __('posts.errors.youtube.upload_unconfirmed'),+ category: ErrorCategory::ServerError,+ platformErrorCode: $reason ?? (string) $e->getCode(),+ rawResponse: $e->getMessage(),+ );+ }+[$message, $category] = self::mapReasonToMessageAndCategory(- reason: $reason,- fallbackMessage: $rawMessage,+ $reason,+ self::filledMessage(data_get($errors, '0.message')),);- return new static(+ return (new static(userMessage: $message,category: $category,platformErrorCode: $reason,rawResponse: $e->getMessage(),- );+ ))->asNetworkRejectionIf(in_array($reason, self::USER_REJECTION_REASONS, true));+ }++ public static function isServerError(GoogleServiceException $e): bool+ {+ return in_array($e->getCode(), self::RETRYABLE_SERVER_STATUSES, true) || in_array(data_get($e->getErrors(), '0.reason'), self::SERVER_ERROR_REASONS, true);}public function platform(): string@@ -84,7 +125,7 @@ class YouTubePublishException extends SocialPublishException/*** @return array{string, ErrorCategory}*/- private static function mapReasonToMessageAndCategory(?string $reason, string $fallbackMessage): array+ private static function mapReasonToMessageAndCategory(?string $reason, ?string $providerMessage): array{return match ($reason) {'invalidTitle' => ['Video title is invalid or empty.', ErrorCategory::ContentPolicy],@@ -104,7 +145,7 @@ class YouTubePublishException extends SocialPublishException'forbidden' => ["You don't have permission to upload to this channel.", ErrorCategory::Permission],'forbiddenLicenseSetting' => ['Invalid video license setting.', ErrorCategory::Permission],'forbiddenPrivacySetting' => ['Invalid video privacy setting.', ErrorCategory::Permission],- default => [$fallbackMessage, ErrorCategory::Unknown],+ default => [$providerMessage ?? __('posts.errors.unrecognized_error', ['platform' => Platform::YouTube->label()]), ErrorCategory::Unknown],};}}diff --git a/app/Jobs/Analytics/AbstractPublicationSync.php b/app/Jobs/Analytics/AbstractPublicationSync.phpindex 86f17923f..b23d16ab4 100644--- a/app/Jobs/Analytics/AbstractPublicationSync.php+++ b/app/Jobs/Analytics/AbstractPublicationSync.php@@ -16,9 +16,11 @@ use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Publications\PublicationHistoryCollectorFactory;use App\Support\Analytics\AnalyticsJobLog;use App\Support\Analytics\AnalyticsRateLimits;+use Carbon\CarbonImmutable;use Illuminate\Cache\RateLimiting\Limit;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Queue\Middleware\RateLimited;use Illuminate\Queue\Middleware\WithoutOverlapping;use Throwable;@@ -33,10 +35,16 @@ abstract class AbstractPublicationSync implements ShouldQueuepublic int $timeout = 180;+ private const int MAX_TRANSIENT_RETRIES = 5;++ public int $transientRetries = 0;+public function __construct(public string $socialAccountId,public string $syncStateId,+ int $transientRetries = 0,) {+ $this->transientRetries = $transientRetries;$this->onQueue('analytics');}@@ -98,20 +106,18 @@ abstract class AbstractPublicationSync implements ShouldQueue$page = $collectors->for($account)->page($account, $capture['cursor'], $capture['cutoff']);$result = $sync->handle($this->syncStateId, $capture['revision'], $account, $page);} catch (AnalyticsCollectionException $exception) {- $log->record($account, $collector, $cursorLabel, $this->attempts(), $exception->category);-if ($exception->category === 'invalid_cursor') {+ $log->record($account, $collector, $cursorLabel, $this->attempts(), $exception->category);$this->handleInvalidCursor($sync, $account, $capture['revision']);return;}- $transient = in_array($exception->category, ['transient', 'rate_limited'], true);- $sync->recordFailure($this->syncStateId, $capture['revision'], $exception->category, ! $transient, $account->id);+ $this->recordFailure($sync, $log, $account, $capture['revision'], $cursorLabel, $exception->category, $exception->retryAt);- if ($transient) {- throw $exception;- }+ return;+ } catch (ConnectionException) {+ $this->recordFailure($sync, $log, $account, $capture['revision'], $cursorLabel, 'transient', null);return;}@@ -144,6 +150,42 @@ abstract class AbstractPublicationSync implements ShouldQueue}}+ private function recordFailure(+ AdvanceAnalyticsSyncState $sync,+ AnalyticsJobLog $log,+ SocialAccount $account,+ int $revision,+ string $cursorLabel,+ string $category,+ ?CarbonImmutable $providerRetryAt,+ ): void {+ $collector = $this->collector()->value;+ $transient = in_array($category, ['transient', 'rate_limited'], true);++ if (! $transient || $this->transientRetries >= self::MAX_TRANSIENT_RETRIES) {+ $sync->recordFailure($this->syncStateId, $revision, $transient ? 'queue_failed' : $category, true, $account->id);+ $log->record($account, $collector, $cursorLabel, $this->attempts(), $category);++ return;+ }++ $sync->recordFailure($this->syncStateId, $revision, $category, false, $account->id);++ $delay = $this->transientDelaySeconds($providerRetryAt);+ $log->record($account, $collector, $cursorLabel, $this->attempts(), $category, CarbonImmutable::now('UTC')->addSeconds($delay)->toIso8601String());+ static::dispatch($account->id, $this->syncStateId, $this->transientRetries + 1)->delay($delay);+ }++ private function transientDelaySeconds(?CarbonImmutable $providerRetryAt): int+ {+ $backoff = $this->backoff();+ $delay = $backoff[min($this->transientRetries, count($backoff) - 1)];+ $now = CarbonImmutable::now('UTC');+ $providerDelay = $providerRetryAt ? (int) ceil($now->diffInSeconds($providerRetryAt->min($now->endOfDay()), false)) : 0;++ return max($delay, $providerDelay);+ }+protected function mayStart(SocialAccount $account): bool{return true;diff --git a/app/Jobs/PublishToSocialPlatform.php b/app/Jobs/PublishToSocialPlatform.phpindex ae0882b67..cdeef1867 100644--- a/app/Jobs/PublishToSocialPlatform.php+++ b/app/Jobs/PublishToSocialPlatform.php@@ -290,21 +290,19 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueueprivate function rescheduleForRetry(PlatformUnavailableException $e): void{- $retryCount = (int) data_get($this->postPlatform->error_context, 'retry_count', 0) + 1;- $maxRetries = (int) ($e->maxRetries- ?? data_get($this->postPlatform->error_context, 'max_retries')- ?? self::MAX_PLATFORM_UNAVAILABLE_RETRIES);- $retryDelaySeconds = (int) ($e->retryDelaySeconds- ?? data_get($this->postPlatform->error_context, 'retry_delay_seconds')- ?? self::DEFAULT_RETRY_DELAY_SECONDS);+ $previousContext = self::withSeparateRetryCounters($this->postPlatform->error_context ?? []);+ $hasOwnPolicy = $e->maxRetries !== null || $e->retryDelaySeconds !== null;+ $counterKey = $hasOwnPolicy ? 'processing_retry_count' : 'retry_count';+ $retryCount = (int) data_get($previousContext, $counterKey, 0) + 1;+ $maxRetries = $e->maxRetries ?? self::MAX_PLATFORM_UNAVAILABLE_RETRIES;+ $retryDelaySeconds = $e->retryDelaySeconds ?? self::DEFAULT_RETRY_DELAY_SECONDS;$context = [- ...($this->postPlatform->error_context ?? []),+ ...Arr::except($previousContext, ['max_retries', 'retry_delay_seconds']),...$e->context,'category' => ErrorCategory::PlatformUnavailable->value,'http_status' => $e->httpStatus,- 'retry_count' => $retryCount,- 'max_retries' => $maxRetries,- 'retry_delay_seconds' => $retryDelaySeconds,+ $counterKey => $retryCount,+ ...($hasOwnPolicy ? ['max_retries' => $maxRetries, 'retry_delay_seconds' => $retryDelaySeconds] : []),'detail' => $e->getMessage(),];@@ -341,14 +339,39 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue],]);- self::dispatch($this->postPlatform, $retryCount)->delay($nextAttemptAt);+ self::dispatch(+ $this->postPlatform,+ (int) data_get($context, 'retry_count', 0) + (int) data_get($context, 'processing_retry_count', 0),+ )->delay($nextAttemptAt);+ }++ /**+ * Before TryPost 2.0 a status poll counted on `retry_count` and stored+ * `max_retries`, with no `processing_retry_count`. That count belongs to+ * the poll budget, so the outage count of such a row starts over.+ *+ * @param array<string, mixed> $context+ * @return array<string, mixed>+ */+ private static function withSeparateRetryCounters(array $context): array+ {+ if (! array_key_exists('max_retries', $context) || array_key_exists('processing_retry_count', $context)) {+ return $context;+ }++ return [+ ...$context,+ 'processing_retry_count' => (int) data_get($context, 'retry_count', 0),+ 'retry_count' => 0,+ ];}/*** A limit refusal (rate limit, posting quota, daily cap) is not a failure* yet: the target waits in Retrying until `retry_at`, when* ProcessScheduledPosts dispatches it again. A refused TikTok publish_id- * is dead, so it is dropped; thread checkpoints stay so the retry resumes.+ * is dead and X media ids expire before a long wait ends, so both are+ * dropped; thread checkpoints stay so the retry resumes.* Returns false once the retries are spent.*/private function waitForLimitRetry(SocialPublishException $e): bool@@ -372,6 +395,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueuePublishCheckpoint::TIKTOK_PUBLISH_ID,PublishCheckpoint::TIKTOK_STATUS,PublishCheckpoint::TIKTOK_DERIVATIVE_PATHS,+ PublishCheckpoint::X_MEDIA,]),'category' => ErrorCategory::RateLimit->value,'platform_error_code' => $e->platformErrorCode,@@ -394,9 +418,10 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue}/**- * 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.+ * Every caught publish failure is logged with the post/platform ids that+ * Nightwatch's exception record lacks. Only an expired token and a+ * documented network rejection the user must act on are not reported;+ * everything else can be ours, so it reaches Nightwatch.** @param array<string, mixed> $context*/@@ -413,6 +438,10 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue'media' => $this->mediaSnapshot($this->postPlatform),]);+ if ($e instanceof TokenExpiredException || ($e instanceof SocialPublishException && $e->isNetworkRejection())) {+ return;+ }+report($e);}diff --git a/app/Services/Social/AbstractLinkedInPublisher.php b/app/Services/Social/AbstractLinkedInPublisher.phpindex bd68c8cf3..3832881c2 100644--- a/app/Services/Social/AbstractLinkedInPublisher.php+++ b/app/Services/Social/AbstractLinkedInPublisher.php@@ -6,6 +6,7 @@ namespace App\Services\Social;use App\Enums\Media\Type as MediaType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\LinkedInPublishException;use App\Exceptions\TokenExpiredException;@@ -432,7 +433,7 @@ abstract class AbstractLinkedInPublisherif ($initResponse->failed()) {Log::error("{$this->label()} image init failed", ['body' => $this->redactResponseBody($initResponse->body())]);- $this->handleApiError($initResponse);+ $this->handleMediaApiError($initResponse);}$initData = $initResponse->json();@@ -466,7 +467,7 @@ abstract class AbstractLinkedInPublisherif ($uploadResponse->failed()) {Log::error("{$this->label()} image upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]);- $this->handleApiError($uploadResponse);+ $this->handleMediaApiError($uploadResponse);}return $imageUrn;@@ -501,7 +502,7 @@ abstract class AbstractLinkedInPublisherif ($initResponse->failed()) {Log::error("{$this->label()} video init failed", ['body' => $this->redactResponseBody($initResponse->body())]);- $this->handleApiError($initResponse);+ $this->handleMediaApiError($initResponse);}$initData = $initResponse->json();@@ -539,7 +540,7 @@ abstract class AbstractLinkedInPublisher'index' => $index,'body' => $this->redactResponseBody($chunkResponse->body()),]);- $this->handleApiError($chunkResponse);+ $this->handleMediaApiError($chunkResponse);}$etag = $chunkResponse->header('etag');@@ -565,7 +566,7 @@ abstract class AbstractLinkedInPublisherif ($finalizeResponse->failed()) {Log::error("{$this->label()} video finalize failed", ['body' => $this->redactResponseBody($finalizeResponse->body())]);- $this->handleApiError($finalizeResponse);+ $this->handleMediaApiError($finalizeResponse);}$this->waitForProcessing('videos', $videoUrn, 'video');@@ -582,7 +583,7 @@ abstract class AbstractLinkedInPublisherif ($initResponse->failed()) {Log::error("{$this->label()} document init failed", ['body' => $this->redactResponseBody($initResponse->body())]);- $this->handleApiError($initResponse);+ $this->handleMediaApiError($initResponse);}$initData = $initResponse->json();@@ -616,7 +617,7 @@ abstract class AbstractLinkedInPublisherif ($uploadResponse->failed()) {Log::error("{$this->label()} document upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]);- $this->handleApiError($uploadResponse);+ $this->handleMediaApiError($uploadResponse);}} finally {@unlink($tempFile);@@ -717,6 +718,22 @@ abstract class AbstractLinkedInPublisherreturn $this->platform()->label();}+ /**+ * Media steps run before the post exists, so a LinkedIn 5xx there is+ * safe to retry; anything else is classified like a post failure.+ */+ private function handleMediaApiError(Response $response): never+ {+ if ($response->serverError()) {+ throw new PlatformUnavailableException(+ "{$this->label()} returned {$response->status()} while uploading media",+ $response->status(),+ );+ }++ $this->handleApiError($response);+ }+private function handleApiError(Response $response): never{throw LinkedInPublishException::fromApiResponse($response);diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.phpindex 7c8882853..e7e04628a 100644--- a/app/Services/Social/BlueskyPublisher.php+++ b/app/Services/Social/BlueskyPublisher.php@@ -8,6 +8,7 @@ use App\Dto\MediaItem;use App\Enums\Media\Type as MediaType;use App\Enums\SocialAccount\Platform;use App\Exceptions\Social\BlueskyPublishException;+use App\Exceptions\Social\ErrorCategory;use App\Models\PostPlatform;use App\Models\SocialAccount;use App\Services\Http\SafeHttpFetcher;@@ -44,7 +45,7 @@ class BlueskyPublisher/** Poll getJobStatus up to this many times before timing out. */private const VIDEO_POLL_MAX_ATTEMPTS = 150;- /** Wall-clock budget (seconds) for the whole upload+poll+retry flow, kept under the 600s job timeout so a stuck transcode degrades to text instead of being killed mid-flight. */+ /** Wall-clock budget (seconds) for the whole upload+poll+retry flow before media preparation fails. */private const VIDEO_PROCESSING_BUDGET = 420;private const JOB_STATE_COMPLETED = 'JOB_STATE_COMPLETED';@@ -171,12 +172,17 @@ class BlueskyPublisherforeach ($medias->take(4) as $media) {if ($media->isImage()) {$blob = $this->uploadBlob($account, $service, $media->url, $media->mime_type);- if ($blob) {- $images[] = [- 'alt' => $media->altTextFor(Platform::Bluesky) ?? '',- 'image' => $blob,- ];+ if (! $blob) {+ throw new BlueskyPublishException(+ userMessage: 'Media upload to Bluesky failed. Please try again.',+ category: ErrorCategory::ServerError,+ );}++ $images[] = [+ 'alt' => $media->altTextFor(Platform::Bluesky) ?? '',+ 'image' => $blob,+ ];}}@@ -190,6 +196,13 @@ class BlueskyPublisher$video = $medias->first(fn (MediaItem $media): bool => $media->isVideo());$videoBlob = $video ? $this->uploadVideo($account, $service, $video->url, $video->mime_type) : null;+ if ($video && ! $videoBlob) {+ throw new BlueskyPublishException(+ userMessage: 'Media upload to Bluesky failed. Please try again.',+ category: ErrorCategory::ServerError,+ );+ }+return $videoBlob ? ['$type' => BlueskyLexicon::EMBED_VIDEO,'video' => $videoBlob,@@ -431,8 +444,8 @@ class BlueskyPublisher* 4. poll app.bsky.video.getJobStatus until the blob is ready,* retrying the whole upload a few times on a transient transcode failure.*- * Returns null on any failure so the post still publishes as text rather- * than crashing the whole job (mirrors uploadBlob()).+ * Returns null on failure so mediaEmbed stops publication. Only a link+ * preview thumbnail may be omitted when its upload fails.*/private function uploadVideo(SocialAccount $account, string $service, string $url, ?string $mimeType): ?array{@@ -475,8 +488,7 @@ class BlueskyPublisher// Bound the whole upload+poll+retry flow to a wall-clock budget that// stays under the queue job timeout: a stuck transcode must give up- // and let the post publish as text, not run the worker to its- // timeout (which would drop the post entirely on a $tries=1 job).+ // and fail publication instead of running the worker to its timeout.$deadline = now()->addSeconds(self::VIDEO_PROCESSING_BUDGET);// The transcoder occasionally fails a job transientlydiff --git a/app/Services/Social/Concerns/HasSocialHttpClient.php b/app/Services/Social/Concerns/HasSocialHttpClient.phpindex 20b337998..c74daf965 100644--- a/app/Services/Social/Concerns/HasSocialHttpClient.php+++ b/app/Services/Social/Concerns/HasSocialHttpClient.php@@ -4,11 +4,11 @@ declare(strict_types=1);namespace App\Services\Social\Concerns;+use App\Exceptions\Social\ContentLimitException;use App\Models\PostPlatform;use App\Services\Social\ContentSanitizer;use App\Services\Social\TokenRedactor;use App\Support\ThreadReplies;-use Exception;use Illuminate\Http\Client\PendingRequest;use Illuminate\Support\Facades\Http;@@ -36,7 +36,7 @@ trait HasSocialHttpClient$threadViolation = ThreadReplies::violation($postPlatform->socialAccount ?? $postPlatform->platform, $postPlatform->meta);if ($threadViolation !== null) {- throw new Exception($threadViolation[1]);+ throw new ContentLimitException($postPlatform->platform, $threadViolation[1]);}$reserved = $postPlatform->platform->reservedLength($postPlatform->meta);@@ -50,9 +50,7 @@ trait HasSocialHttpClient$contentLength = mb_strlen($content) + $reserved;- throw new Exception(- "Content exceeds {$postPlatform->platform->label()} limit of {$maxLength} characters ({$contentLength} provided)."- );+ throw ContentLimitException::exceeds($postPlatform->platform, $maxLength, $contentLength);}private bool $interactiveHttp = false;diff --git a/app/Services/Social/ConnectionVerifier.php b/app/Services/Social/ConnectionVerifier.phpindex 778b7f644..81ecdccff 100644--- a/app/Services/Social/ConnectionVerifier.php+++ b/app/Services/Social/ConnectionVerifier.php@@ -29,6 +29,17 @@ use Illuminate\Support\Facades\Http;class ConnectionVerifier{+ /**+ * TikTok OAuth errors that mean the refresh token itself is dead and the+ * user must reconnect: only invalid_grant ("invalid, expired, revoked")+ * is documented that way. Every other error is ours or temporary.+ *+ * @see https://developers.tiktok.com/doc/oauth-error-handling+ *+ * @var list<string>+ */+ private const array TIKTOK_DEAD_REFRESH_ERRORS = ['invalid_grant'];+/*** Read and connect timeouts for a token refresh. Stated explicitly, even* though they match the client's defaults, so a change to those cannot@@ -138,7 +149,7 @@ class ConnectionVerifierreturn blank($token) ? $current : (string) $token;}- private function tokenFrom(?array $data, Platform $platform, string $key = 'access_token'): string+ private function tokenFrom(mixed $data, Platform $platform, string $key = 'access_token'): string{$token = data_get($data, $key);@@ -399,15 +410,32 @@ class ConnectionVerifierthrow new TokenExpiredException('No refresh token available for TikTok account');}- $response = TokenRefreshClient::for(Platform::TikTok)->send(fn () => $this->refreshHttp()->asForm()- ->post(config('trypost.platforms.tiktok.api').'/oauth/token/', [- 'grant_type' => 'refresh_token',- 'refresh_token' => $account->refresh_token,- 'client_key' => config('services.tiktok.client_id'),- 'client_secret' => config('services.tiktok.client_secret'),- ]));+ $response = TokenRefreshClient::for(Platform::TikTok)->send(+ fn () => $this->refreshHttp()->asForm()+ ->post(config('trypost.platforms.tiktok.api').'/oauth/token/', [+ 'grant_type' => 'refresh_token',+ 'refresh_token' => $account->refresh_token,+ 'client_key' => config('services.tiktok.client_id'),+ 'client_secret' => config('services.tiktok.client_secret'),+ ]),+ function (mixed $body): bool {+ self::throwIfDeadTikTokRefresh($body);++ return false;+ },+ );$data = $response->json();+ self::throwIfDeadTikTokRefresh($data);++ $error = data_get($data, 'error');+ $description = self::tikTokErrorDescription($data);++ if (filled($error)) {+ $code = is_string($error) ? $error : 'unrecognized error';++ throw new PlatformUnavailableException(trim("TikTok refresh returned {$code}: {$description}", ': '));+ }$account->update(['access_token' => $this->tokenFrom($data, $account->platform),@@ -418,6 +446,33 @@ class ConnectionVerifier$account->refresh();}+ /**+ * A dead refresh token expires the account with TikTok's error code,+ * whether TikTok answered it with a 200 or a 4xx.+ *+ * @throws TokenExpiredException+ */+ private static function throwIfDeadTikTokRefresh(mixed $body): void+ {+ $error = is_array($body) ? data_get($body, 'error') : null;++ if (! in_array($error, self::TIKTOK_DEAD_REFRESH_ERRORS, true)) {+ return;+ }++ throw new TokenExpiredException(+ self::tikTokErrorDescription($body) ?? $error,+ platformErrorCode: $error,+ );+ }++ private static function tikTokErrorDescription(mixed $body): ?string+ {+ $description = data_get($body, 'error_description');++ return is_string($description) && $description !== '' ? $description : null;+ }+private function refreshPinterestToken(SocialAccount $account): void{if (! $account->refresh_token) {diff --git a/app/Services/Social/FacebookPublisher.php b/app/Services/Social/FacebookPublisher.phpindex 7c2b5099b..cc436ffbb 100644--- a/app/Services/Social/FacebookPublisher.php+++ b/app/Services/Social/FacebookPublisher.php@@ -419,6 +419,14 @@ class FacebookPublisherLog::error('Facebook video upload failed', ['body' => $this->redactResponseBody($response->body()),]);++ if (FacebookPublishException::isRetryableUpload($response)) {+ throw new PlatformUnavailableException(+ message: "Facebook video upload failed with {$response->status()}",+ httpStatus: $response->status(),+ );+ }+$this->handleApiError($response);}diff --git a/app/Services/Social/InstagramPublisher.php b/app/Services/Social/InstagramPublisher.phpindex d75f2f916..7f31c1b78 100644--- a/app/Services/Social/InstagramPublisher.php+++ b/app/Services/Social/InstagramPublisher.php@@ -31,9 +31,10 @@ class InstagramPublisherprivate PostPlatform $postPlatform;- private const int STATUS_RETRY_DELAY_SECONDS = 10;+ private const int STATUS_RETRY_DELAY_SECONDS = 60;- private const int STATUS_MAX_RETRIES = 90;+ /** Two hours of delayed retries for processing and transient Graph failures. */+ private const int STATUS_MAX_RETRIES = 120;private const string WORKFLOW_CAROUSEL_CHILDREN = 'carousel_children';@@ -384,7 +385,8 @@ class InstagramPublisher'body' => $this->redactResponseBody($publishResponse->body()),]);- if (GraphError::isTransientFailure($publishResponse)) {+ if (! InstagramPublishException::isDocumentedRejection($publishResponse)+ && (GraphError::isTransientFailure($publishResponse) || InstagramPublishException::isMediaNotReady($publishResponse))) {throw $this->pendingContainerException($containerId, $workflow, $publishResponse->status());}@@ -559,11 +561,7 @@ class InstagramPublisher'body' => $body,]);- return new InstagramPublishException(- userMessage: 'Instagram media processing failed',- category: ErrorCategory::ServerError,- rawResponse: $body,- );+ return InstagramPublishException::fromContainerStatus(data_get($response->json(), 'status'), $body);}/**@@ -581,7 +579,7 @@ class InstagramPublisher'body' => $this->redactResponseBody($response->body()),]);- if (GraphError::isTransientFailure($response)) {+ if (! InstagramPublishException::isDocumentedRejection($response) && GraphError::isTransientFailure($response)) {throw new PlatformUnavailableException(message: "Instagram {$label} creation failed transiently",httpStatus: $response->status(),diff --git a/app/Services/Social/MastodonPublisher.php b/app/Services/Social/MastodonPublisher.phpindex f9b22f99a..5259af4ec 100644--- a/app/Services/Social/MastodonPublisher.php+++ b/app/Services/Social/MastodonPublisher.php@@ -7,6 +7,8 @@ namespace App\Services\Social;use App\Dto\MediaItem;use App\Enums\Media\Type as MediaType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\MastodonPublishException;use App\Models\PostPlatform;use App\Models\SocialAccount;@@ -14,6 +16,7 @@ use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use App\Services\Social\Concerns\PublishesThreads;use App\Support\Social\ThreadProgress;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;use Illuminate\Support\Collection;use Illuminate\Support\Facades\File;@@ -69,7 +72,7 @@ class MastodonPublisher/*** Uploads up to four media and returns the status's `media_ids`, empty- * when nothing uploaded.+ * when the post has none.** @param Collection<int, MediaItem> $media* @return array{media_ids?: list<string>}@@ -79,10 +82,7 @@ class MastodonPublisher$mediaIds = [];foreach ($media->take(4) as $item) {- $mediaId = $this->uploadMedia($account, $instance, $item->url, $item->original_filename, $item->isImage() ? $item->altTextFor(Platform::Mastodon) : null);- if ($mediaId) {- $mediaIds[] = $mediaId;- }+ $mediaIds[] = $this->uploadMedia($account, $instance, $item->url, $item->original_filename, $item->isImage() ? $item->altTextFor(Platform::Mastodon) : null);}return $mediaIds === [] ? [] : ['media_ids' => $mediaIds];@@ -142,21 +142,26 @@ class MastodonPublisher];}- private function uploadMedia(SocialAccount $account, string $instance, string $url, ?string $filename, ?string $altText): ?string+ /**+ * Uploads one media item and returns its id. A failure stops the post+ * instead of publishing it without the media: a 5xx or a dropped+ * connection is retried (the status does not exist yet), anything else+ * Mastodon refused fails with its mapped error.+ */+ private function uploadMedia(SocialAccount $account, string $instance, string $url, ?string $filename, ?string $altText): string{$tempFile = tempnam(sys_get_temp_dir(), 'masto_media_');try {$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($url);- if ($downloadResponse->failed()) {- throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());- }-- if (filesize($tempFile) === 0) {- Log::error('Mastodon failed to download media', ['url' => $url]);+ if ($downloadResponse->failed() || filesize($tempFile) === 0) {+ Log::error('Mastodon failed to download media', ['url' => $url, 'status' => $downloadResponse->status()]);- return null;+ throw new MastodonPublishException(+ userMessage: __('posts.errors.media_unavailable', ['platform' => Platform::Mastodon->label()]),+ category: ErrorCategory::ServerError,+ );}// Optimize images (skip GIFs)@@ -182,10 +187,14 @@ class MastodonPublisher$request = $request->attach('description', $altText);}- $response = $request->post("{$instance}/api/v1/media");-- if (is_resource($stream)) {- fclose($stream);+ try {+ $response = $request->post("{$instance}/api/v1/media");+ } catch (ConnectionException $e) {+ throw new PlatformUnavailableException("Mastodon media upload failed to connect: {$e->getMessage()}");+ } finally {+ if (is_resource($stream)) {+ fclose($stream);+ }}if ($response->failed()) {@@ -194,19 +203,24 @@ class MastodonPublisher'body' => $this->redactResponseBody($response->body()),]);- return null;+ if ($response->serverError()) {+ throw new PlatformUnavailableException('Mastodon media upload returned a server error', $response->status());+ }++ $this->handleApiError($response);}- $data = $response->json();+ $mediaId = data_get($response->json(), 'id');- return data_get($data, 'id');- } catch (\Exception $e) {- Log::error('Mastodon media upload error', [- 'error' => $e->getMessage(),- 'url' => $url,- ]);+ if (! is_scalar($mediaId) || (string) $mediaId === '') {+ throw new MastodonPublishException(+ userMessage: __('posts.errors.unrecognized_error', ['platform' => Platform::Mastodon->label()]),+ category: ErrorCategory::Unknown,+ rawResponse: $this->redactResponseBody($response->body()),+ );+ }- return null;+ return (string) $mediaId;} finally {@unlink($tempFile);}diff --git a/app/Services/Social/Meta/GraphError.php b/app/Services/Social/Meta/GraphError.phpindex 6b3dd798b..8a0e071dc 100644--- a/app/Services/Social/Meta/GraphError.php+++ b/app/Services/Social/Meta/GraphError.php@@ -62,6 +62,16 @@ class GraphError*/public const array RATE_LIMIT_CODES = [4, 17, 32, 341, 613, 80001, 80002];+ /**+ * The limit codes Meta documents as the account's own: 17 (the user whose+ * token is used), 80001 (the Page's BUC limit) and 80002 (the Instagram+ * professional account's BUC limit). 4 and 341 are the app's, 32 is "the+ * user or the app" and 613 is an unnamed custom limit.+ *+ * @var list<int>+ */+ public const array ACCOUNT_RATE_LIMIT_CODES = [17, 80001, 80002];+/*** Whether the given Meta Graph error body is a known rate-limit or* transient upstream problem, as opposed to a confirmed rejectiondiff --git a/app/Services/Social/TokenRefreshClient.php b/app/Services/Social/TokenRefreshClient.phpindex d20839e4a..2bbabba96 100644--- a/app/Services/Social/TokenRefreshClient.php+++ b/app/Services/Social/TokenRefreshClient.php@@ -78,8 +78,8 @@ class TokenRefreshClient);}- $message = data_get($body, 'error_description')- ?? data_get($body, 'error.message')+ $message = collect([data_get($body, 'error_description'), data_get($body, 'error.message')])+ ->first(fn (mixed $candidate): bool => is_string($candidate) && $candidate !== '')?? "Failed to refresh {$name} token";throw new TokenExpiredException($message, platformErrorCode: (string) $response->status());diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.phpindex 4633ba1fe..ade2d3d8f 100644--- a/app/Services/Social/XPublisher.php+++ b/app/Services/Social/XPublisher.php@@ -7,13 +7,17 @@ namespace App\Services\Social;use App\Dto\MediaItem;use App\Enums\Media\Type as MediaType;use App\Enums\SocialAccount\Platform;+use App\Enums\X\MediaProcessingState;+use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\XPublishException;use App\Models\PostPlatform;use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use App\Services\Social\Concerns\PublishesThreads;+use App\Support\Social\PublishCheckpoint;use App\Support\Social\ThreadProgress;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response;use Illuminate\Support\Collection;@@ -32,6 +36,22 @@ class XPublisherprivate string $accessToken;+ private const int MEDIA_PROCESSING_RETRY_DELAY_SECONDS = 60;++ private const int MEDIA_PROCESSING_MAX_RETRIES = 30;++ /**+ * The longest wait between two status checks, whatever check_after_secs+ * asks for, so 20 checks stay inside the publish job's timeout. Media+ * still processing after them is rescheduled.+ */+ private const int MEDIA_STATUS_MAX_WAIT_SECONDS = 30;++ /** @var array<string, string> */+ private array $uploadedMedia = [];++ private ?string $currentMediaItemId = null;+public function __construct(){$this->baseUrl = config('trypost.platforms.x.api');@@ -50,6 +70,7 @@ class XPublisher}$this->accessToken = $account->access_token;+ $this->uploadedMedia = PublishCheckpoint::xMedia($postPlatform->error_context);$rootHash = ThreadProgress::hash((string) $content, $postPlatform->post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());@@ -104,15 +125,31 @@ class XPublisher$mediaIds = [];foreach ($media as $mediaItem) {- $uploadedMedia = $this->uploadMedia($mediaItem);-- // v2 API returns data.id, v1 returns media_id- $mediaId = data_get($uploadedMedia, 'data.id', data_get($uploadedMedia, 'media_id'));- if ($mediaId) {- // X expects media_ids as strings in the tweets payload.- $mediaIds[] = (string) $mediaId;- $this->uploadAltText((string) $mediaId, $mediaItem);+ $this->currentMediaItemId = $mediaItem->id;+ $mediaId = $this->uploadedMedia[$mediaItem->id] ?? null;++ if ($mediaId !== null && ! $this->isKnownMedia($mediaId)) {+ unset($this->uploadedMedia[$mediaItem->id]);+ $mediaId = null;+ }++ if ($mediaId !== null) {+ $this->waitForProcessing($mediaId);+ } else {+ $mediaId = data_get($this->uploadMedia($mediaItem), 'data.id');+ }++ if (! $mediaId) {+ throw new XPublishException(+ userMessage: 'X did not accept the media upload. Please try again.',+ category: ErrorCategory::ServerError,+ );}++ $this->uploadedMedia[$mediaItem->id] = (string) $mediaId;+ // X expects media_ids as strings in the tweets payload.+ $mediaIds[] = (string) $mediaId;+ $this->uploadAltText((string) $mediaId, $mediaItem);}return $mediaIds === [] ? [] : ['media' => ['media_ids' => $mediaIds]];@@ -293,7 +330,7 @@ class XPublisher}$initData = $initResponse->json();- $mediaId = $initData['data']['id'] ?? $initData['media_id'] ?? null;+ $mediaId = data_get($initData, 'data.id');if (! $mediaId) {throw new XPublishException(@@ -305,7 +342,7 @@ class XPublisher// APPEND - Read from temp file in 1MB chunks. Matches the// twitter-api-v2 SDK default and X's own quickstart examples;// larger chunks (we previously used 5MB) trigger 413 at the X- // edge with an empty body, surfacing as "An unknown X error".+ // edge with an empty body.$chunkSize = 1024 * 1024;$handle = fopen($tempFile, 'r');$index = 0;@@ -403,6 +440,49 @@ class XPublisherreturn null;}+ private function isKnownMedia(string $mediaId): bool+ {+ $response = $this->mediaStatus($mediaId);++ if (in_array($response->status(), [400, 404], true)) {+ return false;+ }++ if ($response->serverError()) {+ throw new PlatformUnavailableException(+ message: "X returned {$response->status()} checking media {$mediaId}",+ httpStatus: $response->status(),+ );+ }++ if ($response->failed()) {+ $this->handleApiError($response);+ }++ return true;+ }++ private function mediaStatus(string $mediaId): Response+ {+ try {+ return $this->getHttpClient()+ ->get("{$this->baseUrl}/media/upload", [+ 'media_id' => $mediaId,+ 'command' => 'STATUS',+ ]);+ } catch (ConnectionException $e) {+ throw new PlatformUnavailableException(+ message: "X media status check failed to connect: {$e->getMessage()}",+ context: [+ PublishCheckpoint::X_MEDIA => [+ ...$this->uploadedMedia,+ ...($this->currentMediaItemId !== null ? [$this->currentMediaItemId => $mediaId] : []),+ ],+ ],+ );+ }+ }+private function waitForProcessing(string $mediaId, int $maxAttempts = 20): void{$lastProcessingInfo = null;@@ -410,11 +490,7 @@ class XPublisherfor ($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).- $response = $this->getHttpClient()- ->get("{$this->baseUrl}/media/upload", [- 'media_id' => $mediaId,- 'command' => 'STATUS',- ]);+ $response = $this->mediaStatus($mediaId);if ($response->failed()) {Log::error('X media status check error', ['body' => $this->redactResponseBody($response->body())]);@@ -424,8 +500,7 @@ class XPublisher}$responseData = $response->json();- $processingInfo = data_get($responseData, 'processing_info')- ?? data_get($responseData, 'data.processing_info');+ $processingInfo = data_get($responseData, 'data.processing_info');// If processing_info doesn't exist, assume it's readyif ($processingInfo === null) {@@ -433,13 +508,13 @@ class XPublisher}$lastProcessingInfo = $processingInfo;- $state = data_get($processingInfo, 'state', 'unknown');+ $state = $this->processingState($processingInfo);- if ($state === 'succeeded') {+ if ($state === MediaProcessingState::Succeeded) {return;}- if ($state === 'failed') {+ if ($state === MediaProcessingState::Failed) {$error = data_get($processingInfo, 'error', 'Unknown error');$rawError = is_string($error) ? $error : json_encode($error);@@ -453,24 +528,48 @@ class XPublisher);}- Sleep::for(max(0, (int) data_get($processingInfo, 'check_after_secs', 3)))->seconds();+ Sleep::for(min(self::MEDIA_STATUS_MAX_WAIT_SECONDS, max(0, (int) data_get($processingInfo, 'check_after_secs', 3))))->seconds();}- $rawResponse = is_array($lastProcessingInfo) ? json_encode($lastProcessingInfo) : null;+ if ($this->processingState($lastProcessingInfo)?->isProcessing() !== true) {+ 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: is_array($lastProcessingInfo) ? json_encode($lastProcessingInfo) : null,+ );+ }- Log::error('X media processing timed out', [+ Log::warning('X media still processing, publish rescheduled', ['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,+ throw new PlatformUnavailableException(+ message: "X is still processing media {$mediaId}",+ context: [+ PublishCheckpoint::X_MEDIA => [+ ...$this->uploadedMedia,+ ...($this->currentMediaItemId !== null ? [$this->currentMediaItemId => $mediaId] : []),+ ],+ ],+ retryDelaySeconds: self::MEDIA_PROCESSING_RETRY_DELAY_SECONDS,+ maxRetries: self::MEDIA_PROCESSING_MAX_RETRIES,);}+ private function processingState(mixed $processingInfo): ?MediaProcessingState+ {+ $state = data_get($processingInfo, 'state');++ return is_string($state) ? MediaProcessingState::tryFrom($state) : null;+ }+private function handleApiError(Response $response): never{throw XPublishException::fromApiResponse($response);diff --git a/app/Services/Social/YouTubePublisher.php b/app/Services/Social/YouTubePublisher.phpindex 3990e61c1..6d643dfb3 100644--- a/app/Services/Social/YouTubePublisher.php+++ b/app/Services/Social/YouTubePublisher.php@@ -7,6 +7,7 @@ namespace App\Services\Social;use App\Dto\MediaItem;use App\Enums\YouTube\License;use App\Enums\YouTube\PrivacyStatus;+use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\YouTubePublishException;use App\Models\PostPlatform;@@ -134,6 +135,8 @@ class YouTubePublisher];} catch (Exception $e) {throw YouTubePublishException::fromGoogleException($e);+ } catch (PlatformUnavailableException $e) {+ throw $e;} catch (\Throwable $e) {Log::error('YouTube upload failed', ['error' => $e->getMessage(),@@ -197,11 +200,23 @@ class YouTubePublisher);$mediaUpload->setFileSize($fileSize);+ try {+ $mediaUpload->getResumeUri();+ } catch (Exception $e) {+ throw YouTubePublishException::isServerError($e) ? $this->uploadUnavailable($e) : $e;+ }+$uploadStatus = false;while (! $uploadStatus && ! feof($handle)) {$chunk = fread($handle, self::CHUNK_SIZE);- $uploadStatus = $mediaUpload->nextChunk($chunk);+ $isFinalChunk = ftell($handle) >= $fileSize;++ try {+ $uploadStatus = $mediaUpload->nextChunk($chunk);+ } catch (Exception $e) {+ throw ! $isFinalChunk && YouTubePublishException::isServerError($e) ? $this->uploadUnavailable($e) : $e;+ }}if (! $uploadStatus instanceof Video) {@@ -218,6 +233,14 @@ class YouTubePublisher}}+ private function uploadUnavailable(Exception $e): PlatformUnavailableException+ {+ return new PlatformUnavailableException(+ message: "YouTube returned {$e->getCode()} during upload",+ httpStatus: $e->getCode() >= 500 ? $e->getCode() : null,+ );+ }+private function resolveDescription(PostPlatform $postPlatform, ?string $content): string{$description = YouTubeDescription::resolve($postPlatform->meta, $content);diff --git a/app/Support/Social/LimitRetryPolicy.php b/app/Support/Social/LimitRetryPolicy.phpindex 02b3d5927..88feea7b3 100644--- a/app/Support/Social/LimitRetryPolicy.php+++ b/app/Support/Social/LimitRetryPolicy.php@@ -27,7 +27,7 @@ final class LimitRetryPolicy* Keeps the scheduler's dispatches apart from the platform-unavailable* attempts in PublishToSocialPlatform's unique id.*/- public const int UNIQUE_ATTEMPT_OFFSET = 100;+ public const int UNIQUE_ATTEMPT_OFFSET = 1000;/*** @param array<string, mixed>|null $contextdiff --git a/app/Support/Social/PublishCheckpoint.php b/app/Support/Social/PublishCheckpoint.phpindex 328777e54..fa11a4954 100644--- a/app/Support/Social/PublishCheckpoint.php+++ b/app/Support/Social/PublishCheckpoint.php@@ -21,6 +21,8 @@ final class PublishCheckpointpublic const string INSTAGRAM_STATUS = 'instagram_status';+ public const string X_MEDIA = 'x_media';+/*** @param array<string, mixed>|null $context*/@@ -72,4 +74,24 @@ final class PublishCheckpointreturn is_string($value) && $value !== '' ? $value : null;}++ /**+ * X media ids already uploaded for this target, keyed by media item id.+ *+ * @param array<string, mixed>|null $context+ * @return array<string, string>+ */+ public static function xMedia(?array $context): array+ {+ $media = data_get($context, self::X_MEDIA);++ if (! is_array($media)) {+ return [];+ }++ return array_filter(+ array_map(fn (mixed $id): ?string => is_scalar($id) && (string) $id !== '' ? (string) $id : null, $media),+ fn (?string $id): bool => $id !== null,+ );+ }}diff --git a/lang/ar/posts.php b/lang/ar/posts.phpindex f512de2ff..aa40ee33d 100644--- a/lang/ar/posts.php+++ b/lang/ar/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'انتهت مهلة النشر. يرجى المحاولة مرة أخرى.','rejected_in_review' => 'رفضت Google هذا المنشور أثناء المراجعة. عدّل المحتوى أو الصورة وحاول مرة أخرى.','review_unconfirmed' => 'لم تؤكد Google حالة هذا المنشور. تحقّق من ملفك التجاري وحاول مرة أخرى.',+ 'instagram' => [+ 'processing_failed' => 'تعذّر على Instagram معالجة هذا الملف. جرّب ملفًا آخر.',+ ],+ 'content_too_long' => 'يحتوي هذا المنشور على :provided حرفًا، لكن :platform يسمح بـ :max.',+ 'unrecognized_error' => 'أعاد :platform خطأً لم نتمكن من تحديده. حاول مرة أخرى.',+ 'media_unavailable' => 'تعذّر علينا جلب الوسائط لإرسالها إلى :platform. حاول مرة أخرى.',+ 'facebook' => [+ 'processing_failed' => 'تعذّر على Facebook معالجة هذا الفيديو. تأكد من أنه يستوفي متطلبات Reels وحاول مرة أخرى.',+ 'upload_incomplete' => 'لم يستلم Facebook الفيديو كاملًا. حاول مرة أخرى.',+ ],+ 'linkedin' => [+ 'server_error' => 'حدث خطأ في خادم LinkedIn. حاول مرة أخرى.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'فشل YouTube في إنهاء الرفع. تحقق من قناتك قبل المحاولة مرة أخرى: قد يكون الفيديو موجودًا بالفعل.',+ ],'google_business' => ['no_location' => 'حساب Google Business Profile هذا بلا موقع مُعد. أعد ربطه.','permission_denied' => 'تم رفض الإذن. أعد الربط وأكّد الوصول إلى هذا الموقع.',diff --git a/lang/de/posts.php b/lang/de/posts.phpindex 93b545aa1..83d920fd8 100644--- a/lang/de/posts.php+++ b/lang/de/posts.php@@ -833,6 +833,22 @@ return ['publishing_timed_out' => 'Die Veröffentlichung ist abgelaufen. Bitte erneut versuchen.','rejected_in_review' => 'Google hat diesen Beitrag bei der Prüfung abgelehnt. Bearbeite den Inhalt oder das Bild und versuche es erneut.','review_unconfirmed' => 'Google hat den Status dieses Beitrags nicht bestätigt. Prüfe dein Unternehmensprofil und versuche es erneut.',+ 'instagram' => [+ 'processing_failed' => 'Instagram konnte diese Datei nicht verarbeiten. Versuche eine andere Datei.',+ ],+ 'content_too_long' => 'Dieser Beitrag hat :provided Zeichen, :platform erlaubt aber nur :max.',+ 'unrecognized_error' => ':platform hat einen Fehler gemeldet, den wir nicht zuordnen konnten. Versuche es erneut.',+ 'media_unavailable' => 'Wir konnten die Medien für :platform nicht abrufen. Versuche es erneut.',+ 'facebook' => [+ 'processing_failed' => 'Facebook konnte dieses Video nicht verarbeiten. Prüfe, ob es die Anforderungen für Reels erfüllt, und versuche es erneut.',+ 'upload_incomplete' => 'Facebook hat nicht das ganze Video erhalten. Versuche es erneut.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn hatte einen Serverfehler. Bitte versuche es erneut.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube ist beim Abschließen des Uploads fehlgeschlagen. Prüfe deinen Kanal, bevor du es erneut versuchst: Das Video ist dort vielleicht schon.',+ ],'google_business' => ['no_location' => 'Dieses Google-Business-Profile-Konto hat keinen Standort konfiguriert. Bitte erneut verbinden.','permission_denied' => 'Zugriff verweigert. Verbinde erneut und bestätige den Zugriff auf diesen Standort.',diff --git a/lang/el/posts.php b/lang/el/posts.phpindex 58c4792a8..2903149aa 100644--- a/lang/el/posts.php+++ b/lang/el/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Η δημοσίευση έληξε. Δοκιμάστε ξανά.','rejected_in_review' => 'Η Google απέρριψε αυτήν τη δημοσίευση κατά τον έλεγχο. Επεξεργάσου το περιεχόμενο ή την εικόνα και δοκίμασε ξανά.','review_unconfirmed' => 'Η Google δεν επιβεβαίωσε την κατάσταση αυτής της δημοσίευσης. Έλεγξε το προφίλ σου και δοκίμασε ξανά.',+ 'instagram' => [+ 'processing_failed' => 'Το Instagram δεν μπόρεσε να επεξεργαστεί αυτό το αρχείο. Δοκίμασε άλλο.',+ ],+ 'content_too_long' => 'Αυτή η ανάρτηση έχει :provided χαρακτήρες, αλλά το :platform επιτρέπει :max.',+ 'unrecognized_error' => 'Το :platform επέστρεψε ένα σφάλμα που δεν μπορέσαμε να αναγνωρίσουμε. Δοκίμασε ξανά.',+ 'media_unavailable' => 'Δεν μπορέσαμε να ανακτήσουμε το πολυμέσο για αποστολή στο :platform. Δοκίμασε ξανά.',+ 'facebook' => [+ 'processing_failed' => 'Το Facebook δεν μπόρεσε να επεξεργαστεί αυτό το βίντεο. Βεβαιώσου ότι πληροί τις απαιτήσεις των Reels και δοκίμασε ξανά.',+ 'upload_incomplete' => 'Το Facebook δεν έλαβε ολόκληρο το βίντεο. Δοκίμασε ξανά.',+ ],+ 'linkedin' => [+ 'server_error' => 'Το LinkedIn είχε σφάλμα διακομιστή. Δοκίμασε ξανά.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'Το YouTube απέτυχε να ολοκληρώσει τη μεταφόρτωση. Έλεγξε το κανάλι σου πριν δοκιμάσεις ξανά: το βίντεο μπορεί να υπάρχει ήδη.',+ ],'google_business' => ['no_location' => 'Αυτός ο λογαριασμός Google Business Profile δεν έχει ρυθμισμένη τοποθεσία. Σύνδεσέ τον ξανά.','permission_denied' => 'Άρνηση πρόσβασης. Σύνδεσε ξανά και επιβεβαίωσε την πρόσβαση σε αυτή την τοποθεσία.',diff --git a/lang/en/posts.php b/lang/en/posts.phpindex 69c21250b..198fa3fa6 100644--- a/lang/en/posts.php+++ b/lang/en/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Publishing timed out. Please try again.','rejected_in_review' => 'Google rejected this post in review. Edit the content or image and try again.','review_unconfirmed' => 'Google never confirmed this post. Check your Business Profile and try again.',+ 'instagram' => [+ 'processing_failed' => 'Instagram could not process this media. Try another file.',+ ],+ 'content_too_long' => 'This post has :provided characters, but :platform allows :max.',+ 'unrecognized_error' => ':platform returned an error we could not identify. Please try again.',+ 'media_unavailable' => 'We could not fetch the media to send to :platform. Please try again.',+ 'facebook' => [+ 'processing_failed' => 'Facebook could not process this video. Make sure it meets the Reels requirements and try again.',+ 'upload_incomplete' => 'Facebook did not receive the whole video. Please try again.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn had a server error. Please try again.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube failed while finishing the upload. Check your channel before trying again: the video may already be there.',+ ],'google_business' => ['no_location' => 'This Google Business Profile account has no location configured. Please reconnect it.','permission_denied' => 'Permission denied. Please reconnect and confirm access to this business location.',diff --git a/lang/es/posts.php b/lang/es/posts.phpindex f4794a219..5f5339afb 100644--- a/lang/es/posts.php+++ b/lang/es/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'La publicación agotó el tiempo de espera. Inténtalo de nuevo.','rejected_in_review' => 'Google rechazó esta publicación durante la revisión. Edita el contenido o la imagen e inténtalo de nuevo.','review_unconfirmed' => 'Google nunca confirmó esta publicación. Revisa tu Perfil de Empresa e inténtalo de nuevo.',+ 'instagram' => [+ 'processing_failed' => 'Instagram no pudo procesar este archivo. Prueba con otro.',+ ],+ 'content_too_long' => 'Esta publicación tiene :provided caracteres, pero :platform permite :max.',+ 'unrecognized_error' => ':platform devolvió un error que no pudimos identificar. Inténtalo de nuevo.',+ 'media_unavailable' => 'No pudimos obtener el archivo multimedia para enviarlo a :platform. Inténtalo de nuevo.',+ 'facebook' => [+ 'processing_failed' => 'Facebook no pudo procesar este vídeo. Comprueba que cumple los requisitos de Reels e inténtalo de nuevo.',+ 'upload_incomplete' => 'Facebook no recibió el vídeo completo. Inténtalo de nuevo.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn tuvo un error del servidor. Inténtalo de nuevo.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube falló al terminar la subida. Revisa tu canal antes de volver a intentarlo: puede que el vídeo ya esté allí.',+ ],'google_business' => ['no_location' => 'Esta cuenta de Google Business Profile no tiene una ubicación configurada. Vuelve a conectarla.','permission_denied' => 'Permiso denegado. Reconecta y confirma el acceso a esta ubicación.',diff --git a/lang/fr/posts.php b/lang/fr/posts.phpindex 3e24278fc..f79e4c018 100644--- a/lang/fr/posts.php+++ b/lang/fr/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'La publication a expiré. Veuillez réessayer.','rejected_in_review' => 'Google a refusé ce post lors de l\'examen. Modifie le contenu ou l\'image et réessaie.','review_unconfirmed' => 'Google n\'a jamais confirmé ce post. Vérifie ta fiche d\'établissement et réessaie.',+ 'instagram' => [+ 'processing_failed' => 'Instagram n\'a pas pu traiter ce média. Essaie un autre fichier.',+ ],+ 'content_too_long' => 'Cette publication contient :provided caractères, mais :platform en autorise :max.',+ 'unrecognized_error' => ':platform a renvoyé une erreur que nous n\'avons pas pu identifier. Réessaie.',+ 'media_unavailable' => 'Nous n\'avons pas pu récupérer le média à envoyer à :platform. Réessaie.',+ 'facebook' => [+ 'processing_failed' => 'Facebook n\'a pas pu traiter cette vidéo. Vérifie qu\'elle respecte les exigences des Reels et réessaie.',+ 'upload_incomplete' => 'Facebook n\'a pas reçu la vidéo en entier. Réessaie.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn a rencontré une erreur serveur. Réessaie.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube a échoué en finalisant l\'envoi. Vérifie ta chaîne avant de réessayer : la vidéo y est peut-être déjà.',+ ],'google_business' => ['no_location' => 'Ce compte Google Business Profile n\'a aucun établissement configuré. Reconnecte-le.','permission_denied' => 'Autorisation refusée. Reconnecte le compte et confirme l\'accès à cet établissement.',diff --git a/lang/it/posts.php b/lang/it/posts.phpindex 33a8b3554..d31767631 100644--- a/lang/it/posts.php+++ b/lang/it/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Pubblicazione scaduta. Riprova.','rejected_in_review' => 'Google ha rifiutato questo post durante la revisione. Modifica il contenuto o l\'immagine e riprova.','review_unconfirmed' => 'Google non ha mai confermato questo post. Controlla il tuo profilo aziendale e riprova.',+ 'instagram' => [+ 'processing_failed' => 'Instagram non è riuscito a elaborare questo file. Prova con un altro.',+ ],+ 'content_too_long' => 'Questo post ha :provided caratteri, ma :platform ne consente :max.',+ 'unrecognized_error' => ':platform ha restituito un errore che non siamo riusciti a identificare. Riprova.',+ 'media_unavailable' => 'Non siamo riusciti a recuperare il file multimediale da inviare a :platform. Riprova.',+ 'facebook' => [+ 'processing_failed' => 'Facebook non è riuscito a elaborare questo video. Verifica che rispetti i requisiti dei Reels e riprova.',+ 'upload_incomplete' => 'Facebook non ha ricevuto il video completo. Riprova.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn ha avuto un errore del server. Riprova.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube non è riuscito a completare il caricamento. Controlla il tuo canale prima di riprovare: il video potrebbe essere già lì.',+ ],'google_business' => ['no_location' => 'Questo account Google Business Profile non ha una sede configurata. Ricollegalo.','permission_denied' => 'Permesso negato. Ricollega e conferma l\'accesso a questa sede.',diff --git a/lang/ja/posts.php b/lang/ja/posts.phpindex 9434e307f..6f9540492 100644--- a/lang/ja/posts.php+++ b/lang/ja/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => '公開がタイムアウトしました。もう一度お試しください。','rejected_in_review' => 'Google の審査でこの投稿が拒否されました。本文または画像を修正して、もう一度お試しください。','review_unconfirmed' => 'Google からこの投稿の結果が返りませんでした。ビジネス プロフィールを確認して、もう一度お試しください。',+ 'instagram' => [+ 'processing_failed' => 'Instagram でこのメディアを処理できませんでした。別のファイルをお試しください。',+ ],+ 'content_too_long' => 'この投稿は :provided 文字ですが、:platform の上限は :max 文字です。',+ 'unrecognized_error' => ':platform で特定できないエラーが発生しました。もう一度お試しください。',+ 'media_unavailable' => ':platform に送信するメディアを取得できませんでした。もう一度お試しください。',+ 'facebook' => [+ 'processing_failed' => 'Facebook でこの動画を処理できませんでした。リール動画の要件を満たしているか確認して、もう一度お試しください。',+ 'upload_incomplete' => 'Facebook が動画全体を受信できませんでした。もう一度お試しください。',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn でサーバーエラーが発生しました。もう一度お試しください。',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTubeでアップロードの完了中にエラーが発生しました。再試行する前にチャンネルを確認してください。動画がすでに公開されている可能性があります。',+ ],'google_business' => ['no_location' => 'この Google ビジネス プロフィール アカウントには店舗が設定されていません。再接続してください。','permission_denied' => '権限がありません。再接続して、この店舗へのアクセスを確認してください。',diff --git a/lang/ko/posts.php b/lang/ko/posts.phpindex 351288129..0df056530 100644--- a/lang/ko/posts.php+++ b/lang/ko/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => '게시에 시간이 초과되었습니다. 다시 시도하세요.','rejected_in_review' => 'Google 검토에서 이 게시물이 거부되었습니다. 내용이나 이미지를 수정한 후 다시 시도하세요.','review_unconfirmed' => 'Google가 이 게시물을 확인해 주지 않았습니다. 비즈니스 프로필을 확인한 후 다시 시도하세요.',+ 'instagram' => [+ 'processing_failed' => 'Instagram에서 이 미디어를 처리하지 못했습니다. 다른 파일을 사용해 보세요.',+ ],+ 'content_too_long' => '이 게시물은 :provided자이지만 :platform에서는 최대 :max자까지 허용됩니다.',+ 'unrecognized_error' => ':platform에서 확인할 수 없는 오류가 발생했습니다. 다시 시도하세요.',+ 'media_unavailable' => ':platform에 보낼 미디어를 가져오지 못했습니다. 다시 시도하세요.',+ 'facebook' => [+ 'processing_failed' => 'Facebook에서 이 동영상을 처리하지 못했습니다. 릴스 요구 사항을 충족하는지 확인한 후 다시 시도하세요.',+ 'upload_incomplete' => 'Facebook에서 동영상 전체를 받지 못했습니다. 다시 시도하세요.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn 서버 오류가 발생했습니다. 다시 시도하세요.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube에서 업로드를 마무리하지 못했습니다. 다시 시도하기 전에 채널을 확인하세요. 동영상이 이미 올라가 있을 수 있습니다.',+ ],'google_business' => ['no_location' => '이 Google 비즈니스 프로필 계정에 설정된 위치가 없습니다. 다시 연결하세요.','permission_denied' => '권한이 거부되었습니다. 다시 연결하고 이 위치에 대한 액세스를 확인하세요.',diff --git a/lang/nl/posts.php b/lang/nl/posts.phpindex 2fdccb0bb..14a26c8a9 100644--- a/lang/nl/posts.php+++ b/lang/nl/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Publiceren is timed-out. Probeer het opnieuw.','rejected_in_review' => 'Google heeft dit bericht bij de beoordeling afgewezen. Pas de inhoud of afbeelding aan en probeer het opnieuw.','review_unconfirmed' => 'Google heeft dit bericht nooit bevestigd. Controleer je bedrijfsprofiel en probeer het opnieuw.',+ 'instagram' => [+ 'processing_failed' => 'Instagram kon dit bestand niet verwerken. Probeer een ander bestand.',+ ],+ 'content_too_long' => 'Deze post heeft :provided tekens, maar :platform staat er :max toe.',+ 'unrecognized_error' => ':platform gaf een fout die we niet konden herkennen. Probeer het opnieuw.',+ 'media_unavailable' => 'We konden de media voor :platform niet ophalen. Probeer het opnieuw.',+ 'facebook' => [+ 'processing_failed' => 'Facebook kon deze video niet verwerken. Controleer of hij aan de eisen voor Reels voldoet en probeer het opnieuw.',+ 'upload_incomplete' => 'Facebook heeft niet de hele video ontvangen. Probeer het opnieuw.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn had een serverfout. Probeer het opnieuw.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube faalde bij het afronden van de upload. Controleer je kanaal voordat je het opnieuw probeert: de video staat er misschien al.',+ ],'google_business' => ['no_location' => 'Dit Google Business Profile-account heeft geen locatie ingesteld. Verbind het opnieuw.','permission_denied' => 'Toegang geweigerd. Verbind opnieuw en bevestig toegang tot deze locatie.',diff --git a/lang/pl/posts.php b/lang/pl/posts.phpindex 175230151..4e97a465a 100644--- a/lang/pl/posts.php+++ b/lang/pl/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Publikowanie przekroczyło limit czasu. Spróbuj ponownie.','rejected_in_review' => 'Google odrzuciło ten post podczas weryfikacji. Zmień treść lub obraz i spróbuj ponownie.','review_unconfirmed' => 'Google nie potwierdziło tego posta. Sprawdź swój profil firmy i spróbuj ponownie.',+ 'instagram' => [+ 'processing_failed' => 'Instagram nie mógł przetworzyć tego pliku. Spróbuj innego.',+ ],+ 'content_too_long' => 'Ten post ma :provided znaków, a :platform pozwala na :max.',+ 'unrecognized_error' => ':platform zwrócił błąd, którego nie udało się rozpoznać. Spróbuj ponownie.',+ 'media_unavailable' => 'Nie udało się pobrać multimediów do wysłania do :platform. Spróbuj ponownie.',+ 'facebook' => [+ 'processing_failed' => 'Facebook nie mógł przetworzyć tego filmu. Sprawdź, czy spełnia wymagania dla Reels, i spróbuj ponownie.',+ 'upload_incomplete' => 'Facebook nie otrzymał całego filmu. Spróbuj ponownie.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn zgłosił błąd serwera. Spróbuj ponownie.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube nie zdołał dokończyć przesyłania. Sprawdź swój kanał, zanim spróbujesz ponownie: film może już tam być.',+ ],'google_business' => ['no_location' => 'To konto Google Business Profile nie ma skonfigurowanej lokalizacji. Połącz je ponownie.','permission_denied' => 'Brak uprawnień. Połącz ponownie i potwierdź dostęp do tej lokalizacji.',diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex f227d95f4..7e33d6867 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'A publicação excedeu o tempo limite. Tente novamente.','rejected_in_review' => 'O Google recusou este post na revisão. Edite o conteúdo ou a imagem e tente novamente.','review_unconfirmed' => 'O Google nunca confirmou este post. Confira seu Perfil da Empresa e tente novamente.',+ 'instagram' => [+ 'processing_failed' => 'O Instagram não conseguiu processar esta mídia. Tente outro arquivo.',+ ],+ 'content_too_long' => 'Este post tem :provided caracteres, mas o :platform permite :max.',+ 'unrecognized_error' => 'O :platform retornou um erro que não conseguimos identificar. Tente novamente.',+ 'media_unavailable' => 'Não conseguimos buscar a mídia para enviar ao :platform. Tente novamente.',+ 'facebook' => [+ 'processing_failed' => 'O Facebook não conseguiu processar este vídeo. Confira se ele atende aos requisitos de Reels e tente novamente.',+ 'upload_incomplete' => 'O Facebook não recebeu o vídeo inteiro. Tente novamente.',+ ],+ 'linkedin' => [+ 'server_error' => 'O LinkedIn teve um erro no servidor. Tente novamente.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'O YouTube falhou ao concluir o envio. Confira seu canal antes de tentar de novo: o vídeo pode já estar lá.',+ ],'google_business' => ['no_location' => 'Esta conta do Google Business Profile não tem um local configurado. Reconecte-a.','permission_denied' => 'Permissão negada. Reconecte e confirme o acesso a este local.',diff --git a/lang/ru/posts.php b/lang/ru/posts.phpindex 31043825b..694b1245b 100644--- a/lang/ru/posts.php+++ b/lang/ru/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Публикация превысила время ожидания. Попробуйте снова.','rejected_in_review' => 'Google отклонил эту публикацию при проверке. Измените текст или изображение и попробуйте снова.','review_unconfirmed' => 'Google так и не подтвердил эту публикацию. Проверьте профиль компании и попробуйте снова.',+ 'instagram' => [+ 'processing_failed' => 'Instagram не смог обработать этот файл. Попробуйте другой.',+ ],+ 'content_too_long' => 'В этом посте :provided символов, а :platform допускает :max.',+ 'unrecognized_error' => ':platform вернул ошибку, которую нам не удалось определить. Попробуйте снова.',+ 'media_unavailable' => 'Не удалось получить медиафайл для отправки в :platform. Попробуйте снова.',+ 'facebook' => [+ 'processing_failed' => 'Facebook не смог обработать это видео. Убедитесь, что оно соответствует требованиям Reels, и попробуйте снова.',+ 'upload_incomplete' => 'Facebook получил видео не полностью. Попробуйте снова.',+ ],+ 'linkedin' => [+ 'server_error' => 'На сервере LinkedIn произошла ошибка. Попробуйте ещё раз.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube не смог завершить загрузку. Проверьте канал, прежде чем пробовать снова: видео может уже быть там.',+ ],'google_business' => ['no_location' => 'У этого аккаунта Google Business Profile не настроена локация. Подключите его заново.','permission_denied' => 'Доступ запрещён. Подключите аккаунт заново и подтвердите доступ к этой локации.',diff --git a/lang/tr/posts.php b/lang/tr/posts.phpindex e2ea1ed5d..fd34b50c6 100644--- a/lang/tr/posts.php+++ b/lang/tr/posts.php@@ -833,6 +833,22 @@ return ['publishing_timed_out' => 'Yayınlama zaman aşımına uğradı. Lütfen tekrar deneyin.','rejected_in_review' => 'Google bu gönderiyi incelemede reddetti. İçeriği veya görseli düzenleyip tekrar deneyin.','review_unconfirmed' => 'Google bu gönderiyi hiç onaylamadı. İşletme Profili\'ni kontrol edip tekrar deneyin.',+ 'instagram' => [+ 'processing_failed' => 'Instagram bu medyayı işleyemedi. Başka bir dosya deneyin.',+ ],+ 'content_too_long' => 'Bu gönderi :provided karakter, ancak :platform en fazla :max karaktere izin veriyor.',+ 'unrecognized_error' => ':platform tanımlayamadığımız bir hata döndürdü. Lütfen tekrar deneyin.',+ 'media_unavailable' => ':platform platformuna gönderilecek medyayı alamadık. Lütfen tekrar deneyin.',+ 'facebook' => [+ 'processing_failed' => 'Facebook bu videoyu işleyemedi. Reels gereksinimlerini karşıladığından emin olup tekrar deneyin.',+ 'upload_incomplete' => 'Facebook videonun tamamını almadı. Lütfen tekrar deneyin.',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn\'de bir sunucu hatası oluştu. Lütfen tekrar deneyin.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube yüklemeyi tamamlarken başarısız oldu. Tekrar denemeden önce kanalınızı kontrol edin: video zaten orada olabilir.',+ ],'google_business' => ['no_location' => 'Bu Google Business Profile hesabında yapılandırılmış bir konum yok. Yeniden bağlayın.','permission_denied' => 'İzin reddedildi. Yeniden bağlanın ve bu konuma erişimi onaylayın.',diff --git a/lang/uk/posts.php b/lang/uk/posts.phpindex 09b7724f8..bad7442df 100644--- a/lang/uk/posts.php+++ b/lang/uk/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => 'Публікація перевищила час очікування. Спробуйте ще раз.','rejected_in_review' => 'Google відхилив цю публікацію під час перевірки. Змініть текст або зображення та спробуйте ще раз.','review_unconfirmed' => 'Google так і не підтвердив цю публікацію. Перевірте профіль компанії та спробуйте ще раз.',+ 'instagram' => [+ 'processing_failed' => 'Instagram не зміг обробити цей файл. Спробуйте інший.',+ ],+ 'content_too_long' => 'У цьому дописі :provided символів, а :platform дозволяє :max.',+ 'unrecognized_error' => ':platform повернув помилку, яку нам не вдалося визначити. Спробуйте ще раз.',+ 'media_unavailable' => 'Не вдалося отримати медіафайл для надсилання до :platform. Спробуйте ще раз.',+ 'facebook' => [+ 'processing_failed' => 'Facebook не зміг обробити це відео. Переконайтеся, що воно відповідає вимогам Reels, і спробуйте ще раз.',+ 'upload_incomplete' => 'Facebook отримав відео не повністю. Спробуйте ще раз.',+ ],+ 'linkedin' => [+ 'server_error' => 'На сервері LinkedIn сталася помилка. Спробуйте ще раз.',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube не зміг завершити завантаження. Перевірте канал, перш ніж пробувати знову: відео може вже бути там.',+ ],'google_business' => ['no_location' => 'У цього акаунта Google Business Profile немає налаштованої локації. Підключіть його знову.','permission_denied' => 'Доступ заборонено. Підключіть акаунт знову й підтвердьте доступ до цієї локації.',diff --git a/lang/zh/posts.php b/lang/zh/posts.phpindex 560c9bdd3..3f037c285 100644--- a/lang/zh/posts.php+++ b/lang/zh/posts.php@@ -831,6 +831,22 @@ return ['publishing_timed_out' => '发布超时。请重试。','rejected_in_review' => 'Google 在审核中拒绝了这篇帖子。请修改内容或图片后重试。','review_unconfirmed' => 'Google 始终未确认这篇帖子。请检查你的商家资料后重试。',+ 'instagram' => [+ 'processing_failed' => 'Instagram 无法处理此媒体,请换一个文件。',+ ],+ 'content_too_long' => '此帖子有 :provided 个字符,但 :platform 最多允许 :max 个。',+ 'unrecognized_error' => ':platform 返回了无法识别的错误,请重试。',+ 'media_unavailable' => '无法获取要发送到 :platform 的媒体,请重试。',+ 'facebook' => [+ 'processing_failed' => 'Facebook 无法处理此视频。请确认它符合 Reels 的要求后重试。',+ 'upload_incomplete' => 'Facebook 未收到完整的视频,请重试。',+ ],+ 'linkedin' => [+ 'server_error' => 'LinkedIn 服务器出错,请重试。',+ ],+ 'youtube' => [+ 'upload_unconfirmed' => 'YouTube 在完成上传时失败。重试前请先检查你的频道:视频可能已经在那里了。',+ ],'google_business' => ['no_location' => '此 Google 商家资料账号尚未配置地点。请重新连接。','permission_denied' => '权限被拒绝。请重新连接并确认对此地点的访问权限。',diff --git a/tests/Browser/ComposerSharedDataTest.php b/tests/Browser/ComposerSharedDataTest.phpindex 94c4b30d0..354884806 100644--- a/tests/Browser/ComposerSharedDataTest.php+++ b/tests/Browser/ComposerSharedDataTest.php@@ -10,8 +10,6 @@ use App\Models\PostPlatform;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;-use App\Support\PostingSchedule;-use Illuminate\Http\Client\Request;use Illuminate\Support\Facades\Http;/**@@ -106,50 +104,6 @@ function waitForComposerSharedDataReady(mixed $page, string $testId): voidJS);}-function pinterestBoardListReads(): int-{- return Http::recorded(fn (Request $request): bool => $request->method() === 'GET'- && str_starts_with($request->url(), config('trypost.platforms.pinterest.api').'/boards'))->count();-}--test('a new post lists every channel at once and fills the pinterest and tiktok pickers', function () {- [$user, , $pinterest, $tiktok] = composerSharedDataSetup();- $this->actingAs($user);-- $page = visit(route('app.posts.create'));- waitForComposerSharedDataReady($page, 'composer-add-account');-- $page->click('@composer-add-account')- ->assertVisible("@composer-account-option-{$pinterest->id}")- ->assertVisible("@composer-account-option-{$tiktok->id}")- ->click("@composer-account-option-{$pinterest->id}");- waitForComposerSharedDataTestId($page, 'pinterest-board-trigger');-- $page->click('@pinterest-board-trigger');- waitForComposerSharedDataTestId($page, 'pinterest-board-option-board_live');- $page->assertSeeIn('@pinterest-board-option-board_live', 'Live board')- ->assertNoJavaScriptErrors();-});--test('the composer opens again from the sidebar without reading pinterest again', function () {- [$user, , $pinterest] = composerSharedDataSetup();- $this->actingAs($user);-- $page = visit(route('app.insights'));- clickComposerSharedDataNewPost($page);- waitForComposerSharedDataReady($page, 'composer-add-account');- $page->click('@composer-close');- waitForComposerSharedDataCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");-- clickComposerSharedDataNewPost($page);- waitForComposerSharedDataReady($page, 'composer-add-account');- $page->click('@composer-add-account')- ->assertVisible("@composer-account-option-{$pinterest->id}")- ->assertNoJavaScriptErrors();-- expect(pinterestBoardListReads())->toBeLessThanOrEqual(1);-});-test('editing from the calendar opens the post with its board', function () {[$user, $workspace, $pinterest] = composerSharedDataSetup();$post = composerSharedDataPost($workspace, $pinterest, ContentType::PinterestPin, ['board_id' => 'board_live']);@@ -284,110 +238,3 @@ test('editing a tiktok post keeps its stored interaction flags', function () {expect(data_get($target->fresh()->meta, 'allow_comments'))->toBeTrue();});--/**- * A LinkedIn channel whose only posting time today is 15:00 in a zone where it- * is noon now, so the slot is in the future whatever the test clock says.- */-function composerSharedDataSlotChannel(Workspace $workspace): SocialAccount-{- $offset = 12 - now('UTC')->hour;- $zone = match (true) {- $offset === 0 => 'UTC',- $offset > 0 => "Etc/GMT-{$offset}",- default => 'Etc/GMT+'.abs($offset),- };-- return SocialAccount::factory()->linkedin()->create([- 'workspace_id' => $workspace->id,- 'timezone' => $zone,- 'posting_schedule' => PostingSchedule::empty()->withTime(now($zone)->dayOfWeek, '15:00'),- ]);-}--/**- * Keeps every request to the TikTok channel's composer data from being sent- * until `window.__releaseTikTok()` runs.- */-function holdComposerSharedDataTikTok(mixed $page, SocialAccount $tiktok): void-{- $page->script(<<<JS- (() => {- const { open, send } = XMLHttpRequest.prototype;- const held = [];- XMLHttpRequest.prototype.open = function (method, url, ...rest) {- this.__held = String(url).includes('/posts/composer/accounts/{$tiktok->id}');- return open.call(this, method, url, ...rest);- };- XMLHttpRequest.prototype.send = function (body) {- if (this.__held && !window.__tiktokReleased) {- held.push(() => send.call(this, body));- return;- }- return send.call(this, body);- };- window.__releaseTikTok = () => {- window.__tiktokReleased = true;- held.splice(0).forEach((release) => release());- };- })()- JS);-}--test('a network that does not answer holds only its own channel settings', function () {- [$user, , $pinterest, $tiktok] = composerSharedDataSetup();- $this->actingAs($user);-- $page = visit(route('app.insights'));- holdComposerSharedDataTikTok($page, $tiktok);- openComposerFromSidebar($page);-- $page->click('@composer-add-account')- ->click("@composer-account-option-{$pinterest->id}");- waitForComposerSharedDataTestId($page, 'pinterest-board-trigger');- $page->assertMissing('@composer-live-data-pending');-- $page->click("@composer-account-option-{$pinterest->id}")- ->click("@composer-account-option-{$tiktok->id}");- waitForComposerSharedDataTestId($page, 'composer-live-data-pending');- $page->assertMissing('@tiktok-privacy-level');-- $page->script('window.__releaseTikTok()');- waitForComposerSharedDataTestId($page, 'tiktok-privacy-level');- $page->assertMissing('@composer-live-data-pending')- ->assertNoJavaScriptErrors();-});--test('a failed slot read shows a retry banner and slots open once it loads', function () {- [$user, $workspace] = composerSharedDataSetup();- $channel = composerSharedDataSlotChannel($workspace);- $this->actingAs($user);-- $page = visit(route('app.insights'));- $page->script(<<<'JS'- (() => {- const open = XMLHttpRequest.prototype.open;- let broken = false;- XMLHttpRequest.prototype.open = function (method, url, ...rest) {- if (!broken && String(url).includes('/taken-slots')) {- broken = true;- url = String(url).replace('/taken-slots', '/taken-slots-unavailable');- }- return open.call(this, method, url, ...rest);- };- })()- JS);- openComposerFromSidebar($page);-- composerSharedDataZoneLabel($page, $channel);- waitForComposerSharedDataTestId($page, 'composer-live-data-failed');- $page->assertSeeIn('@composer-live-data-failed', __('posts.composer.load_failed'));- waitForComposerSharedDataTestId($page, 'composer-schedule-slot-1500');- expect($page->script('document.querySelector("[data-testid=composer-schedule-slot-1500]").disabled'))->toBeTrue();-- $page->click('@composer-live-data-retry');- waitForComposerSharedDataCondition($page, "!document.querySelector('[data-testid=\"composer-live-data-failed\"]') && document.querySelector('[data-testid=\"composer-schedule-slot-1500\"]')?.disabled === false");-- $page->assertMissing('@composer-live-data-failed');- expect($page->script('document.querySelector("[data-testid=composer-schedule-slot-1500]").disabled'))->toBeFalse();-});diff --git a/tests/Browser/PostComposerDialogTest.php b/tests/Browser/PostComposerDialogTest.phpindex 95e4bd345..0175f9800 100644--- a/tests/Browser/PostComposerDialogTest.php+++ b/tests/Browser/PostComposerDialogTest.php@@ -49,6 +49,30 @@ function waitForComposerReady(mixed $page, string $testId = 'composer-add-accounJS);}+function clickComposerDialogNewPost(mixed $page): void+{+ $item = "document.querySelector('[data-testid=\"sidebar-new-post\"]')?.getBoundingClientRect().height > 0";+ $settled = "{$item} && document.querySelector('[data-testid=\"sidebar-new-menu\"]').getAnimations().every((animation) => animation.playState !== 'running')";++ for ($attempt = 0; $attempt < 3 && ! $page->script("Boolean({$item})"); $attempt++) {+ clickComposerDialogControl($page, '[data-testid="sidebar-new"]');+ waitForComposerCondition($page, $item);+ }++ waitForComposerCondition($page, $settled);+ clickComposerDialogControl($page, '[data-testid="sidebar-new-post"]');+}++/**+ * Pest retries clicks with a one-second timeout. A successful click can time+ * out after opening a modal or removing its target, then be repeated. Let+ * Playwright wait with the full timeout and issue the action only once.+ */+function clickComposerDialogControl(mixed $page, string $selector): void+{+ $page->page()->locator($selector)->click();+}+test('schedule view switch opens the weekly calendar and goes back to the list', function () {$user = User::factory()->create();$workspace = Workspace::factory()->create([@@ -173,9 +197,9 @@ test('new post buttons open the global dialog without changing the page URL', fu$this->actingAs($user);$calendar = visit(route('app.calendar'));- $calendar->click('@sidebar-new')- ->click('@sidebar-new-post')- ->assertVisible('@post-composer-dialog')+ clickComposerDialogNewPost($calendar);+ waitForComposerReady($calendar);+ $calendar->assertVisible('@post-composer-dialog')->assertScript('location.pathname + location.search', parse_url(route('app.calendar'), PHP_URL_PATH));$posts = visit(route('app.posts.index'));@@ -216,7 +240,7 @@ test('the global composer opens without accessibility or attribute warnings', fu})();JS);- $page->click('@sidebar-new')->click('@sidebar-new-post');+ clickComposerDialogNewPost($page);waitForComposerReady($page);$page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();@@ -489,8 +513,8 @@ test('composer searches and selects multiple labels and exposes emoji and signatwaitForComposerCondition($page, "!document.querySelector('[data-testid=\"composer-label-search\"]')");$page->click('@composer-base-emoji');waitForComposerCondition($page, "document.querySelector('button[aria-label=\"grinning face\"]')?.getBoundingClientRect().height > 0");- $page->click('button[aria-label="grinning face"]')- ->assertValue('@composer-base-content', '😀')+ clickComposerDialogControl($page, 'button[aria-label="grinning face"]');+ $page->assertValue('@composer-base-content', '😀')->click('@composer-base-signature')->click('text=Campaign signature')->assertValue('@composer-base-content', "😀\n\n#campaign")@@ -500,8 +524,8 @@ test('composer searches and selects multiple labels and exposes emoji and signatwaitForComposerCondition($page, "!document.querySelector('[data-testid=\"composer-account-option-{$account->id}\"]')");$page->click("@composer-{$account->id}-emoji");waitForComposerCondition($page, "document.querySelector('button[aria-label=\"grinning face with big eyes\"]')?.getBoundingClientRect().height > 0");- $page->click('button[aria-label="grinning face with big eyes"]')- ->assertValue("@composer-caption-{$account->id}", "😀\n\n#campaign😃")+ clickComposerDialogControl($page, 'button[aria-label="grinning face with big eyes"]');+ $page->assertValue("@composer-caption-{$account->id}", "😀\n\n#campaign😃")->click('@composer-save-draft');$page->script(<<<'JS'@@ -577,7 +601,7 @@ test('a label created from the empty label picker of the global composer is list$this->actingAs($user);$page = visit(route('app.insights'));- $page->click('@sidebar-new')->click('@sidebar-new-post');+ clickComposerDialogNewPost($page);waitForComposerReady($page);$page->fill('@composer-base-content', 'Draft text')->click('@composer-add-account')diff --git a/tests/Feature/Analytics/PublicationBackfillJobsTest.php b/tests/Feature/Analytics/PublicationBackfillJobsTest.phpindex 1c44d396b..710b04001 100644--- a/tests/Feature/Analytics/PublicationBackfillJobsTest.php+++ b/tests/Feature/Analytics/PublicationBackfillJobsTest.php@@ -11,6 +11,7 @@ use App\Enums\Analytics\SyncCollector;use App\Enums\Analytics\SyncStatus;use App\Enums\SocialAccount\Platform;use App\Exceptions\Analytics\AnalyticsCollectionException;+use App\Jobs\Analytics\AbstractPublicationSync;use App\Jobs\Analytics\BackfillAccountPublications;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;@@ -24,11 +25,13 @@ use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Publications\AbstractPublicationHistoryCollector;use App\Services\Analytics\Collectors\Publications\PublicationHistoryCollectorFactory;use Carbon\CarbonImmutable;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Queue\Middleware\RateLimited;use Illuminate\Queue\Middleware\WithoutOverlapping;use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Exceptions;+use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Queue;beforeEach(fn () => Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]));@@ -461,31 +464,190 @@ test('a stale page can reconcile facts but cannot move the current cursor backwa->and(AnalyticsPublication::query()->where('remote_id', 'stale-fact')->exists())->toBeTrue();});-test('a transient failure preserves the cursor for a later queue attempt', function () {- Bus::fake();- $account = SocialAccount::factory()->instagram()->create();- $state = AnalyticsSyncState::factory()->create([- 'social_account_id' => $account->id,- 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],- ]);+function bindFailingPublicationPage(SocialAccount $account, Throwable $failure): void+{$collector = Mockery::mock(AbstractPublicationHistoryCollector::class);$collector->shouldReceive('page')->once()->withArgs(fn (SocialAccount $received, ?string $cursor): bool => $received->is($account) && $cursor === 'resume-here',- )->andThrow(new AnalyticsCollectionException('transient', 'temporary'));+ )->andThrow($failure);$factory = Mockery::mock(PublicationHistoryCollectorFactory::class);$factory->shouldReceive('for')->once()->andReturn($collector);app()->instance(PublicationHistoryCollectorFactory::class, $factory);+}- expect(SocialAccount::query()->connected()->includedInAnalytics()->find($account->id))- ->not->toBeNull()- ->and($state->fresh()->status)->toBe(SyncStatus::Pending);+test('a transient failure dispatches a delayed retry and preserves the cursor', function (Throwable $failure) {+ Bus::fake();+ Exceptions::fake();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, $failure);- expect(fn () => app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']))- ->toThrow(AnalyticsCollectionException::class);+ expect($state->fresh()->status)->toBe(SyncStatus::Pending);+ $job = (new BackfillAccountPublications($account->id, $state->id))->withFakeQueueInteractions();+ app()->call([$job, 'handle']);++ $job->assertNotReleased();+ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->syncStateId === $state->id+ && $retry->transientRetries === 1+ && $retry->delay === 300);+ Exceptions::assertNothingReported();expect(data_get($state->fresh()->checkpoint, 'cursor'))->toBe('resume-here')->and($state->fresh()->status)->toBe(SyncStatus::Running)->and($state->fresh()->last_error_category)->toBe('transient');+})->with([+ 'provider 5xx' => fn () => new AnalyticsCollectionException('transient', 'publication history collection failed with HTTP 503'),+ 'connection reset' => fn () => new ConnectionException('cURL error 56: Recv failure: Connection reset by peer'),+]);++test('a rate limited failure waits for the provider retry time when it is later than the backoff', function () {+ Bus::fake();+ $this->freezeTime();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('rate_limited', 'slow down', CarbonImmutable::now()->addMinutes(20)));++ Log::spy();++ app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->delay === 1200);+ expect($state->fresh()->last_error_category)->toBe('rate_limited');+ Log::shouldHaveReceived('info')->withArgs(fn (string $message, array $context): bool => $message === 'analytics.collection'+ && data_get($context, 'category') === 'rate_limited'+ && data_get($context, 'retry_at') === CarbonImmutable::now('UTC')->addSeconds(1200)->toIso8601String())->once();+});++test('a provider retry time beyond the end of the day is capped at the end of the day', function () {+ Bus::fake();+ $this->travelTo(CarbonImmutable::parse('2026-10-07 12:00:00', 'UTC'));+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('rate_limited', 'slow down', CarbonImmutable::now('UTC')->addDays(30)));++ app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->delay === 43200);+});++test('a provider retry time later than the backoff but within the day is honoured', function () {+ Bus::fake();+ $this->travelTo(CarbonImmutable::parse('2026-10-07 12:00:00', 'UTC'));+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('rate_limited', 'slow down', CarbonImmutable::now('UTC')->addHours(6)));++ app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->delay === 21600);+});++test('a job queued before the retry counter existed still retries a transient failure', function () {+ Bus::fake();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('transient', 'temporary'));++ $queuedBeforeDeploy = (new ReflectionClass(BackfillAccountPublications::class))->newInstanceWithoutConstructor();+ $queuedBeforeDeploy->socialAccountId = $account->id;+ $queuedBeforeDeploy->syncStateId = $state->id;++ app()->call([$queuedBeforeDeploy, 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->transientRetries === 1);+});++test('the transient backoff follows our own retry counter', function () {+ Bus::fake();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('transient', 'temporary'));++ app()->call([new BackfillAccountPublications($account->id, $state->id, transientRetries: 2), 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->transientRetries === 3+ && $retry->delay === 7200);+});++test('middleware releases do not consume the transient retry cap', function () {+ Bus::fake();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('transient', 'temporary'));++ $job = (new BackfillAccountPublications($account->id, $state->id))->withFakeQueueInteractions();+ $job->job->attempts = 9;+ app()->call([$job, 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->transientRetries === 1+ && $retry->delay === 300);+ expect($state->fresh()->status)->toBe(SyncStatus::Running);+});++function maxTransientAnalyticsRetries(): int+{+ return (new ReflectionClassConstant(AbstractPublicationSync::class, 'MAX_TRANSIENT_RETRIES'))->getValue();+}++test('the last transient retry below the cap is still dispatched', function () {+ Bus::fake();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('transient', 'temporary'));++ app()->call([new BackfillAccountPublications($account->id, $state->id, transientRetries: maxTransientAnalyticsRetries() - 1), 'handle']);++ Bus::assertDispatched(BackfillAccountPublications::class, fn (BackfillAccountPublications $retry): bool => $retry->transientRetries === maxTransientAnalyticsRetries());+ expect($state->fresh()->status)->toBe(SyncStatus::Running);+});++test('a transient failure at the retry cap fails the sync so the scheduler restarts it', function () {+ Bus::fake();+ Exceptions::fake();+ $account = SocialAccount::factory()->instagram()->create();+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'resume-here', 'revision' => 0],+ ]);+ bindFailingPublicationPage($account, new AnalyticsCollectionException('transient', 'temporary'));++ $job = (new BackfillAccountPublications($account->id, $state->id, transientRetries: maxTransientAnalyticsRetries()))->withFakeQueueInteractions();+ app()->call([$job, 'handle']);++ $job->assertNotReleased();+ Bus::assertNotDispatched(BackfillAccountPublications::class);+ Exceptions::assertNothingReported();+ expect(data_get($state->fresh()->checkpoint, 'cursor'))->toBe('resume-here')+ ->and($state->fresh()->status)->toBe(SyncStatus::Failed)+ ->and($state->fresh()->last_error_category)->toBe('queue_failed');++ $this->artisan('analytics:dispatch-publication-discovery')->assertSuccessful();++ Bus::assertDispatched(BootstrapAccountAnalytics::class, fn (BootstrapAccountAnalytics $job): bool => $job->socialAccountId === $account->id);});test('an invalid provider cursor clears only the cursor and restarts the bounded backfill', function () {diff --git a/tests/Feature/Jobs/PublishLimitRetryTest.php b/tests/Feature/Jobs/PublishLimitRetryTest.phpindex 5b16db2ca..a4053aa21 100644--- a/tests/Feature/Jobs/PublishLimitRetryTest.php+++ b/tests/Feature/Jobs/PublishLimitRetryTest.php@@ -424,3 +424,35 @@ test('a refused tiktok publish_id is dropped so the retry starts a new publish',->and(PublishCheckpoint::tiktokPublishId($target->fresh()->error_context))->toBeNull()->and(data_get($target->fresh()->error_context, PublishCheckpoint::TIKTOK_STATUS))->toBeNull();});++test('a limit wait drops the x media checkpoint so the retry uploads the media again', function () {+ Queue::fake();+ $threadProgress = [['id' => '1', 'hash' => 'root-hash']];+ $target = limitRetryTarget($this, Platform::X, [+ 'error_context' => [+ PublishCheckpoint::X_MEDIA => ['media-1' => '1880000000000000000'],+ ThreadProgress::KEY => $threadProgress,+ ],+ ]);+ limitRetryPublisherThrows(XPublisher::class, XPublishException::fromApiResponse(limitRetryResponse(429, ['type' => 'https://api.twitter.com/2/problems/usage-capped', 'title' => 'Usage capped'])));++ (new PublishToSocialPlatform($target))->handle();++ $context = $target->fresh()->error_context;+ expect($target->fresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($context)->not->toHaveKey(PublishCheckpoint::X_MEDIA)+ ->and(PublishCheckpoint::xMedia($context))->toBe([])+ ->and(data_get($context, ThreadProgress::KEY))->toEqual($threadProgress)+ ->and(data_get($context, LimitRetryPolicy::ATTEMPTS_KEY))->toBe(1);+});++test('the scheduler unique attempts never collide with platform-unavailable attempts', function () {+ $largestProcessingBudget = max(+ (new ReflectionClassConstant(InstagramPublisher::class, 'STATUS_MAX_RETRIES'))->getValue(),+ (new ReflectionClassConstant(TikTokPublisher::class, 'STATUS_MAX_RETRIES'))->getValue(),+ (new ReflectionClassConstant(XPublisher::class, 'MEDIA_PROCESSING_MAX_RETRIES'))->getValue(),+ );++ expect(LimitRetryPolicy::UNIQUE_ATTEMPT_OFFSET)+ ->toBeGreaterThan($largestProcessingBudget + PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES);+});diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.phpindex d44249b1f..ad21559d1 100644--- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php+++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php@@ -13,9 +13,12 @@ use App\Enums\SocialAccount\Status as AccountStatus;use App\Enums\TikTok\PrivacyLevel;use App\Events\PostPlatformStatusUpdated;use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\ContentLimitException;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\InstagramPublishException;use App\Exceptions\Social\LinkedInPublishException;+use App\Exceptions\Social\SocialPublishException;+use App\Exceptions\Social\YouTubePublishException;use App\Exceptions\TokenExpiredException;use App\Jobs\PublishToSocialPlatform;use App\Jobs\SendNotification;@@ -223,10 +226,15 @@ test('publish keeps the vetted user message from a publish exception', functionexpect($this->postPlatform->error_message)->toBe('LinkedIn rejected this post.');});-test('publish reports caught publish exceptions so Nightwatch sees them', function (LinkedInPublishException $exception) {+test('publish reports an unmapped publish exception so Nightwatch sees it', function () {Event::fake();Exceptions::fake();+ $exception = new LinkedInPublishException(+ userMessage: 'Something LinkedIn has not told us about.',+ category: ErrorCategory::Unknown,+ );+$publisher = Mockery::mock(LinkedInPublisher::class);$publisher->shouldReceive('publish')->andThrow($exception);@@ -239,6 +247,46 @@ test('publish reports caught publish exceptions so Nightwatch sees them', functi$this->postPlatform->refresh();expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)->and($this->postPlatform->error_message)->toBe($exception->userMessage);+});++test('publish logs but does not report a documented rejection the user must act on', function (LinkedInPublishException $exception) {+ Event::fake();+ Exceptions::fake();+ Log::spy();++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow($exception);++ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform))->handle();++ Exceptions::assertNothingReported();+ Log::shouldHaveReceived('error')+ ->withArgs(fn (string $message, array $context): bool => $message === 'Social publish failed'+ && $context['exception'] === LinkedInPublishException::class)+ ->once();+ $this->postPlatform->refresh();+ expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)+ ->and($this->postPlatform->error_message)->toBe($exception->userMessage);+})->with([+ 'permission' => fn () => linkedInRejection(403),+]);++test('publish reports a failure that can be ours, even when categorized', function (SocialPublishException $exception) {+ Event::fake();+ Exceptions::fake();+ Log::spy();++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow($exception);++ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform))->handle();++ Exceptions::assertReported($exception::class);+ expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Failed);})->with(['server error' => fn () => new LinkedInPublishException(userMessage: 'LinkedIn could not process the media.',@@ -246,12 +294,58 @@ test('publish reports caught publish exceptions so Nightwatch sees them', functiplatformErrorCode: 'media-processing-timeout',rawResponse: '{"status":"ERROR"}',),- 'content policy' => fn () => new LinkedInPublishException(- userMessage: 'LinkedIn rejected this post.',- category: ErrorCategory::ContentPolicy,+ 'content over the limit at publish time' => fn () => ContentLimitException::exceeds(Platform::LinkedIn, 3000, 3200),+ 'our own media failure' => fn () => new LinkedInPublishException(+ userMessage: 'Unsupported video format.',+ category: ErrorCategory::MediaFormat,+ ),+ 'our own configuration failure' => fn () => new LinkedInPublishException(+ userMessage: 'LinkedIn organization ID not configured.',+ category: ErrorCategory::Permission,),+ 'a mapped server error' => fn () => linkedInRejection(500),+ 'a request LinkedIn could not process' => fn () => linkedInRejection(422),]);+test('publish reports a YouTube download that came back empty, though it is a media format failure', function () {+ Event::fake();+ Exceptions::fake();++ $account = SocialAccount::factory()->youtube()->create([+ 'workspace_id' => $this->workspace->id,+ 'token_expires_at' => now()->addDays(7),+ ]);+ $this->post->update(['content' => 'A short', 'media' => [[+ 'id' => 'video-1',+ 'type' => 'video',+ 'path' => 'medias/video.mp4',+ 'url' => 'https://example.com/video.mp4',+ 'mime_type' => 'video/mp4',+ 'original_filename' => 'video.mp4',+ ]]]);+ $postPlatform = PostPlatform::factory()->youtube()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $account->id,+ 'content_type' => ContentType::YouTubeShort,+ 'scheduled_before_media_checks' => true,+ ]);+ Http::fake(['https://example.com/video.mp4' => Http::response('tiny')]);++ (new PublishToSocialPlatform($postPlatform))->handle();++ Exceptions::assertReported(fn (YouTubePublishException $exception): bool => $exception->category === ErrorCategory::MediaFormat+ && str_contains($exception->userMessage, 'Downloaded video is too small or empty'));+ expect($postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);+});++function linkedInRejection(int $status): LinkedInPublishException+{+ return LinkedInPublishException::fromApiResponse(+ Http::fake(['*' => Http::response(['message' => 'Rejected', 'status' => $status], $status)])+ ->post(config('trypost.platforms.linkedin.api').'/rest/posts'),+ );+}+test('publish reports unexpected errors so Nightwatch sees them', function () {Event::fake();Exceptions::fake();@@ -269,7 +363,7 @@ test('publish reports unexpected errors so Nightwatch sees them', function () {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 () {+test('publish does not report a token expiry it settles', function () {Event::fake();Exceptions::fake();Mail::fake();@@ -285,11 +379,11 @@ test('publish reports token expiry so Nightwatch sees it', function () {(new PublishToSocialPlatform($this->postPlatform))->handle();- Exceptions::assertReportedCount(1);- Exceptions::assertReported(TokenExpiredException::class);+ Exceptions::assertNothingReported();+ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);});-test('publish reports a failed token refresh once', function () {+test('publish does not report a token refresh that confirms the token is dead', function () {Event::fake();Exceptions::fake();Mail::fake();@@ -304,8 +398,27 @@ test('publish reports a failed token refresh once', function () {(new PublishToSocialPlatform($this->postPlatform))->handle();+ Exceptions::assertNothingReported();+ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);+});++test('publish reports an unexpected error from the 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 RuntimeException('Refresh exploded'));+ $this->app->instance(ConnectionVerifier::class, $verifier);++ (new PublishToSocialPlatform($this->postPlatform))->handle();+Exceptions::assertReportedCount(1);- Exceptions::assertReported(fn (TokenExpiredException $e): bool => $e->getMessage() === 'Refresh failed');+ Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'Refresh exploded');expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);});@@ -629,7 +742,7 @@ test('publish honors a platform-specific retry delay and retry limit', function&& Carbon::instance($job->delay)->equalTo($now->copy()->addSeconds(30));});- $this->postPlatform->update(['error_context' => ['retry_count' => 2]]);+ $this->postPlatform->update(['error_context' => [...$this->postPlatform->error_context, 'processing_retry_count' => 2]]);(new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);@@ -694,10 +807,11 @@ test('publish preserves resumable context when a later transient error has no co->and($context['http_status'] ?? null)->toBe(503);});-test('publish preserves a resumable retry policy after the global retry limit', function () {+test('an unrelated outage after a processing reschedule does not inherit the processing retry policy', function () {Bus::fake([PublishToSocialPlatform::class]);Event::fake();Mail::fake();+ $this->freezeTime();$this->postPlatform->update(['error_context' => [@@ -705,7 +819,7 @@ test('publish preserves a resumable retry policy after the global retry limit','stage' => 'final_container','container_id' => 'container-123',],- 'retry_count' => 7,+ 'processing_retry_count' => 7,'max_retries' => 90,'retry_delay_seconds' => 10,],@@ -722,9 +836,135 @@ test('publish preserves a resumable retry policy after the global retry limit',$context = $this->postPlatform->fresh()->error_context;expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)- ->and($context['retry_count'] ?? null)->toBe(8)- ->and($context['max_retries'] ?? null)->toBe(90)- ->and($context['retry_delay_seconds'] ?? null)->toBe(10);+ ->and($context['instagram_workflow']['container_id'] ?? null)->toBe('container-123')+ ->and($context['retry_count'] ?? null)->toBe(1)+ ->and($context['processing_retry_count'] ?? null)->toBe(7)+ ->and($context)->not->toHaveKey('max_retries')+ ->and($context)->not->toHaveKey('retry_delay_seconds')+ ->and($context['next_attempt_at'] ?? null)->toBe(now()->addSeconds(600)->toIso8601String());+});++test('a processing reschedule keeps counting against its own retry policy', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();+ $this->freezeTime();++ $this->postPlatform->update([+ 'error_context' => ['retry_count' => 2, 'processing_retry_count' => 7, 'max_retries' => 30, 'retry_delay_seconds' => 60],+ ]);++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException('Still processing', retryDelaySeconds: 60, maxRetries: 30)+ );+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();++ $context = $this->postPlatform->fresh()->error_context;++ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($context['processing_retry_count'] ?? null)->toBe(8)+ ->and($context['retry_count'] ?? null)->toBe(2)+ ->and($context['max_retries'] ?? null)->toBe(30)+ ->and($context['retry_delay_seconds'] ?? null)->toBe(60)+ ->and($context['next_attempt_at'] ?? null)->toBe(now()->addSeconds(60)->toIso8601String());+});++test('alternating processing reschedules and outages still exhausts the outage retries', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();+ Mail::fake();++ $this->postPlatform->update([+ 'error_context' => ['retry_count' => 6, 'processing_retry_count' => 3, 'max_retries' => 30, 'retry_delay_seconds' => 60],+ ]);++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException('Service unavailable', 503)+ );+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();++ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);+ Bus::assertNotDispatched(PublishToSocialPlatform::class);+});++test('an outage after a processing reschedule is dispatched under a new unique attempt', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();++ $this->postPlatform->update([+ 'error_context' => ['processing_retry_count' => 1, 'max_retries' => 30, 'retry_delay_seconds' => 60],+ ]);++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException('Service unavailable', 503)+ );+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform->fresh(), 1))->handle();++ Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->uniqueAttempt === 2);+});++test('an outage on a status poll rescheduled before 2.0 restarts the outage retries', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();+ Mail::fake();+ $this->freezeTime();++ $this->postPlatform->update([+ 'error_context' => ['retry_count' => 40, 'max_retries' => 90, 'retry_delay_seconds' => 10],+ ]);++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException('Service unavailable', 503)+ );+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform->fresh(), 40))->handle();++ $context = $this->postPlatform->fresh()->error_context;++ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($context['retry_count'] ?? null)->toBe(1)+ ->and($context['processing_retry_count'] ?? null)->toBe(40)+ ->and($context)->not->toHaveKey('max_retries')+ ->and($context['next_attempt_at'] ?? null)->toBe(now()->addSeconds(600)->toIso8601String());++ Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->uniqueAttempt > 40);+});++test('a status poll rescheduled before 2.0 keeps counting its poll budget', function () {+ Bus::fake([PublishToSocialPlatform::class]);+ Event::fake();+ $this->freezeTime();++ $this->postPlatform->update([+ 'error_context' => ['retry_count' => 40, 'max_retries' => 90, 'retry_delay_seconds' => 10],+ ]);++ $publisher = Mockery::mock(LinkedInPublisher::class);+ $publisher->shouldReceive('publish')->andThrow(+ new PlatformUnavailableException('Still processing', retryDelaySeconds: 10, maxRetries: 90)+ );+ $this->app->instance(LinkedInPublisher::class, $publisher);++ (new PublishToSocialPlatform($this->postPlatform->fresh(), 40))->handle();++ $context = $this->postPlatform->fresh()->error_context;++ expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($context['processing_retry_count'] ?? null)->toBe(41)+ ->and((int) ($context['retry_count'] ?? 0))->toBe(0)+ ->and($context['max_retries'] ?? null)->toBe(90);++ Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->uniqueAttempt > 40);});test('post stays in Publishing while one platform is still Retrying', function () {@@ -2162,7 +2402,7 @@ test('a mastodon thread that fails midway is visible and its retry never posts a$failed = $target->fresh();expect($failed->status)->toBe(PlatformStatus::Failed)- ->and($failed->error_message)->toBe(__('posts.errors.thread_incomplete', ['published' => 2, 'total' => 3, 'error' => 'Media validation failed.']))+ ->and($failed->error_message)->toBe(__('posts.errors.thread_incomplete', ['published' => 2, 'total' => 3, 'error' => 'Validation failed']))->and(collect(data_get($failed->error_context, 'thread_progress'))->pluck('id')->all())->toBe(['1', '2']);Bus::fake([PublishToSocialPlatform::class]);diff --git a/tests/Feature/Jobs/SocialPublishingPipelineTest.php b/tests/Feature/Jobs/SocialPublishingPipelineTest.phpnew file mode 100644index 000000000..1ed08e74a--- /dev/null+++ b/tests/Feature/Jobs/SocialPublishingPipelineTest.php@@ -0,0 +1,211 @@+<?php++declare(strict_types=1);++use App\Enums\Post\Status as PostStatus;+use App\Enums\PostPlatform\ContentType;+use App\Enums\PostPlatform\Status as PlatformStatus;+use App\Enums\SocialAccount\Platform;+use App\Enums\SocialAccount\Status as AccountStatus;+use App\Enums\TikTok\PrivacyLevel;+use App\Exceptions\PlatformUnavailableException;+use App\Jobs\PublishPost;+use App\Jobs\PublishToSocialPlatform;+use App\Models\Media;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Models\SocialAccount;+use App\Services\Social\BlueskyPublisher;+use App\Services\Social\Discord\DiscordPublisher;+use App\Services\Social\FacebookPublisher;+use App\Services\Social\GoogleBusinessPublisher;+use App\Services\Social\InstagramPublisher;+use App\Services\Social\LinkedInPagePublisher;+use App\Services\Social\LinkedInPublisher;+use App\Services\Social\MastodonPublisher;+use App\Services\Social\PinterestPublisher;+use App\Services\Social\Telegram\TelegramPublisher;+use App\Services\Social\ThreadsPublisher;+use App\Services\Social\TikTokPublisher;+use App\Services\Social\XPublisher;+use App\Services\Social\YouTubePublisher;+use Illuminate\Http\Client\Request;+use Illuminate\Queue\WorkerOptions;+use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Exceptions;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Storage;++beforeEach(function () {+ $this->freezeTime();+ Storage::fake();+ Exceptions::fake();+ config()->set('queue.default', 'database');++ // Exercise serialization, queue middleware and the worker on the test database.+ Queue::swap(Queue::getFacadeRoot()->queue);+ $this->publishingQueue = Queue::connection('database');+ $this->publishingWorker = app('queue.worker');+ Bus::fake()->except([PublishPost::class, PublishToSocialPlatform::class]);+ $this->workerOptions = new WorkerOptions(sleep: 0, maxTries: 1);+});++function scheduledPipelineTarget(Platform $platform): PostPlatform+{+ $account = SocialAccount::factory()->create([+ 'platform' => $platform,+ 'scopes' => $platform->requiredPublishScopes(),+ ]);+ $post = Post::factory()->scheduled()->create([+ 'workspace_id' => $account->workspace_id,+ 'user_id' => $account->workspace->user_id,+ 'scheduled_at' => now()->subMinute(),+ 'content' => 'Publishing pipeline regression',+ ]);+ $contentType = ContentType::defaultFor($platform);++ if ($contentType->requiresMedia()) {+ $factory = Media::factory()->ownedByPost($post)->stored();+ if (in_array($platform, [Platform::TikTok, Platform::YouTube], true)) {+ $factory = $factory->video();+ }+ $media = $factory->create(['meta' => ['width' => 1080, 'height' => 1080, 'duration' => 15]]);+ $post->update(['media' => [$media->toArray()]]);+ }++ return PostPlatform::factory()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $account->id,+ 'platform' => $platform,+ 'content_type' => $contentType,+ 'meta' => $platform === Platform::TikTok ? ['privacy_level' => PrivacyLevel::SelfOnly->value] : [],+ ]);+}++test('each network queue consumes scheduled posts and delayed retries through the worker', function (Platform $platform, string $publisherClass) {+ $retrying = scheduledPipelineTarget($platform);+ $broken = scheduledPipelineTarget($platform);+ $retryCalls = 0;+ $publisher = Mockery::mock($publisherClass);+ $publisher->shouldReceive('publish')->times(4)->andReturnUsing(function (PostPlatform $target) use ($retrying, $broken, &$retryCalls): array {+ if ($target->is($retrying) && ++$retryCalls === 1) {+ throw new PlatformUnavailableException('Temporary outage');+ }+ if ($target->is($broken)) {+ throw new RuntimeException('Unexpected publisher failure');+ }++ return ['id' => 'published-'.$target->id, 'url' => 'https://example.com/published'];+ });+ $this->app->instance($publisherClass, $publisher);++ expect(config('horizon.defaults.supervisor-1.queue'))->toContain('default')+ ->and(config('horizon.defaults.social-publishing.queue'))->toContain($platform->queue());++ $this->artisan('posts:process-scheduled')->assertSuccessful();+ expect($this->publishingQueue->size('default'))->toBe(2);++ for ($i = 0; $i < 2; $i++) {+ $this->publishingWorker->runNextJob('database', 'default', $this->workerOptions);+ }++ expect($this->publishingQueue->size('default'))->toBe(0)+ ->and($this->publishingQueue->size($platform->queue()))->toBe(2);++ for ($i = 0; $i < 2; $i++) {+ $this->publishingWorker->runNextJob('database', $platform->queue(), $this->workerOptions);+ }++ expect($retrying->refresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($broken->refresh()->status)->toBe(PlatformStatus::Failed)+ ->and($this->publishingQueue->pendingSize($platform->queue()))->toBe(0)+ ->and($this->publishingQueue->delayedSize($platform->queue()))->toBe(1);++ $healthy = scheduledPipelineTarget($platform);+ $this->artisan('posts:process-scheduled')->assertSuccessful();+ $this->publishingWorker->runNextJob('database', 'default', $this->workerOptions);+ $this->publishingWorker->runNextJob('database', $platform->queue(), $this->workerOptions);++ expect($healthy->refresh()->status)->toBe(PlatformStatus::Published)+ ->and($healthy->post->status)->toBe(PostStatus::Published);++ $this->travel(10)->minutes();+ $this->publishingWorker->runNextJob('database', $platform->queue(), $this->workerOptions);++ expect($retrying->refresh()->status)->toBe(PlatformStatus::Published)+ ->and($retrying->post->status)->toBe(PostStatus::Published)+ ->and($this->publishingQueue->size($platform->queue()))->toBe(0);+ $this->assertDatabaseCount('failed_jobs', 0);+})->with([+ 'LinkedIn' => [Platform::LinkedIn, LinkedInPublisher::class],+ 'LinkedIn pages' => [Platform::LinkedInPage, LinkedInPagePublisher::class],+ 'X' => [Platform::X, XPublisher::class],+ 'TikTok' => [Platform::TikTok, TikTokPublisher::class],+ 'YouTube' => [Platform::YouTube, YouTubePublisher::class],+ 'Facebook' => [Platform::Facebook, FacebookPublisher::class],+ 'Instagram' => [Platform::Instagram, InstagramPublisher::class],+ 'Instagram via Facebook' => [Platform::InstagramFacebook, InstagramPublisher::class],+ 'Threads' => [Platform::Threads, ThreadsPublisher::class],+ 'Pinterest' => [Platform::Pinterest, PinterestPublisher::class],+ 'Bluesky' => [Platform::Bluesky, BlueskyPublisher::class],+ 'Mastodon' => [Platform::Mastodon, MastodonPublisher::class],+ 'Telegram' => [Platform::Telegram, TelegramPublisher::class],+ 'Discord' => [Platform::Discord, DiscordPublisher::class],+ 'Google Business' => [Platform::GoogleBusiness, GoogleBusinessPublisher::class],+]);++test('the TikTok worker publishes through the real publisher and token refresh flow', function (string $scenario) {+ $affected = scheduledPipelineTarget(Platform::TikTok);+ $affected->socialAccount->update(['token_expires_at' => now()->subMinute(), 'refresh_token' => 'affected-refresh']);+ $refreshCalls = 0;++ Http::fake(function (Request $request) use ($scenario, &$refreshCalls) {+ if (str_ends_with($request->url(), '/oauth/token/')) {+ $refreshCalls++;+ if ($scenario === 'dead refresh') {+ return Http::response(['error' => 'invalid_grant', 'error_description' => 'Refresh token revoked']);+ }+ if ($scenario === 'temporary refresh' && $refreshCalls === 1) {+ return Http::response(['error' => 'server_error'], 503);+ }++ return Http::response(['access_token' => 'renewed-token', 'refresh_token' => 'rotated-refresh', 'expires_in' => 86400]);+ }+ if (str_ends_with($request->url(), '/post/publish/video/init/')) {+ return Http::response(['data' => ['publish_id' => $request->hasHeader('Authorization', 'Bearer renewed-token') ? 'affected-publish' : 'healthy-publish']]);+ }+ if (str_ends_with($request->url(), '/post/publish/status/fetch/')) {+ return Http::response(['data' => ['status' => 'PUBLISH_COMPLETE', 'publicaly_available_post_id' => [$request['publish_id'].'-public']]]);+ }++ throw new RuntimeException('Unexpected TikTok request: '.$request->url());+ });++ $this->artisan('posts:process-scheduled')->assertSuccessful();+ $this->publishingWorker->runNextJob('database', 'default', $this->workerOptions);+ $this->publishingWorker->runNextJob('database', Platform::TikTok->queue(), $this->workerOptions);++ $healthy = scheduledPipelineTarget(Platform::TikTok);+ $this->artisan('posts:process-scheduled')->assertSuccessful();+ $this->publishingWorker->runNextJob('database', 'default', $this->workerOptions);+ $this->publishingWorker->runNextJob('database', Platform::TikTok->queue(), $this->workerOptions);++ expect($healthy->refresh()->status)->toBe(PlatformStatus::Published)+ ->and($healthy->socialAccount->status)->toBe(AccountStatus::Connected)+ ->and($healthy->post->status)->toBe(PostStatus::Published);++ if ($scenario === 'temporary refresh') {+ expect($affected->refresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($affected->socialAccount->status)->toBe(AccountStatus::Connected);+ $this->travel(10)->minutes();+ $this->publishingWorker->runNextJob('database', Platform::TikTok->queue(), $this->workerOptions);+ }++ expect($affected->refresh()->status)->toBe($scenario === 'dead refresh' ? PlatformStatus::Failed : PlatformStatus::Published)+ ->and($affected->socialAccount->status)->toBe($scenario === 'dead refresh' ? AccountStatus::TokenExpired : AccountStatus::Connected)+ ->and($this->publishingQueue->size(Platform::TikTok->queue()))->toBe(0);+ expect(Http::recorded(fn (Request $request) => str_ends_with($request->url(), '/post/publish/video/init/')))+ ->toHaveCount($scenario === 'dead refresh' ? 1 : 2);+ $this->assertDatabaseCount('failed_jobs', 0);+})->with(['successful refresh', 'dead refresh', 'temporary refresh']);diff --git a/tests/Feature/Posts/XLongPostTest.php b/tests/Feature/Posts/XLongPostTest.phpindex ba54eedfa..d7d80e988 100644--- a/tests/Feature/Posts/XLongPostTest.php+++ b/tests/Feature/Posts/XLongPostTest.php@@ -4,6 +4,7 @@ declare(strict_types=1);use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\Social\ContentLimitException;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;@@ -74,7 +75,8 @@ test('an account that lost premium fails the long post at publish', function ()]);Http::fake();- expect(fn () => (new XPublisher)->publish($postPlatform))->toThrow(Exception::class, 'limit of 280 characters');+ expect(fn () => (new XPublisher)->publish($postPlatform))+ ->toThrow(ContentLimitException::class, __('posts.errors.content_too_long', ['platform' => 'X', 'max' => 280, 'provided' => 2000]));Http::assertNothingSent();});diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.phpindex 22aad24fa..9886fc39f 100644--- a/tests/Feature/Services/Social/BlueskyPublisherTest.php+++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php@@ -608,7 +608,7 @@ test('bluesky publisher optimizes images before upload', function () {@unlink($tempFile);});-test('bluesky publisher handles media download failure gracefully', function () {+test('bluesky publisher stops publication when an image download fails', function () {$this->post->update(['media' => [[@@ -635,21 +635,10 @@ test('bluesky publisher handles media download failure gracefully', function ()return Http::response('Not Found', 404);});- // When media download fails, uploadBlob returns null and post publishes as text-only- $result = $this->publisher->publish($this->postPlatform);-- expect($result)->toHaveKey('id');- expect($result['id'])->toBe('3textonly');-- // The createRecord request should NOT contain an embed (no images uploaded)- Http::assertSent(function ($request) {- if (! str_contains($request->url(), 'createRecord')) {- return false;- }- $record = $request['record'];+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- return ! isset($record['embed']);- });+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));});test('bluesky publisher limits images to 4', function () {@@ -698,6 +687,42 @@ test('bluesky publisher limits images to 4', function () {});});+test('bluesky publisher never publishes a partial image set', function (string $failure) {+ $this->post->update(['media' => collect(['first', 'second'])->map(fn (string $id): array => [+ 'id' => $id,+ 'path' => "media/{$id}.gif",+ 'url' => "https://example.com/{$id}.gif",+ 'mime_type' => 'image/gif',+ 'original_filename' => "{$id}.gif",+ ])->all()]);++ $uploads = 0;+ Http::fake(function ($request) use (&$uploads, $failure) {+ if (str_contains($request->url(), 'uploadBlob')) {+ $uploads++;++ if ($uploads === 2) {+ return match ($failure) {+ 'refusal' => Http::response(['error' => 'BlobTooLarge'], 413),+ 'server error' => Http::response(['error' => 'InternalServerError'], 500),+ 'connection' => Http::failedConnection(),+ 'missing blob' => Http::response([]),+ };+ }++ return Http::response(['blob' => ['$type' => 'blob', 'ref' => ['$link' => 'first-blob'], 'mimeType' => 'image/gif', 'size' => 1024]]);+ }++ return Http::response(str_repeat('x', 1024));+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');++ expect($uploads)->toBe(2);+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));+})->with(['refusal', 'server error', 'connection', 'missing blob']);+/*** Attach a single video to the post under test (mp4 by default).*/@@ -807,7 +832,7 @@ test('bluesky publisher scopes the upload service-auth to the resolved PDS host'});});-test('bluesky publisher publishes text-only when video processing fails', function () {+test('bluesky publisher stops publication when video processing fails', function () {$this->post->update(['media' => [['id' => 'test-video-id',@@ -820,13 +845,10 @@ test('bluesky publisher publishes text-only when video processing fails', functifakeBlueskyVideoPipeline('JOB_STATE_FAILED');- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- // A failed transcode must not crash the job; the post still goes out as text.- Http::assertSent(function ($request) {- return str_contains($request->url(), 'createRecord')- && ! isset($request['record']['embed']);- });+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));});test('bluesky publisher retries a transient video transcode failure', function () {@@ -884,7 +906,7 @@ test('bluesky publisher retries a transient video transcode failure', function (});});-test('bluesky publisher skips an oversized video and publishes text-only', function () {+test('bluesky publisher stops publication for an oversized video', function () {attachBlueskyVideo($this->post);config(['trypost.platforms.bluesky.video_max_bytes' => 1024]);@@ -897,14 +919,14 @@ test('bluesky publisher skips an oversized video and publishes text-only', functreturn Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- // Oversized video is dropped before any upload; the post still goes out as text.- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));Http::assertNotSent(fn ($request) => str_contains($request->url(), 'app.bsky.video.uploadVideo'));});-test('bluesky publisher publishes text-only when the video download fails', function () {+test('bluesky publisher stops publication when the video download fails', function () {attachBlueskyVideo($this->post);Http::fake(function ($request) {@@ -912,17 +934,17 @@ test('bluesky publisher publishes text-only when the video download fails', funcreturn Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3dl', 'cid' => 'bafdl'], 200);}- // The CDN download 404s — no video, no service-auth, just text.return Http::response('Not Found', 404);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));Http::assertNotSent(fn ($request) => str_contains($request->url(), 'getServiceAuth'));});-test('bluesky publisher publishes text-only when service-auth minting fails', function () {+test('bluesky publisher stops publication when service-auth minting fails', function () {attachBlueskyVideo($this->post);Http::fake(function ($request) {@@ -941,10 +963,10 @@ test('bluesky publisher publishes text-only when service-auth minting fails', fureturn Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- // Without a service-auth token the upload can't proceed; degrade to text.- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));Http::assertNotSent(fn ($request) => str_contains($request->url(), 'app.bsky.video.uploadVideo'));});@@ -993,7 +1015,7 @@ test('bluesky publisher embeds the existing blob when upload returns 409 alreadyHttp::assertNotSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.getJobStatus'));});-test('bluesky publisher publishes text-only when upload returns no job id', function () {+test('bluesky publisher stops publication when upload returns no job id', function () {attachBlueskyVideo($this->post);config(['trypost.platforms.bluesky.video_poll_seconds' => 0]);@@ -1016,12 +1038,13 @@ test('bluesky publisher publishes text-only when upload returns no job id', funcreturn Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));});-test('bluesky publisher publishes text-only when getJobStatus errors', function () {+test('bluesky publisher stops publication when getJobStatus errors', function () {attachBlueskyVideo($this->post);config(['trypost.platforms.bluesky.video_poll_seconds' => 0]);@@ -1047,11 +1070,12 @@ test('bluesky publisher publishes text-only when getJobStatus errors', functionreturn Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');// A failing getJobStatus bails immediately rather than sleeping to timeout.Http::assertSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.getJobStatus'));- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));});test('bluesky publisher backs off while video processing remains pending', function () {@@ -1191,14 +1215,14 @@ test('bluesky publisher retries the upload up to three times before giving up',return Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- // Every attempt fails permanently → exactly VIDEO_UPLOAD_ATTEMPTS uploads, then text-only.expect($uploads)->toBe(3);- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));});-test('bluesky publisher times out and publishes text-only when the job never completes', function () {+test('bluesky publisher times out and stops publication when the job never completes', function () {attachBlueskyVideo($this->post);config(['trypost.platforms.bluesky.video_poll_seconds' => 0]);@@ -1225,9 +1249,10 @@ test('bluesky publisher times out and publishes text-only when the job never comreturn Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));});test('bluesky publisher falls back to the entryway when the DID document is unavailable', function () {@@ -1499,7 +1524,7 @@ test('bluesky publisher embeds images and skips the video when a post carries boHttp::assertNotSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo'));});-test('bluesky publisher publishes text-only when only the status token fails', function () {+test('bluesky publisher stops publication when only the status token fails', function () {attachBlueskyVideo($this->post);Http::fake(function ($request) {@@ -1521,10 +1546,10 @@ test('bluesky publisher publishes text-only when only the status token fails', freturn Http::response(str_repeat('v', 2048), 200);});- $this->publisher->publish($this->postPlatform);+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');- // Without the status token the upload can't be polled, so we never upload — degrade to text.- Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord') && ! isset($request['record']['embed']));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));Http::assertNotSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo'));});@@ -2040,6 +2065,57 @@ test('a bluesky thread resumes from the stored segments without posting the root&& data_get($request->data(), 'record.reply.parent') === ['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r2', 'cid' => 'c2']);});+test('a bluesky thread stops on reply media failure and resumes without repeating its root', function () {+ $image = [+ 'id' => 'reply-image',+ 'path' => 'media/reply.gif',+ 'url' => 'https://example.com/reply.gif',+ 'mime_type' => 'image/gif',+ 'original_filename' => 'reply.gif',+ ];+ $this->postPlatform->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]]]]]);++ $failUpload = true;+ $records = 0;+ Http::fake(function ($request) use (&$failUpload, &$records) {+ if (str_contains($request->url(), 'uploadBlob')) {+ return $failUpload+ ? Http::response(['error' => 'InternalServerError'], 500)+ : Http::response(['blob' => ['$type' => 'blob', 'ref' => ['$link' => 'reply-blob'], 'mimeType' => 'image/gif', 'size' => 1024]]);+ }++ if (str_contains($request->url(), 'getPostThread')) {+ return Http::response(['thread' => ['replies' => []]]);+ }++ if (str_contains($request->url(), 'createRecord')) {+ $records++;++ return Http::response(['uri' => "at://did:plc:testuser123/app.bsky.feed.post/r{$records}", 'cid' => "c{$records}"]);+ }++ return Http::response(str_repeat('x', 1024));+ });++ expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))+ ->toThrow(BlueskyPublishException::class);++ expect($records)->toBe(1)+ ->and(data_get($this->postPlatform->fresh()->error_context, 'thread_progress.0.id'))->toBe('r1');+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord')+ && data_get($request->data(), 'record.text') === 'Two');++ $failUpload = false;+ $result = $this->publisher->publish($this->postPlatform->fresh());++ expect($records)->toBe(2)+ ->and($result['id'])->toBe('r1')+ ->and($result['thread_reply_ids'])->toBe(['r2']);+ Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord')+ && data_get($request->data(), 'record.text') === 'Two'+ && data_get($request->data(), 'record.embed.images.0.image.ref.$link') === 'reply-blob');+});+function blueskyThreadCheckpoint(PostPlatform $postPlatform): void{ThreadProgress::remember($postPlatform, [diff --git a/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php b/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.phpindex 94480a9c8..81712ddab 100644--- a/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php+++ b/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php@@ -4,6 +4,7 @@ declare(strict_types=1);use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\Social\ContentLimitException;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;@@ -109,5 +110,9 @@ test('validateContentLength throws when content exceeds limit', function () {]);expect(fn () => $this->client->callValidateContentLength($postPlatform))- ->toThrow(Exception::class, '3000');+ ->toThrow(ContentLimitException::class, __('posts.errors.content_too_long', [+ 'platform' => Platform::LinkedIn->label(),+ 'max' => 3000,+ 'provided' => 4000,+ ]));});diff --git a/tests/Feature/Services/Social/ConnectionVerifierTest.php b/tests/Feature/Services/Social/ConnectionVerifierTest.phpindex 6210f536d..d8f273995 100644--- a/tests/Feature/Services/Social/ConnectionVerifierTest.php+++ b/tests/Feature/Services/Social/ConnectionVerifierTest.php@@ -170,6 +170,104 @@ test('refreshes tiktok token before verifying when expired', function () {Http::assertSent(fn ($request) => str_contains($request->url(), config('trypost.platforms.tiktok.api').'/oauth/token'));});+test('a tiktok refresh answered with a dead refresh token error expires the account, whatever the status', function (int $status, string $error) {+ Http::fake([+ config('trypost.platforms.tiktok.api').'/oauth/token/' => Http::response([+ 'error' => $error,+ 'error_description' => 'Refresh token is invalid or expired.',+ 'log_id' => '20261007182924',+ ], $status),+ ]);++ $account = SocialAccount::factory()->tiktok()->create([+ 'access_token' => 'old_token',+ 'token_expires_at' => now()->subHour(),+ 'refresh_token' => 'old_refresh_token',+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(function (TokenExpiredException $exception) use ($error): void {+ expect($exception->getMessage())->toBe('Refresh token is invalid or expired.')+ ->and($exception->platformErrorCode)->toBe($error);+ });++ expect($account->fresh()->access_token)->toBe('old_token');+})->with([200, 400])->with(['invalid_grant']);++test('a tiktok refresh answered with a json scalar stays transient', function (int $status) {+ Http::fake([+ config('trypost.platforms.tiktok.api').'/oauth/token/' => Http::response('"unexpected"', $status),+ ]);++ $account = SocialAccount::factory()->tiktok()->create([+ 'access_token' => 'old_token',+ 'token_expires_at' => now()->subHour(),+ 'refresh_token' => 'old_refresh_token',+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(PlatformUnavailableException::class);++ expect($account->fresh()->access_token)->toBe('old_token');+})->with([200, 400]);++test('a tiktok refresh answered with any error but invalid_grant stays transient, whatever the status', function (int $status, string $error) {+ Http::fake([+ config('trypost.platforms.tiktok.api').'/oauth/token/' => Http::response([+ 'error' => $error,+ 'error_description' => 'Something went wrong.',+ 'log_id' => '20261007182924',+ ], $status),+ ]);++ $account = SocialAccount::factory()->tiktok()->create([+ 'access_token' => 'old_token',+ 'token_expires_at' => now()->subHour(),+ 'refresh_token' => 'old_refresh_token',+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(PlatformUnavailableException::class);++ expect($account->fresh()->access_token)->toBe('old_token');+})->with([200, 400])->with(['server_error', 'temporarily_unavailable', 'invalid_client', 'invalid_request', 'access_denied']);++test('a tiktok refresh error body with non-string fields never breaks the classification', function (int $status, array $body, string $exception) {+ Http::fake([+ config('trypost.platforms.tiktok.api').'/oauth/token/' => Http::response($body, $status),+ ]);++ $account = SocialAccount::factory()->tiktok()->create([+ 'access_token' => 'old_token',+ 'token_expires_at' => now()->subHour(),+ 'refresh_token' => 'old_refresh_token',+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))->toThrow($exception);+})->with([+ 'array error on 200' => [200, ['error' => ['code' => 'x'], 'error_description' => ['a']], PlatformUnavailableException::class],+ 'array description on 200' => [200, ['error' => 'server_error', 'error_description' => ['a']], PlatformUnavailableException::class],+ 'array description on a dead token' => [400, ['error' => 'invalid_grant', 'error_description' => ['a']], TokenExpiredException::class],+ 'array description on a dead token with 200' => [200, ['error' => 'invalid_grant', 'error_description' => ['a']], TokenExpiredException::class],+]);++test('tiktok refresh answered with 200 and neither a token nor an error stays transient', function () {+ Http::fake([+ config('trypost.platforms.tiktok.api').'/oauth/token/' => Http::response(['log_id' => '20261007182924'], 200),+ ]);++ $account = SocialAccount::factory()->tiktok()->create([+ 'access_token' => 'old_token',+ 'token_expires_at' => now()->subHour(),+ 'refresh_token' => 'old_refresh_token',+ ]);++ expect(fn () => (new ConnectionVerifier)->refreshToken($account))+ ->toThrow(PlatformUnavailableException::class);++ expect($account->fresh()->access_token)->toBe('old_token');+});+test('refreshes pinterest token before verifying when expired', function () {Http::fake([config('trypost.platforms.pinterest.api').'/oauth/token' => Http::response([@@ -246,6 +344,25 @@ test('throws exception when x refresh fails', function () {->toThrow(TokenExpiredException::class, 'Failed to refresh X token');});+test('a refresh failure without a usable error_description falls back to the next message', function (array $body, string $expected) {+ Http::fake([+ config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response($body, 400),+ ]);++ $account = SocialAccount::factory()->linkedin()->create([+ 'token_expires_at' => now()->subHour(),+ 'refresh_token' => 'old_refresh_token',+ ]);++ expect(fn () => (new ConnectionVerifier)->verify($account))+ ->toThrow(fn (TokenExpiredException $exception) => expect($exception->getMessage())->toBe($expected));+})->with([+ 'empty description' => [['error_description' => '', 'error' => ['message' => 'Refresh token revoked']], 'Refresh token revoked'],+ 'array description' => [['error_description' => ['a'], 'error' => ['message' => 'Refresh token revoked']], 'Refresh token revoked'],+ 'empty description and no message' => [['error_description' => ''], 'Failed to refresh LinkedIn token'],+ 'non-string description and message' => [['error_description' => 42, 'error' => ['message' => ['a']]], 'Failed to refresh LinkedIn token'],+]);+test('does not refresh facebook token as it uses long-lived tokens', function () {Http::fake([config('trypost.platforms.facebook.graph_api').'/*' => Http::response(['id' => '123', 'name' => 'Test'], 200),diff --git a/tests/Feature/Services/Social/FacebookPublisherTest.php b/tests/Feature/Services/Social/FacebookPublisherTest.phpindex a2b95c905..298c2b017 100644--- a/tests/Feature/Services/Social/FacebookPublisherTest.php+++ b/tests/Feature/Services/Social/FacebookPublisherTest.php@@ -5,6 +5,7 @@ declare(strict_types=1);use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\FacebookPublishException;use App\Exceptions\TokenExpiredException;use App\Models\Post;@@ -439,6 +440,55 @@ test('facebook publisher waits for meta to fetch the video before finishing', fu]);})->with('facebook resumable video formats');+test('facebook publisher retries a rupload failure meta documents as retryable', function (int $status, array $body) {+ $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);+ $this->post->update(['media' => facebookVideoMedia()]);++ $rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');++ Http::fake([+ ...facebookVideoUploadFakes('video_reels'),+ "{$rupload}/*" => Http::response($body, $status),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(PlatformUnavailableException::class);++ Http::assertNotSent(fn ($request) => ($request['upload_phase'] ?? null) === 'finish');+})->with([+ 'retriable flag' => [400, ['debug_info' => ['retriable' => true, 'type' => 'OtherError', 'message' => 'Temporary failure']]],+ 'server error' => [503, ['debug_info' => ['retriable' => false, 'type' => 'ServiceUnavailable', 'message' => 'Service unavailable']]],+]);++test('facebook publisher fails a rupload error meta flags not retriable by its documented type', function (string $type, string $message, ErrorCategory $category) {+ $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);+ $this->post->update(['media' => facebookVideoMedia()]);++ $rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');++ Http::fake([+ ...facebookVideoUploadFakes('video_reels'),+ "{$rupload}/*" => Http::response(['debug_info' => [+ 'retriable' => false,+ 'type' => $type,+ 'message' => 'The video file could not be read from file_url.',+ ]], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(fn (FacebookPublishException $exception) => expect($exception->userMessage)+ ->toBe(__($message, ['platform' => Platform::Facebook->label()]))+ ->and($exception->category)->toBe($category)+ ->and($exception->platformErrorCode)->toBe($type));++ Http::assertNotSent(fn ($request) => ($request['upload_phase'] ?? null) === 'finish');+})->with([+ 'processing failed' => ['ProcessingFailedError', 'posts.errors.facebook.processing_failed', ErrorCategory::MediaFormat],+ 'partial request' => ['PartialRequestError', 'posts.errors.facebook.upload_incomplete', ErrorCategory::ServerError],+ 'invalid upload offset' => ['OffsetInvalidError', 'posts.errors.facebook.upload_incomplete', ErrorCategory::ServerError],+ 'undocumented type' => ['InvalidFileError', 'posts.errors.unrecognized_error', ErrorCategory::Unknown],+]);+test('facebook publisher fails when start does not return upload_url', function (ContentType $contentType, string $edge) {$this->postPlatform->update(['content_type' => $contentType]);$this->post->update(['media' => facebookVideoMedia()]);diff --git a/tests/Feature/Services/Social/InstagramPublisherTest.php b/tests/Feature/Services/Social/InstagramPublisherTest.phpindex 5c5e7a5c9..58ead9d65 100644--- a/tests/Feature/Services/Social/InstagramPublisherTest.php+++ b/tests/Feature/Services/Social/InstagramPublisherTest.php@@ -2,12 +2,15 @@declare(strict_types=1);+use App\Enums\Post\Status as PostStatus;use App\Enums\PostPlatform\ContentType;+use App\Enums\PostPlatform\Status as PlatformStatus;use App\Enums\SocialAccount\Platform;use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\InstagramPublishException;use App\Exceptions\TokenExpiredException;+use App\Jobs\PublishToSocialPlatform;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;@@ -18,6 +21,7 @@ use App\Services\Social\InstagramPublisher;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Request;use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Storage;use Intervention\Image\Drivers\Gd\Driver;use Intervention\Image\ImageManager;@@ -495,8 +499,8 @@ test('instagram publisher resumes a processing carousel child without recreating'processing_child_container_ids' => ['child-2'],],'instagram_status' => 'IN_PROGRESS',- ])->and($exception->retryDelaySeconds)->toBe(10)- ->and($exception->maxRetries)->toBe(90);+ ])->and($exception->retryDelaySeconds)->toBe(60)+ ->and($exception->maxRetries)->toBe(120);$this->postPlatform->update(['error_context' => $exception->context]);}@@ -659,7 +663,8 @@ test('instagram publisher handles media processing error', function () {expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(function (InstagramPublishException $exception): void {- expect($exception->getMessage())->toBe('Instagram media processing failed')+ expect($exception->getMessage())->toBe(__('posts.errors.instagram.processing_failed'))+ ->and($exception->category)->toBe(ErrorCategory::Unknown)->and($exception->rawResponse)->toContain('Media download has failed')->and($exception->rawResponse)->toContain('ERROR');});@@ -668,6 +673,88 @@ test('instagram publisher handles media processing error', function () {&& str_contains((string) data_get($request->data(), 'fields', ''), 'status'));});+test('instagram publisher explains a container error reported as an error subcode', function (string $status) {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-id',+ 'path' => 'media/2026-01/test-image.jpg',+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'test.jpg',+ ]],+ ]);++ $graph = config('trypost.platforms.instagram.graph_api');++ Http::fake([+ "{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),+ "{$graph}/container-123*" => Http::response(['status_code' => 'ERROR', 'status' => $status]),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(function (InstagramPublishException $exception): void {+ expect($exception->userMessage)->toBe('Unsupported video format. Please upload MP4 or MOV.')+ ->and($exception->category)->toBe(ErrorCategory::MediaFormat)+ ->and($exception->platformErrorCode)->toBe('2207026');+ });+})->with([+ 'bare subcode' => '2207026',+ 'padded subcode' => ' 2207026 ',+]);++test('instagram publisher never reads a subcode out of a container status sentence', function (string $status, ?string $code) {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-id',+ 'path' => 'media/2026-01/test-image.jpg',+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'test.jpg',+ ]],+ ]);++ $graph = config('trypost.platforms.instagram.graph_api');++ Http::fake([+ "{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),+ "{$graph}/container-123*" => Http::response(['status_code' => 'ERROR', 'status' => $status]),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(function (InstagramPublishException $exception) use ($status, $code): void {+ expect($exception->userMessage)->toBe(__('posts.errors.instagram.processing_failed'))+ ->and($exception->userMessage)->not->toContain($status)+ ->and($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->platformErrorCode)->toBe($code);+ });+})->with([+ 'subcode in a sentence' => ['Error: Media upload has failed with error code 2207026', null],+ 'unmapped bare subcode' => ['2207999', '2207999'],+]);++test('instagram publisher says processing failed when the container gives no reason', function () {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-id',+ 'path' => 'media/2026-01/test-image.jpg',+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'test.jpg',+ ]],+ ]);++ $graph = config('trypost.platforms.instagram.graph_api');++ Http::fake([+ "{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),+ "{$graph}/container-123*" => Http::response(['status_code' => 'ERROR']),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(fn (InstagramPublishException $exception) => expect($exception->userMessage)+ ->toBe(__('posts.errors.instagram.processing_failed')));+});+test('instagram publisher resumes media processing without creating another container', function () {$this->post->update(['media' => [@@ -707,8 +794,8 @@ test('instagram publisher resumes media processing without creating another cont'container_id' => 'container-123',],'instagram_status' => 'IN_PROGRESS',- ])->and($exception->retryDelaySeconds)->toBe(10)- ->and($exception->maxRetries)->toBe(90);+ ])->and($exception->retryDelaySeconds)->toBe(60)+ ->and($exception->maxRetries)->toBe(120);$this->postPlatform->update(['error_context' => $exception->context]);}@@ -756,6 +843,92 @@ test('instagram publisher does not publish a container that never finishes proceHttp::assertNotSent(fn ($request) => str_contains($request->url(), '/media_publish'));});+test('instagram retries long interruptions without abandoning or duplicating the container', function (int $minutes, string $interruption, bool $recovers) {+ Queue::fake();+ $this->freezeTime();+ $startedAt = now();+ $availableAt = $startedAt->copy()->addMinutes($minutes);+ $workflow = ['stage' => 'final_container', 'container_id' => 'container-123'];+ $this->post->update(['status' => PostStatus::Publishing]);+ $this->postPlatform->update(['error_context' => ['instagram_workflow' => $workflow]]);++ Http::fake(function (Request $request) use ($availableAt, $interruption, $recovers) {+ $unavailable = ! $recovers || now()->lt($availableAt);++ if (str_contains($request->url(), '/container-123')) {+ if ($unavailable && $interruption === 'connection') {+ throw new ConnectionException('Instagram is unreachable');+ }++ if ($unavailable && $interruption === 'status') {+ return Http::response(['error' => ['code' => 2, 'is_transient' => true]], 503);+ }++ return Http::response(['status_code' => $unavailable && $interruption === 'processing' ? 'IN_PROGRESS' : 'FINISHED']);+ }++ if (str_ends_with($request->url(), '/media_publish')) {+ if ($unavailable && $interruption === 'publish') {+ return Http::response(['error' => ['code' => 2, 'is_transient' => true]], 503);+ }++ return Http::response(['id' => 'media-123456789']);+ }++ if (str_contains($request->url(), '/media-123456789')) {+ return Http::response(['permalink' => 'https://www.instagram.com/p/ABC123/']);+ }++ throw new RuntimeException('Unexpected Instagram request: '.$request->url());+ });++ $job = new PublishToSocialPlatform($this->postPlatform);++ for ($minute = 0; $minute < $minutes; $minute++) {+ $job->handle();++ expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($this->postPlatform->error_context['instagram_workflow'])->toBe($workflow)+ ->and($this->postPlatform->error_context['processing_retry_count'])->toBe($minute + 1);++ $job = Queue::pushed(PublishToSocialPlatform::class)->last();++ expect($job->uniqueAttempt)->toBe($minute + 1)+ ->and($job->delay->equalTo(now()->addMinute()))->toBeTrue();++ $this->travelTo($job->delay);++ if ($minute >= 59) {+ $this->artisan('social:recover-stuck-posts')->assertSuccessful();++ expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($this->post->refresh()->status)->toBe(PostStatus::Publishing);+ }+ }++ expect(now()->equalTo($availableAt))->toBeTrue();+ $job->handle();++ expect($this->postPlatform->refresh()->status)->toBe($recovers ? PlatformStatus::Published : PlatformStatus::Failed)+ ->and($this->post->refresh()->status)->toBe($recovers ? PostStatus::Published : PostStatus::Failed);+ Queue::assertPushed(PublishToSocialPlatform::class, $minutes);+ Http::assertNotSent(fn (Request $request) => str_ends_with($request->url(), '/media'));+ expect(Http::recorded(fn (Request $request, $response) => str_ends_with($request->url(), '/media_publish')+ && $response->successful()))->toHaveCount($recovers ? 1 : 0);++ if (! $recovers) {+ expect($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))+ ->and($this->postPlatform->error_context['instagram_workflow'])->toBe($workflow);+ }+})->with([+ 'processing for 30 minutes' => [30, 'processing', true],+ 'status unavailable for over an hour' => [61, 'status', true],+ 'connection unavailable for over an hour' => [61, 'connection', true],+ 'publish unavailable for over an hour' => [61, 'publish', true],+ 'ready on the last retry' => [120, 'processing', true],+ 'still processing after two hours' => [120, 'processing', false],+]);+test('instagram publisher retries a transient Graph rate-limit on container status', function (int $code) {$this->post->update(['media' => [[@@ -831,6 +1004,92 @@ test('instagram publisher retries a transient Graph failure on media_publish', f});});+test('instagram publisher fails at once on a documented rejection sent under a transient Graph code', function (string $edge, int $code, int $subcode, ErrorCategory $category) {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-id',+ 'path' => 'media/2026-01/test-image.jpg',+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'test.jpg',+ ]],+ ]);++ $rejection = Http::response(['error' => ['message' => 'Rejected', 'code' => $code, 'error_subcode' => $subcode]], 400);++ Http::fake([+ 'https://graph.instagram.com/v25.0/ig_123456789/media' => $edge === 'media' ? $rejection : Http::response(['id' => 'container-123']),+ 'https://graph.instagram.com/v25.0/container-123*' => Http::response(['status_code' => 'FINISHED']),+ 'https://graph.instagram.com/v25.0/ig_123456789/media_publish' => $rejection,+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(function (InstagramPublishException $exception) use ($subcode, $category): void {+ expect($exception->platformErrorCode)->toBe((string) $subcode)+ ->and($exception->category)->toBe($category);+ });+})->with([+ 'activity restricted on media_publish' => ['media_publish', 4, 2207051, ErrorCategory::ContentPolicy],+ 'thumbnail offset on the container' => ['media', 1, 2207057, ErrorCategory::MediaFormat],+]);++test('instagram publisher still retries a documented server subcode sent under a transient Graph code', function () {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-id',+ 'path' => 'media/2026-01/test-image.jpg',+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'test.jpg',+ ]],+ ]);++ Http::fake([+ 'https://graph.instagram.com/v25.0/ig_123456789/media' => Http::response(['error' => ['message' => 'Server error', 'code' => 2, 'error_subcode' => 2207001]], 500),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(PlatformUnavailableException::class);+});++test('instagram publisher waits for a container media_publish reports as not ready yet', function () {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media-id',+ 'path' => 'media/2026-01/test-image.jpg',+ 'url' => 'https://example.com/media/2026-01/test-image.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'test.jpg',+ ]],+ ]);++ $graph = config('trypost.platforms.instagram.graph_api');++ Http::fake([+ "{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),+ "{$graph}/container-123*" => Http::response(['status_code' => 'FINISHED']),+ "{$graph}/ig_123456789/media_publish" => Http::response([+ 'error' => [+ 'message' => 'Media ID is not available',+ 'type' => 'OAuthException',+ 'code' => 9007,+ 'error_subcode' => 2207027,+ 'error_user_msg' => 'The media is not ready for publishing, please wait for a moment',+ ],+ ], 400),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(function (PlatformUnavailableException $exception): void {+ expect($exception->httpStatus)->toBe(400)+ ->and($exception->context)->toBe([+ 'instagram_workflow' => [+ 'stage' => 'final_container',+ 'container_id' => 'container-123',+ ],+ ]);+ });+});+test('instagram publisher retries a dropped connection on media_publish', function () {$this->post->update(['media' => [[@@ -1026,7 +1285,7 @@ test('instagram publisher fails a resumed container that reports ERROR', functioexpect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(function (InstagramPublishException $exception): void {- expect($exception->getMessage())->toBe('Instagram media processing failed')+ expect($exception->getMessage())->toBe(__('posts.errors.instagram.processing_failed'))->and($exception->rawResponse)->toContain('Media download has failed');});diff --git a/tests/Feature/Services/Social/LinkedInPublisherTest.php b/tests/Feature/Services/Social/LinkedInPublisherTest.phpindex 75181b6a6..7d89fb1ee 100644--- a/tests/Feature/Services/Social/LinkedInPublisherTest.php+++ b/tests/Feature/Services/Social/LinkedInPublisherTest.php@@ -5,6 +5,7 @@ declare(strict_types=1);use App\Enums\Media\Type as MediaType;use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\LinkedInPublishException;use App\Exceptions\TokenExpiredException;use App\Models\Post;@@ -1081,6 +1082,94 @@ test('linkedin publisher throws and does not post when document init fails', funHttp::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));});+test('linkedin publisher retries a LinkedIn 5xx while uploading media before the post exists', function (string $initPath, string $mimeType, string $file) {+ $this->post->update([+ 'media' => [[+ 'id' => 'media-1', 'path' => "media/2026-01/{$file}",+ 'url' => "https://example.com/media/2026-01/{$file}",+ 'mime_type' => $mimeType, 'original_filename' => $file,+ ]],+ ]);++ Http::fake(function ($request) use ($initPath) {+ if (str_contains($request->url(), $initPath)) {+ return Http::response(['message' => 'RestException{_response=RestResponse[status=500]}', 'status' => 500], 500);+ }++ return Http::response('fake-bytes', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(500));++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));+})->with([+ 'image' => ['/rest/images', 'image/jpeg', 'photo.jpg'],+ 'video' => ['/rest/videos', 'video/mp4', 'clip.mp4'],+ 'document' => ['/rest/documents', 'application/pdf', 'deck.pdf'],+]);++test('linkedin publisher retries a LinkedIn 5xx after the media upload starts and before the post exists', function (string $failingStep, string $mimeType, string $file) {+ $this->post->update([+ 'media' => [[+ 'id' => 'media-1', 'path' => "media/2026-01/{$file}",+ 'url' => "https://example.com/media/2026-01/{$file}",+ 'mime_type' => $mimeType, 'original_filename' => $file,+ ]],+ ]);++ $uploadUrls = [+ 'image upload' => 'https://www.linkedin.com/dms/upload/image/1',+ 'video chunk' => 'https://www.linkedin.com/dms/upload/video/1',+ 'document upload' => 'https://www.linkedin.com/dms/upload/document/1',+ ];++ Http::fake(function ($request) use ($failingStep, $uploadUrls) {+ $url = $request->url();+ $failingUrl = $failingStep === 'video finalize' ? 'finalizeUpload' : $uploadUrls[$failingStep];++ if (str_contains($url, $failingUrl)) {+ return Http::response(['message' => 'RestException{_response=RestResponse[status=503]}', 'status' => 503], 503);+ }++ if (str_contains($url, '/rest/images')) {+ return Http::response(['value' => ['uploadUrl' => $uploadUrls['image upload'], 'image' => 'urn:li:image:1']], 200);+ }++ if (str_contains($url, '/rest/videos') && str_contains($url, 'initializeUpload')) {+ return Http::response(['value' => [+ 'video' => 'urn:li:video:1',+ 'uploadToken' => 'upload-token',+ 'uploadInstructions' => [['uploadUrl' => $uploadUrls['video chunk'], 'firstByte' => 0, 'lastByte' => 9]],+ ]], 200);+ }++ if (str_contains($url, '/rest/documents') && str_contains($url, 'initializeUpload')) {+ return Http::response(['value' => ['uploadUrl' => $uploadUrls['document upload'], 'document' => 'urn:li:document:1']], 200);+ }++ if (in_array($url, $uploadUrls, true)) {+ return Http::response(null, 201, ['etag' => '"etag-1"']);+ }++ if (str_contains($url, '/rest/posts')) {+ return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:1']);+ }++ return Http::response('fake-bytes', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(503));++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));+})->with([+ 'image upload' => ['image upload', 'image/jpeg', 'photo.jpg'],+ 'video chunk' => ['video chunk', 'video/mp4', 'clip.mp4'],+ 'video finalize' => ['video finalize', 'video/mp4', 'clip.mp4'],+ 'document upload' => ['document upload', 'application/pdf', 'deck.pdf'],+]);+test('linkedin publisher throws when document init response is missing the urn', function () {$this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);$this->post->update([diff --git a/tests/Feature/Services/Social/MastodonPublisherTest.php b/tests/Feature/Services/Social/MastodonPublisherTest.phpindex 0585cf385..53f463076 100644--- a/tests/Feature/Services/Social/MastodonPublisherTest.php+++ b/tests/Feature/Services/Social/MastodonPublisherTest.php@@ -4,6 +4,9 @@ declare(strict_types=1);use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\ContentLimitException;+use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\MastodonPublishException;use App\Exceptions\TokenExpiredException;use App\Models\Post;@@ -104,7 +107,17 @@ test('mastodon publisher uploads media', function () {],]);+ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');+ copy($tempFile, $optimized);++ return $optimized;+ });+ app()->instance(MediaOptimizer::class, $mockOptimizer);+Http::fake([+ 'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),'https://mastodon.social/api/v1/media' => Http::response(['id' => 'media-123','type' => 'image',@@ -118,9 +131,8 @@ test('mastodon publisher uploads media', function () {$this->publisher->publish($this->postPlatform);- Http::assertSent(function ($request) {- return str_contains($request->url(), '/api/v1/statuses');- });+ Http::assertSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses')+ && data_get($request->data(), 'media_ids') === ['media-123']);});test('mastodon publisher sends capped alt text as media description', function () {@@ -371,7 +383,17 @@ test('mastodon publisher limits media to 4', function () {$this->post->update(['media' => $mediaItems]);+ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');+ copy($tempFile, $optimized);++ return $optimized;+ });+ app()->instance(MediaOptimizer::class, $mockOptimizer);+Http::fake([+ 'https://example.com/*' => fn () => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),'https://mastodon.social/api/v1/media' => Http::response(['id' => 'media-123','type' => 'image',@@ -384,10 +406,9 @@ test('mastodon publisher limits media to 4', function () {$this->publisher->publish($this->postPlatform);- // Should still publish successfully (media upload might fail but post should succeed)- Http::assertSent(function ($request) {- return str_contains($request->url(), '/api/v1/statuses');- });+ Http::assertSentCount(9);+ Http::assertSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses')+ && count(data_get($request->data(), 'media_ids', [])) === 4);});test('mastodon publisher handles empty content', function () {@@ -483,70 +504,84 @@ test('mastodon publisher optimizes images before upload', function () {@unlink($optimizedFile);});-test('mastodon publisher publishes text-only when media upload fails', function () {- // Minimal valid JPEG header so mime_content_type() detects image/jpeg- $minimalJpeg = "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"- ."\xFF\xDB\x00\x43\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\x09\x09\x08\x0A\x0C"- ."\x14\x0D\x0C\x0B\x0B\x0C\x19\x12\x13\x0F\x14\x1D\x1A\x1F\x1E\x1D\x1A\x1C\x1C\x20"- ."\xFF\xC0\x00\x0B\x08\x00\x01\x00\x01\x01\x01\x11\x00\xFF\xC4\x00\x1F\x00\x00\x01"- ."\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05"- ."\xFF\xDA\x00\x08\x01\x01\x00\x00\x3F\x00\xFB\xD3\xFF\xD9";+test('mastodon publisher retries a media upload server error before creating the status', function () {+ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');+ copy($tempFile, $optimized);- $optimizedFile = tempnam(sys_get_temp_dir(), 'masto_fail_opt_');- file_put_contents($optimizedFile, str_repeat('x', 512));+ return $optimized;+ });+ app()->instance(MediaOptimizer::class, $mockOptimizer);- $this->post->update([- 'media' => [- [- 'id' => 'test-media-fail',- 'path' => 'media/2026-01/failing-upload.jpg',- 'url' => 'https://example.com/media/2026-01/failing-upload.jpg',- 'mime_type' => 'image/jpeg',- 'original_filename' => 'failing-upload.jpg',- ],- ],- ]);+ $this->post->update(['media' => [[+ 'id' => 'test-media-fail',+ 'path' => 'media/2026-01/failing-upload.jpg',+ 'url' => 'https://example.com/media/2026-01/failing-upload.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'failing-upload.jpg',+ ]]]);- $this->mock(MediaOptimizer::class)- ->shouldReceive('optimizeImage')- ->once()- ->with(Mockery::any(), Platform::Mastodon)- ->andReturn($optimizedFile);+ Http::fake([+ 'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),+ 'https://mastodon.social/api/v1/media' => Http::response(['error' => 'Internal server error'], 500),+ 'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),+ ]);- Http::fake(function ($request) use ($minimalJpeg) {- $url = $request->url();+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(500));- // Media upload returns 500 — uploadMedia returns null- if (str_contains($url, '/api/v1/media')) {- return Http::response(['error' => 'Internal server error'], 500);- }+ Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses'));+});- if (str_contains($url, '/api/v1/statuses')) {- return Http::response([- 'id' => '999111222333',- 'url' => 'https://mastodon.social/@testuser/999111222333',- ], 200);- }+test('mastodon publisher fails with Mastodon\'s message when it refuses the media', function () {+ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'masto_opt_');+ copy($tempFile, $optimized);- // Media download — return valid JPEG bytes- return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);+ return $optimized;});+ app()->instance(MediaOptimizer::class, $mockOptimizer);- $result = $this->publisher->publish($this->postPlatform);+ $this->post->update(['media' => [[+ 'id' => 'test-media-refused',+ 'path' => 'media/2026-01/refused.jpg',+ 'url' => 'https://example.com/media/2026-01/refused.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'refused.jpg',+ ]]]);- // Post still succeeds as text-only- expect($result['id'])->toBe('999111222333');+ Http::fake([+ 'https://example.com/*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png')),+ 'https://mastodon.social/api/v1/media' => Http::response(['error' => 'Validation failed: File content type is invalid'], 422),+ 'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),+ ]);- // The statuses request should NOT include media_ids- Http::assertSent(function ($request) {- if (! str_contains($request->url(), '/api/v1/statuses')) {- return false;- }+ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(MastodonPublishException::class, 'Validation failed: File content type is invalid');- return ! isset($request->data()['media_ids']);- });+ Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses'));+});- @unlink($optimizedFile);+test('mastodon publisher fails instead of posting without the media it could not download', function () {+ $this->post->update(['media' => [[+ 'id' => 'test-media-missing',+ 'path' => 'media/2026-01/missing.jpg',+ 'url' => 'https://example.com/media/2026-01/missing.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'missing.jpg',+ ]]]);++ Http::fake([+ 'https://example.com/*' => Http::response('', 404),+ 'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),+ ]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(MastodonPublishException::class, __('posts.errors.media_unavailable', ['platform' => 'Mastodon']));++ Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/'));});test('mastodon publisher defaults to mastodon.social if no instance in meta', function () {@@ -610,7 +645,9 @@ test('mastodon refuses a post whose content and content warning exceed the limit$this->postPlatform->update(['meta' => ['spoiler_text' => str_repeat('a', 10)]]);Http::fake();- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(Exception::class, 'limit of');+ expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))+ ->toThrow(fn (ContentLimitException $exception) => expect($exception->category)->toBe(ErrorCategory::ContentPolicy)+ ->and($exception->userMessage)->toBe(__('posts.errors.content_too_long', ['platform' => 'Mastodon', 'max' => $limit, 'provided' => $limit + 1])));Http::assertNothingSent();});@@ -676,7 +713,8 @@ test('a mastodon thread with a reply over the limit fails before posting anythin$this->postPlatform->update(['meta' => ['thread_replies' => [str_repeat('a', 495)], 'spoiler_text' => 'Ten chars!']]);Http::fake();- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(Exception::class);+ expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))+ ->toThrow(ContentLimitException::class, __('posts.form.thread.reply_too_long', ['limit' => 490, 'over' => 5]));Http::assertNothingSent();});diff --git a/tests/Feature/Services/Social/TikTokPublisherTest.php b/tests/Feature/Services/Social/TikTokPublisherTest.phpindex 865ad1396..83706dcb9 100644--- a/tests/Feature/Services/Social/TikTokPublisherTest.php+++ b/tests/Feature/Services/Social/TikTokPublisherTest.php@@ -640,7 +640,9 @@ test('tiktok publisher throws TokenExpiredException when refresh_token is rejectHttp::fake([$this->api.'/oauth/token/' => Http::response([- 'error' => ['code' => 'invalid_grant', 'message' => 'Refresh token expired'],+ 'error' => 'invalid_grant',+ 'error_description' => 'Refresh token expired',+ 'log_id' => '20261007182924',], 400),]);diff --git a/tests/Feature/Services/Social/XPublisherTest.php b/tests/Feature/Services/Social/XPublisherTest.phpindex 791f17a3c..16c4fed2e 100644--- a/tests/Feature/Services/Social/XPublisherTest.php+++ b/tests/Feature/Services/Social/XPublisherTest.php@@ -3,9 +3,14 @@declare(strict_types=1);use App\Enums\PostPlatform\ContentType;+use App\Enums\PostPlatform\Status as PlatformStatus;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\ContentLimitException;+use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\XPublishException;use App\Exceptions\TokenExpiredException;+use App\Jobs\PublishToSocialPlatform;use App\Models\Post;use App\Models\PostPlatform;use App\Models\SocialAccount;@@ -13,9 +18,11 @@ use App\Models\User;use App\Models\Workspace;use App\Services\Media\MediaOptimizer;use App\Services\Social\XPublisher;+use App\Support\Social\PublishCheckpoint;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Request;use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Queue;use Illuminate\Support\Sleep;/**@@ -881,6 +888,55 @@ test('x publisher uses simple upload for small images and skips chunked finalize&& ! str_contains($request->url(), '/initialize'));});+test('x publisher fails instead of posting without the image when the simple upload returns no media id', function () {+ $this->post->update([+ 'media' => [+ [+ 'id' => 'test-media-image',+ 'path' => 'media/2026-01/photo.jpg',+ 'url' => 'https://example.com/media/2026-01/photo.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'photo.jpg',+ ],+ ],+ ]);++ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'x_opt_');+ copy($tempFile, $optimized);++ return $optimized;+ });+ app()->instance(MediaOptimizer::class, $mockOptimizer);++ Http::fake(function ($request) {+ if (str_contains($request->url(), '/media/upload')) {+ return Http::response(['data' => []], 200);+ }++ if (str_contains($request->url(), '/2/tweets')) {+ return Http::response(['data' => ['id' => 'tweet_without_image']], 200);+ }++ return Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200);+ });++ $exception = null;++ try {+ $this->publisher->publish($this->postPlatform);+ } catch (XPublishException $caught) {+ $exception = $caught;+ }++ expect($exception)->toBeInstanceOf(XPublishException::class)+ ->and($exception->userMessage)->toBe('X did not accept the media upload. Please try again.')+ ->and($exception->category)->toBe(ErrorCategory::ServerError)+ ->and($exception->isNetworkRejection())->toBeFalse();+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/tweets'));+});+test('x publisher uses chunked upload for images larger than 5MB', function () {$this->post->update(['media' => [@@ -1028,7 +1084,7 @@ test('x publisher fails when chunked finalize is rejected by X', function () {});expect(fn () => $this->publisher->publish($this->postPlatform))- ->toThrow(XPublishException::class, 'X rejected the media upload request');+ ->toThrow(XPublishException::class, 'Invalid request. Check your post content.');});test('x publisher fails when append is rejected by X', function () {@@ -1117,7 +1173,7 @@ 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 () {+test('x publisher reschedules media still processing with its media id as a checkpoint', function () {Sleep::fake();$this->post->update([@@ -1168,16 +1224,259 @@ test('x publisher times out media processing with the last status payload', func});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');+ ->toThrow(function (PlatformUnavailableException $exception): void {+ expect($exception->context)->toBe([+ PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_proc_timeout'],+ ]);});Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/tweets'));});+test('x publisher never waits longer than thirty seconds between media status checks', 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_slow']], 200);+ }++ if (str_contains($url, '/append')) {+ return Http::response(null, 204);+ }++ if (str_contains($url, '/finalize')) {+ return Http::response(['data' => ['id' => 'media_slow', 'processing_info' => ['state' => 'pending', 'check_after_secs' => 0]]], 200);+ }++ if (isXMediaUploadStatusRequest($request)) {+ return Http::response(['data' => ['processing_info' => ['state' => 'in_progress', 'check_after_secs' => 600]]], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(PlatformUnavailableException::class);++ Sleep::assertSlept(fn ($duration): bool => $duration->totalSeconds === 30.0, 20);+ Sleep::assertSleptTimes(20);+});++test('x publisher fails once instead of rescheduling when no status check ever succeeds', 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_status_broken']], 200);+ }++ if (str_contains($url, '/append')) {+ return Http::response(null, 204);+ }++ if (str_contains($url, '/finalize')) {+ return Http::response([+ 'data' => [+ 'id' => 'media_status_broken',+ 'processing_info' => ['state' => 'pending', 'check_after_secs' => 0],+ ],+ ], 200);+ }++ if (isXMediaUploadStatusRequest($request)) {+ return Http::response(['errors' => [['message' => 'Bad request']]], 400);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(XPublishException::class, 'X media processing timed out. Please try again.');+});++test('x publisher resumes checkpointed media without uploading it again', 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',+ ],+ ],+ ]);+ $this->postPlatform->update([+ 'error_context' => [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_ready']],+ ]);++ Http::fake(function ($request) {+ if (isXMediaUploadStatusRequest($request)) {+ return Http::response([+ 'data' => ['processing_info' => ['state' => 'succeeded']],+ ], 200);+ }++ if (str_contains($request->url(), '/2/tweets')) {+ return Http::response(['data' => ['id' => '1234567890123456789', 'text' => 'Hello from X!']], 200);+ }++ return Http::response('unexpected', 500);+ });++ $result = $this->publisher->publish($this->postPlatform->fresh());++ expect($result['id'])->toBe('1234567890123456789');+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/media/upload/initialize'));+ Http::assertSent(fn ($request) => str_contains($request->url(), '/2/tweets')+ && data_get($request->data(), 'media.media_ids') === ['media_ready']);+});++test('x status connection failures reschedule and resume the uploaded media', function (bool $checkpointed, int $failedCheck) {+ Sleep::fake();+ Queue::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',+ ]],+ ]);+ $this->postPlatform->forceFill([+ 'scheduled_before_media_checks' => true,+ 'error_context' => $checkpointed ? [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_ready']] : null,+ ])->save();++ $checks = 0;+ Http::fake(function ($request) use (&$checks, $failedCheck) {+ if (isXMediaUploadStatusRequest($request)) {+ if (++$checks === $failedCheck) {+ throw new ConnectionException('Timed out checking media');+ }++ return Http::response(['data' => ['processing_info' => ['state' => 'succeeded']]]);+ }++ if (str_contains($request->url(), '/initialize')) {+ return Http::response(['data' => ['id' => 'media_ready']]);+ }++ if (str_contains($request->url(), '/finalize')) {+ return Http::response(['data' => ['id' => 'media_ready', 'processing_info' => ['state' => 'pending']]]);+ }++ if (str_contains($request->url(), '/2/tweets')) {+ return Http::response(['data' => ['id' => 'tweet_ready']]);+ }++ return Http::response('fake-video-content');+ });++ (new PublishToSocialPlatform($this->postPlatform))->handle();++ expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Retrying)+ ->and($this->postPlatform->error_context[PublishCheckpoint::X_MEDIA])->toBe(['test-media-video' => 'media_ready'])+ ->and($this->postPlatform->error_context['retry_count'])->toBe(1);+ Queue::assertPushed(PublishToSocialPlatform::class, fn ($job) => $job->postPlatform->is($this->postPlatform)+ && $job->delay->isFuture());+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/tweets'));++ (new PublishToSocialPlatform($this->postPlatform, 1))->handle();++ expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Published);+ expect(Http::recorded(fn ($request) => str_contains($request->url(), '/initialize')))->toHaveCount($checkpointed ? 0 : 1);+ expect(Http::recorded(fn ($request) => str_contains($request->url(), '/2/tweets')))->toHaveCount(1);+})->with([+ 'checkpoint existence check' => [true, 1],+ 'checkpoint processing check' => [true, 2],+ 'first poll after upload' => [false, 1],+]);++test('x publisher uploads again when a checkpointed media id is no longer known to X', function (int $status) {+ 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',+ ],+ ],+ ]);+ $this->postPlatform->update([+ 'error_context' => [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_expired']],+ ]);++ Http::fake(function ($request) use ($status) {+ $url = $request->url();++ if (isXMediaUploadStatusRequest($request)) {+ return str_contains($url, 'media_expired')+ ? Http::response(['errors' => [['message' => 'Invalid media id']]], $status)+ : Http::response(['data' => ['processing_info' => ['state' => 'succeeded']]], 200);+ }++ if (str_contains($url, '/2/media/upload/initialize')) {+ return Http::response(['data' => ['id' => 'media_fresh']], 200);+ }++ if (str_contains($url, '/append')) {+ return Http::response(null, 204);+ }++ if (str_contains($url, '/finalize')) {+ return Http::response(['data' => ['id' => 'media_fresh', 'processing_info' => ['state' => 'pending', 'check_after_secs' => 0]]], 200);+ }++ if (str_contains($url, '/2/tweets')) {+ return Http::response(['data' => ['id' => '1234567890123456789', 'text' => 'Hello from X!']], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ $this->publisher->publish($this->postPlatform->fresh());++ Http::assertSent(fn ($request) => str_contains($request->url(), '/2/media/upload/initialize'));+ Http::assertSent(fn ($request) => str_contains($request->url(), '/2/tweets')+ && data_get($request->data(), 'media.media_ids') === ['media_fresh']);+})->with([400, 404]);+test('x publisher fails when tweet rejects invalid media ids', function () {$this->post->update(['media' => [@@ -1226,7 +1525,7 @@ test('x publisher fails when tweet rejects invalid media ids', function () {});expect(fn () => $this->publisher->publish($this->postPlatform))- ->toThrow(XPublishException::class, 'X rejected the attached media');+ ->toThrow(XPublishException::class, 'Invalid request. Check your post content.');});test('x publisher sends the tweet with links defused', function () {@@ -1264,7 +1563,9 @@ test('x publisher rejects a post that only fits before its links are defused', fHttp::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '1']], 200)]);expect(fn () => $this->publisher->publish($this->postPlatform))- ->toThrow(Exception::class, 'Content exceeds X limit of 280 characters (282 provided).');+ ->toThrow(fn (ContentLimitException $exception) => expect($exception->category)->toBe(ErrorCategory::ContentPolicy)+ ->and($exception->userMessage)->toBe(__('posts.errors.content_too_long', ['platform' => 'X', 'max' => 280, 'provided' => 282]))+ ->and($exception->platform())->toBe('x'));Http::assertNothingSent();});@@ -1357,7 +1658,8 @@ test('an x reply over the account limit is rejected before anything is posted',$this->postPlatform->update(['meta' => ['thread_replies' => [str_repeat('a', 281)]]]);Http::fake();- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(Exception::class);+ expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))+ ->toThrow(ContentLimitException::class, __('posts.form.thread.reply_too_long', ['limit' => 280, 'over' => 1]));Http::assertNothingSent();});@@ -1386,3 +1688,248 @@ test('an x post marked as ai generated discloses it with made_with_ai', function'marked' => [true, true],'not marked' => [false, false],]);++test('x publisher never uploads checkpointed media again when the status check fails for another reason', function (int $status, string $exception) {+ 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',+ ]],+ ]);+ $this->postPlatform->update([+ 'error_context' => [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_ready']],+ ]);++ Http::fake(function ($request) use ($status) {+ if (isXMediaUploadStatusRequest($request)) {+ return Http::response(['title' => 'Error', 'detail' => 'Error', 'status' => $status], $status);+ }++ return Http::response('fake-video-content', 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow($exception);++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/media/upload/initialize'));+})->with([+ 'rate limited' => [429, XPublishException::class],+ 'unauthorized' => [401, TokenExpiredException::class],+ 'server error' => [503, PlatformUnavailableException::class],+]);++function fakeXVideoUploadStuckWith(array $statusProcessingInfo): void+{+ Http::fake(function ($request) use ($statusProcessingInfo) {+ $url = $request->url();++ if (str_contains($url, '/2/media/upload/initialize')) {+ return Http::response(['data' => ['id' => 'media_video_1']], 200);+ }++ if (str_contains($url, '/append')) {+ return Http::response(null, 204);+ }++ if (str_contains($url, '/finalize')) {+ return Http::response([+ 'data' => [+ 'id' => 'media_video_1',+ 'processing_info' => ['state' => 'pending', 'check_after_secs' => 0],+ ],+ ], 200);+ }++ if (isXMediaUploadStatusRequest($request)) {+ return Http::response(['data' => ['processing_info' => $statusProcessingInfo]], 200);+ }++ if (str_contains($url, '/media/upload')) {+ return Http::response(['data' => ['id' => 'media_image_1']], 200);+ }++ if (str_contains($url, 'photo.jpg')) {+ return Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200);+ }++ return Http::response('fake-video-content', 200);+ });+}++test('x publisher reads processing_info only under data in the status response', 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_video_1']], 200);+ }++ if (str_contains($url, '/append')) {+ return Http::response(null, 204);+ }++ if (str_contains($url, '/finalize')) {+ return Http::response([+ 'data' => ['id' => 'media_video_1', 'processing_info' => ['state' => 'pending', 'check_after_secs' => 0]],+ ], 200);+ }++ if (isXMediaUploadStatusRequest($request)) {+ return Http::response(['processing_info' => ['state' => 'failed', 'error' => ['message' => 'Invalid media']]], 200);+ }++ if (str_contains($url, '/2/tweets')) {+ return Http::response(['data' => ['id' => '555']], 200);+ }++ return Http::response('fake-video-content', 200);+ });++ $result = $this->publisher->publish($this->postPlatform);++ expect($result['id'])->toBe('555')+ ->and(Http::recorded(fn (Request $request): bool => isXMediaUploadStatusRequest($request)))->toHaveCount(1);+});++test('x publisher reschedules media still processing under its own retry policy', 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',+ ]],+ ]);++ fakeXVideoUploadStuckWith(['state' => 'in_progress', 'check_after_secs' => 0]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(function (PlatformUnavailableException $exception): void {+ expect($exception->retryDelaySeconds)->toBe(60)+ ->and($exception->maxRetries)->toBe(30);+ });+});++test('x publisher keeps the media uploaded before the one still processing in the checkpoint', function () {+ Sleep::fake();++ $this->post->update([+ 'media' => [+ [+ 'id' => 'test-media-image',+ 'path' => 'media/2026-01/photo.jpg',+ 'url' => 'https://example.com/media/2026-01/photo.jpg',+ 'mime_type' => 'image/jpeg',+ 'original_filename' => 'photo.jpg',+ ],+ [+ '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',+ ],+ ],+ ]);++ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'x_opt_');+ copy($tempFile, $optimized);++ return $optimized;+ });+ app()->instance(MediaOptimizer::class, $mockOptimizer);++ fakeXVideoUploadStuckWith(['state' => 'in_progress', 'check_after_secs' => 0]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(function (PlatformUnavailableException $exception): void {+ expect($exception->context)->toBe([+ PublishCheckpoint::X_MEDIA => [+ 'test-media-image' => 'media_image_1',+ 'test-media-video' => 'media_video_1',+ ],+ ]);+ });+});++test('x publisher treats a processing state that is not a string as unknown', 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',+ ]],+ ]);++ fakeXVideoUploadStuckWith(['state' => ['name' => 'in_progress'], 'check_after_secs' => 0]);++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(XPublishException::class, 'X media processing timed out. Please try again.');+});++test('x publisher fails on a v1-shaped upload response without data.id', function (string $mimeType, string $url, string $uploadPath) {+ $this->post->update([+ 'media' => [[+ 'id' => 'test-media',+ 'path' => 'media/2026-01/file',+ 'url' => $url,+ 'mime_type' => $mimeType,+ 'original_filename' => basename($url),+ ]],+ ]);++ $mockOptimizer = Mockery::mock(MediaOptimizer::class);+ $mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {+ $optimized = tempnam(sys_get_temp_dir(), 'x_opt_');+ copy($tempFile, $optimized);++ return $optimized;+ });+ app()->instance(MediaOptimizer::class, $mockOptimizer);++ Http::fake(function ($request) use ($uploadPath) {+ if (str_contains($request->url(), $uploadPath)) {+ return Http::response(['media_id' => 710511363345354753, 'media_id_string' => '710511363345354753'], 200);+ }++ if (str_contains($request->url(), '/2/tweets')) {+ return Http::response(['data' => ['id' => 'tweet_without_media']], 200);+ }++ return Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200);+ });++ expect(fn () => $this->publisher->publish($this->postPlatform))+ ->toThrow(XPublishException::class, 'X did not accept the media upload. Please try again.');++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/append'));+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/tweets'));+})->with([+ 'simple upload' => ['image/jpeg', 'https://example.com/media/2026-01/photo.jpg', '/2/media/upload'],+ 'chunked initialize' => ['video/mp4', 'https://example.com/media/2026-01/clip.mp4', '/2/media/upload/initialize'],+]);diff --git a/tests/Feature/Services/Social/YouTubePublisherTest.php b/tests/Feature/Services/Social/YouTubePublisherTest.phpindex 80de2b1f3..2f3a85036 100644--- a/tests/Feature/Services/Social/YouTubePublisherTest.php+++ b/tests/Feature/Services/Social/YouTubePublisherTest.php@@ -4,6 +4,8 @@ declare(strict_types=1);use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Exceptions\PlatformUnavailableException;+use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\YouTubePublishException;use App\Exceptions\TokenExpiredException;use App\Models\Post;@@ -17,6 +19,7 @@ use App\Support\YouTubeMetadata;use Google\Client;use Illuminate\Http\Client\Request;use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;function fakeYouTubeUpload(array $responses = []): YouTubePublisher{@@ -503,3 +506,60 @@ test('a long youtube content becomes the description while the title stays short&& $payload['snippet']['description'] === trim(str_repeat('word ', 400));});});++test('a Google server error before the final chunk retries the upload', function (string $url, array $video) {+ Log::spy();+ $this->post->update(['media' => [$video]]);+ $publisher = fakeYouTubeUpload([+ 'https://example.com/video.mp4' => fn () => Http::response(str_repeat('x', $video['size'])),+ $url => Http::response([+ 'error' => ['code' => 503, 'message' => 'Backend Error', 'errors' => [['reason' => 'backendError', 'message' => 'Backend Error']]],+ ], 503),+ ]);++ expect(fn () => $publisher->publish($this->postPlatform->fresh()))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(503));++ Log::shouldNotHaveReceived('error', ['YouTube upload failed', Mockery::any()]);+})->with([+ 'starting the upload session' => [+ 'https://youtube.googleapis.com/upload/youtube/v3/videos*',+ ['id' => 'v', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'v.mp4', 'size' => 2048],+ ],+ 'a chunk before the last one' => [+ 'https://upload.example.test/session',+ ['id' => 'v', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'v.mp4', 'size' => 10 * 1024 * 1024 + 2048],+ ],+]);++test('a Google backendError below 500 retries the upload without an http status', function () {+ $publisher = fakeYouTubeUpload([+ 'https://youtube.googleapis.com/upload/youtube/v3/videos*' => Http::response([+ 'error' => ['code' => 400, 'message' => 'Backend Error', 'errors' => [['reason' => 'backendError', 'message' => 'Backend Error']]],+ ], 400),+ ]);+ $this->post->update(['media' => [[+ 'id' => 'v', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'v.mp4',+ ]]]);++ expect(fn () => $publisher->publish($this->postPlatform->fresh()))+ ->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBeNull());+});++test('a Google server error on the final chunk fails without retrying because the video may exist', function () {+ $this->post->update(['media' => [[+ 'id' => 'v', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'v.mp4',+ ]]]);+ $publisher = fakeYouTubeUpload([+ 'https://upload.example.test/session' => Http::response([+ 'error' => ['code' => 503, 'message' => 'Backend Error', 'errors' => [['reason' => 'backendError', 'message' => 'Backend Error']]],+ ], 503),+ ]);++ expect(fn () => $publisher->publish($this->postPlatform->fresh()))+ ->toThrow(function (YouTubePublishException $exception) {+ expect($exception->category)->toBe(ErrorCategory::ServerError)+ ->and($exception->userMessage)->toBe(__('posts.errors.youtube.upload_unconfirmed'))+ ->and($exception->platformErrorCode)->toBe('backendError');+ });+});diff --git a/tests/Unit/Enums/X/MediaProcessingStateTest.php b/tests/Unit/Enums/X/MediaProcessingStateTest.phpnew file mode 100644index 000000000..daa45eebf--- /dev/null+++ b/tests/Unit/Enums/X/MediaProcessingStateTest.php@@ -0,0 +1,19 @@+<?php++declare(strict_types=1);++use App\Enums\X\MediaProcessingState;++test('x media processing state matches the media upload status values', function () {+ expect(array_map(fn (MediaProcessingState $state): string => $state->value, MediaProcessingState::cases()))+ ->toBe(['pending', 'in_progress', 'succeeded', 'failed']);+});++test('only pending and in progress count as still processing', function (MediaProcessingState $state, bool $isProcessing) {+ expect($state->isProcessing())->toBe($isProcessing);+})->with([+ [MediaProcessingState::Pending, true],+ [MediaProcessingState::InProgress, true],+ [MediaProcessingState::Succeeded, false],+ [MediaProcessingState::Failed, false],+]);diff --git a/tests/Unit/Exceptions/Social/BlueskyPublishExceptionTest.php b/tests/Unit/Exceptions/Social/BlueskyPublishExceptionTest.phpindex 3aa52c9a2..e76631f15 100644--- a/tests/Unit/Exceptions/Social/BlueskyPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/BlueskyPublishExceptionTest.php@@ -79,3 +79,13 @@ test('platform returns bluesky', function () {expect($exception->platform())->toBe('bluesky');});++test('an invalid request and a rate limit from Bluesky are not network rejections', function (string $error, int $status) {+ $fakeResponse = Http::fake(['*' => Http::response(['error' => $error, 'message' => 'Rejected'], $status)])+ ->post(config('trypost.platforms.bluesky.default_service').'/xrpc/com.atproto.repo.createRecord');++ expect(BlueskyPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBeFalse();+})->with([+ 'our invalid request' => ['InvalidRequest', 400],+ 'an account or IP rate limit' => ['RateLimitExceeded', 429],+]);diff --git a/tests/Unit/Exceptions/Social/DiscordPublishExceptionTest.php b/tests/Unit/Exceptions/Social/DiscordPublishExceptionTest.phpnew file mode 100644index 000000000..ca1b288b1--- /dev/null+++ b/tests/Unit/Exceptions/Social/DiscordPublishExceptionTest.php@@ -0,0 +1,19 @@+<?php++declare(strict_types=1);++use App\Exceptions\Social\DiscordPublishException;+use Illuminate\Support\Facades\Http;++test('only a Discord rejection the server owner can fix is marked as a network rejection', function (int $status, int $code, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response(['code' => $code, 'message' => 'Rejected'], $status)])+ ->post(config('trypost.platforms.discord.api').'/channels/1/messages');++ expect(DiscordPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'bot missing permissions in the channel' => [403, 50013, true],+ 'attachment too large' => [413, 40005, true],+ 'an undocumented 413 without the attachment code' => [413, 0, false],+ 'a channel id we sent that does not exist' => [404, 10003, false],+ 'our bot rate limit' => [429, 0, false],+]);diff --git a/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php b/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.phpindex d1f6a491b..6db3e606f 100644--- a/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/FacebookPublishExceptionTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\SocialAccount\Platform;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\FacebookPublishException;use App\Exceptions\TokenExpiredException;@@ -171,3 +172,57 @@ test('subcode 463 throws TokenExpiredException', function () {FacebookPublishException::fromApiResponse($fakeResponse);})->throws(TokenExpiredException::class);++test('only a Graph code caused by the Page is marked as a network rejection', function (int $code, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'error' => ['code' => $code, 'message' => 'Rejected'],+ ], 400)])->post(config('trypost.platforms.facebook.graph_api').'/123/feed');++ expect(FacebookPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'unsupported video format' => [1363024, true],+ 'video above the maximum size' => [1363023, true],+ 'video below the minimum size' => [1363022, true],+ 'file is not a valid video' => [1363032, true],+ 'video too short' => [1363025, true],+ 'video too long' => [1363026, true],+ 'duplicate post' => [506, true],+ 'user request limit' => [17, true],+ 'Page BUC limit' => [80001, true],+ 'app request limit' => [4, false],+ 'user or app Page limit' => [32, false],+ 'application limit' => [341, false],+ 'custom limit' => [613, false],+ 'no video file in our request' => [1363020, false],+ 'upload problem to retry and report' => [6000, false],+ 'no permission to upload, fixed with a valid token' => [1363042, false],+ 'undocumented reel encoding code' => [1363047, false],+ 'undocumented caption code' => [1390008, false],+ 'undocumented rate limit' => [1349125, false],+]);++test('no rupload failure is marked as a network rejection', function (string $type) {+ $fakeResponse = Http::fake(['*' => Http::response(['debug_info' => ['type' => $type, 'message' => 'Failed']], 400)])+ ->post('https://'.config('trypost.platforms.facebook.rupload_host').'/video-upload/v25.0/1');++ expect(FacebookPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBeFalse();+})->with([+ 'processing failed' => ['ProcessingFailedError'],+ 'our partial request' => ['PartialRequestError'],+ 'invalid upload offset' => ['OffsetInvalidError'],+]);++test('a rupload failure without a usable type has no platform error code', function (mixed $type) {+ $fakeResponse = Http::fake(['*' => Http::response(['debug_info' => ['type' => $type, 'message' => 'Failed']], 400)])+ ->post('https://'.config('trypost.platforms.facebook.rupload_host').'/video-upload/v25.0/1');++ $exception = FacebookPublishException::fromApiResponse($fakeResponse);++ expect($exception->platformErrorCode)->toBeNull()+ ->and($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->userMessage)->toBe(__('posts.errors.unrecognized_error', ['platform' => Platform::Facebook->label()]));+})->with([+ 'empty type' => [''],+ 'array type' => [['ProcessingFailedError']],+ 'integer type' => [42],+]);diff --git a/tests/Unit/Exceptions/Social/GoogleBusinessPublishExceptionTest.php b/tests/Unit/Exceptions/Social/GoogleBusinessPublishExceptionTest.phpindex bda197e29..55f06f6a3 100644--- a/tests/Unit/Exceptions/Social/GoogleBusinessPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/GoogleBusinessPublishExceptionTest.php@@ -91,3 +91,15 @@ test('isConfirmedDeadToken is false for PERMISSION_DENIED status', function () {expect(GoogleBusinessPublishException::isConfirmedDeadToken($fakeResponse))->toBeFalse();});++test('no Google Business error is marked as a network rejection', function (string $reason, int $status) {+ $fakeResponse = Http::fake(['*' => Http::response(['error' => ['status' => $reason, 'message' => 'Rejected']], $status)])+ ->post(config('trypost.platforms.google_business.local_posts_api').'/accounts/1/locations/2/localPosts');++ expect(GoogleBusinessPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBeFalse();+})->with([+ 'permission denied, also returned for our project' => ['PERMISSION_DENIED', 403],+ 'a location we sent that does not exist' => ['NOT_FOUND', 404],+ 'an argument we sent' => ['INVALID_ARGUMENT', 400],+ 'our project quota' => ['RESOURCE_EXHAUSTED', 429],+]);diff --git a/tests/Unit/Exceptions/Social/InstagramPublishExceptionTest.php b/tests/Unit/Exceptions/Social/InstagramPublishExceptionTest.phpindex eb376431a..4fbcb219f 100644--- a/tests/Unit/Exceptions/Social/InstagramPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/InstagramPublishExceptionTest.php@@ -182,3 +182,37 @@ test('platform returns instagram', function () {expect($exception->platform())->toBe('instagram');});++test('only an Instagram error caused by the account is marked as a network rejection', function (int $code, ?int $subcode, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'error' => array_filter(['code' => $code, 'error_subcode' => $subcode, 'message' => 'Rejected']),+ ], 400)])->post(config('trypost.platforms.instagram.graph_api').'/123/media');++ expect(InstagramPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'unsupported video format' => [352, 2207026, true],+ 'image too large' => [36000, 2207004, true],+ 'unsupported aspect ratio' => [36003, 2207009, true],+ 'thumbnail offset outside the video' => [1, 2207057, true],+ 'carousel item count' => [100, 2207028, true],+ 'activity restricted to protect the community' => [4, 2207051, true],+ 'too many tags' => [100, 2207040, true],+ 'undocumented trial reels subcode' => [100, 2207081, false],+ 'caption too long' => [36004, 2207010, true],+ 'daily publishing limit' => [9, 2207042, true],+ 'account restricted' => [25, 2207050, true],+ 'user request limit' => [17, null, true],+ 'Instagram BUC limit' => [80002, null, true],+ 'the media type we send' => [100, 2207023, false],+ 'product tags we never send' => [100, 2207037, false],+ 'image format whose fix is a permission or token' => [36001, 2207005, false],+ 'app request limit' => [4, null, false],+ 'server error' => [-1, 2207001, false],+]);++test('a container status is marked only for a subcode caused by the account', function (int $status, bool $marked) {+ expect(InstagramPublishException::fromContainerStatus($status, null)->isNetworkRejection())->toBe($marked);+})->with([+ 'unsupported video format' => [2207026, true],+ 'the media type we send' => [2207023, false],+]);diff --git a/tests/Unit/Exceptions/Social/LinkedInPublishExceptionTest.php b/tests/Unit/Exceptions/Social/LinkedInPublishExceptionTest.phpindex 26d9f7a40..ec52e14ca 100644--- a/tests/Unit/Exceptions/Social/LinkedInPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/LinkedInPublishExceptionTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\SocialAccount\Platform;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\LinkedInPublishException;use App\Exceptions\TokenExpiredException;@@ -28,18 +29,18 @@ test('HTTP 403 maps to Permission category', function () {->and($exception->userMessage)->toBe('Not authorized to post to this account.');});-test('body containing "Unable to obtain activity" maps to ServerError category', function () {+test('a 400 saying "Unable to obtain activity" is not a server error', function () {$response = Http::response(['message' => 'Unable to obtain activity for URN'], 400);$fakeResponse = Http::fake(['*' => $response])->post('https://api.linkedin.com/test');$exception = LinkedInPublishException::fromApiResponse($fakeResponse);- expect($exception->category)->toBe(ErrorCategory::ServerError)- ->and($exception->userMessage)->toBe('LinkedIn server error. Please try again.');+ expect($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->userMessage)->toBe('Unable to obtain activity for URN');});-test('unknown error maps to Unknown category with response body as message', function () {+test('an unmapped error shows the message LinkedIn sent', function () {$response = Http::response(['message' => 'Something went wrong.'], 400);$fakeResponse = Http::fake(['*' => $response])->post('https://api.linkedin.com/test');@@ -61,8 +62,8 @@ test('HTTP 422 maps to ContentPolicy category', function () {->and($exception->userMessage)->toBe('Invalid post data. Please check your content.');});-test('body containing "resource is forbidden" maps to Permission category', function () {- $response = Http::response(['message' => 'The resource is forbidden'], 403);+test('a 403 maps to Permission by its status, whatever the message', function () {+ $response = Http::response(['message' => 'Something else entirely'], 403);$fakeResponse = Http::fake(['*' => $response])->post('https://api.linkedin.com/test');@@ -72,6 +73,20 @@ test('body containing "resource is forbidden" maps to Permission category', func->and($exception->userMessage)->toBe('Not authorized to post to this account.');});+test('a LinkedIn 5xx maps to ServerError without the raw RestException dump', function () {+ $body = ['message' => 'RestException{_response=RestResponse[headers={content-length=17616, content-type=application/json, x-restli-error-response=true},cookies=[],status=500,entityLength=17616]}', 'status' => 500];++ $fakeResponse = Http::fake(['*' => Http::response($body, 500)])+ ->post(config('trypost.platforms.linkedin.api').'/rest/posts');++ $exception = LinkedInPublishException::fromApiResponse($fakeResponse);++ expect($exception->category)->toBe(ErrorCategory::ServerError)+ ->and($exception->userMessage)->toBe(__('posts.errors.linkedin.server_error'))+ ->and($exception->userMessage)->not->toContain('RestException')+ ->and($exception->rawResponse)->toContain('RestException');+});+test('platform returns linkedin', function () {$response = Http::response(['message' => 'Some error'], 400);@@ -81,3 +96,33 @@ test('platform returns linkedin', function () {expect($exception->platform())->toBe('linkedin');});++test('only a status LinkedIn documents as caused by the member is marked as a network rejection', function (int $status, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response(['message' => 'Rejected'], $status)])+ ->post(config('trypost.platforms.linkedin.api').'/rest/posts');++ expect(LinkedInPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'permission' => [403, true],+ 'semantic errors in our fields' => [422, false],+ 'member or application limit' => [429, false],+ 'server error' => [500, false],+ 'unknown' => [400, false],+]);++test('an exception we raise ourselves is never a network rejection', function () {+ $exception = new LinkedInPublishException(userMessage: 'LinkedIn organization ID not configured.', category: ErrorCategory::Permission);++ expect($exception->isNetworkRejection())->toBeFalse();+});++test('an unmapped error without a message shows the generic message', function (array $body) {+ $fakeResponse = Http::fake(['*' => Http::response($body, 400)])+ ->post(config('trypost.platforms.linkedin.api').'/rest/posts');++ expect(LinkedInPublishException::fromApiResponse($fakeResponse)->userMessage)+ ->toBe(__('posts.errors.unrecognized_error', ['platform' => Platform::LinkedIn->label()]));+})->with([+ 'no message' => [['status' => 400]],+ 'an empty message' => [['message' => ' ', 'status' => 400]],+]);diff --git a/tests/Unit/Exceptions/Social/MastodonPublishExceptionTest.php b/tests/Unit/Exceptions/Social/MastodonPublishExceptionTest.phpindex 882932e8f..7b35d1c97 100644--- a/tests/Unit/Exceptions/Social/MastodonPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/MastodonPublishExceptionTest.php@@ -54,14 +54,21 @@ test('HTTP 429 maps to RateLimit category', function () {->and($exception->userMessage)->toBe('Rate limit exceeded. Please try again later.');});-test('HTTP 422 without text blank maps to MediaFormat category', function () {- $response = Http::response(['error' => 'Validation failed'], 422);+test('HTTP 422 without text blank shows Mastodon\'s own validation message as Unknown', function () {+ $response = Http::response(['error' => 'Validation failed: Visibility is not included in the list'], 422);$fakeResponse = Http::fake(['*' => $response])->post('https://mastodon.social/api/v1/statuses');$exception = MastodonPublishException::fromApiResponse($fakeResponse);- expect($exception->category)->toBe(ErrorCategory::MediaFormat)- ->and($exception->userMessage)->toBe('Media validation failed.');+ expect($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->userMessage)->toBe('Validation failed: Visibility is not included in the list');+});++test('HTTP 422 without a message falls back to the generic translated one', function () {+ $fakeResponse = Http::fake(['*' => Http::response([], 422)])->post('https://mastodon.social/api/v1/statuses');++ expect(MastodonPublishException::fromApiResponse($fakeResponse)->userMessage)+ ->toBe(__('posts.errors.unrecognized_error', ['platform' => 'Mastodon']));});test('unknown status maps to Unknown category with error message', function () {@@ -82,3 +89,15 @@ test('platform returns mastodon', function () {expect($exception->platform())->toBe('mastodon');});++test('no Mastodon failure is marked as a network rejection', function (int $status) {+ $fakeResponse = Http::fake(['*' => Http::response(['error' => 'Validation failed: File content type is invalid'], $status)])+ ->post(config('trypost.platforms.mastodon.default_instance').'/api/v2/media');++ expect(MastodonPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBeFalse();+})->with([+ 'generic validation failure, which also covers our payload' => [422],+ 'undocumented file too large' => [413],+ 'undocumented forbidden' => [403],+ 'an account or IP rate limit' => [429],+]);diff --git a/tests/Unit/Exceptions/Social/PinterestPublishExceptionTest.php b/tests/Unit/Exceptions/Social/PinterestPublishExceptionTest.phpindex b3ca5123b..7127ef138 100644--- a/tests/Unit/Exceptions/Social/PinterestPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/PinterestPublishExceptionTest.php@@ -68,13 +68,15 @@ test('processing status failed maps to MediaFormat category', function () {$exception = PinterestPublishException::fromProcessingStatus('failed');expect($exception->category)->toBe(ErrorCategory::MediaFormat)- ->and($exception->userMessage)->toBe('Media processing failed. Please try a different file.');+ ->and($exception->userMessage)->toBe('Media processing failed. Please try a different file.')+ ->and($exception->isNetworkRejection())->toBeTrue();});test('processing status unknown maps to Unknown category', function () {$exception = PinterestPublishException::fromProcessingStatus('pending', 'raw response');- expect($exception->category)->toBe(ErrorCategory::Unknown);+ expect($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->isNetworkRejection())->toBeFalse();});test('HTTP 500 maps to ServerError category', function () {@@ -92,3 +94,15 @@ test('platform returns pinterest', function () {expect($exception->platform())->toBe('pinterest');});++test('only a Pinterest rejection caused by the user is marked as a network rejection', function (int $status, array $body, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response($body, $status)])+ ->post(config('trypost.platforms.pinterest.api').'/pins');++ expect(PinterestPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'user lacks permission' => [403, ['code' => 403, 'message' => 'Forbidden'], true],+ 'undocumented code 1' => [400, ['code' => 1, 'message' => "Sorry! This site doesn't allow you to save Pins."], false],+ 'a board we sent that does not exist' => [404, ['code' => 404, 'message' => 'Not found'], false],+ 'rate limit' => [429, ['code' => 429, 'message' => 'Too many requests'], false],+]);diff --git a/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php b/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.phpindex b4e345073..2b9f1cbcd 100644--- a/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/SocialPublishExceptionTest.php@@ -139,3 +139,22 @@ test('error category tryFromContext reads a stored category', function (?array $'missing' => [[], null],'null context' => [null, null],]);++test('a code the mapper lists as caused by the user is marked only when its category needs the user', function (ErrorCategory $category, bool $marked) {+ $exception = (new TestPlatformException(userMessage: 'Rejected.', category: $category))->asNetworkRejectionIf(true);++ expect($exception->isNetworkRejection())->toBe($marked);+})->with([+ 'media format' => [ErrorCategory::MediaFormat, true],+ 'rate limit' => [ErrorCategory::RateLimit, true],+ 'permission' => [ErrorCategory::Permission, true],+ 'content policy' => [ErrorCategory::ContentPolicy, true],+ 'unknown' => [ErrorCategory::Unknown, false],+ 'server error' => [ErrorCategory::ServerError, false],+]);++test('a code the mapper does not list as caused by the user is never marked', function () {+ $exception = (new TestPlatformException(userMessage: 'Rejected.', category: ErrorCategory::Permission))->asNetworkRejectionIf(false);++ expect($exception->isNetworkRejection())->toBeFalse();+});diff --git a/tests/Unit/Exceptions/Social/TelegramPublishExceptionTest.php b/tests/Unit/Exceptions/Social/TelegramPublishExceptionTest.phpindex 3be8f1d87..bc4c4cc4d 100644--- a/tests/Unit/Exceptions/Social/TelegramPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/TelegramPublishExceptionTest.php@@ -62,3 +62,10 @@ test('platform returns telegram', function () {expect($exception->platform())->toBe('telegram');});++test('no Telegram failure is marked as a network rejection, since the Bot API documents no error codes', function (int $status) {+ expect(TelegramPublishException::fromApiResponse(telegramErrorResponse(['ok' => false, 'description' => 'Rejected'], $status))->isNetworkRejection())->toBeFalse();+})->with([+ 'bot not an admin' => [403],+ 'our bot flood limit' => [429],+]);diff --git a/tests/Unit/Exceptions/Social/ThreadsPublishExceptionTest.php b/tests/Unit/Exceptions/Social/ThreadsPublishExceptionTest.phpindex 369954075..efad3c823 100644--- a/tests/Unit/Exceptions/Social/ThreadsPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/ThreadsPublishExceptionTest.php@@ -136,3 +136,15 @@ test('platform returns threads', function () {expect($exception->platform())->toBe('threads');});++test('only an account rate limit from Threads is marked as a network rejection', function (int $status, ?int $code, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'error' => array_filter(['code' => $code, 'message' => 'Rejected']),+ ], $status)])->post(config('trypost.platforms.threads.graph_api').'/me/threads');++ expect(ThreadsPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'user request limit' => [400, 17, true],+ 'app request limit' => [400, 4, false],+ 'bare 429' => [429, null, false],+]);diff --git a/tests/Unit/Exceptions/Social/TikTokPublishExceptionTest.php b/tests/Unit/Exceptions/Social/TikTokPublishExceptionTest.phpindex b0b3d52f1..f5f257ce8 100644--- a/tests/Unit/Exceptions/Social/TikTokPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/TikTokPublishExceptionTest.php@@ -157,3 +157,37 @@ test('documented init refusals map to their category', function (string $code, i'unknown publish id' => ['invalid_publish_id', 400, ErrorCategory::Unknown],'publish id of another token' => ['token_not_authorized_for_specified_publish_id', 400, ErrorCategory::Unknown],]);++test('only an error code TikTok documents as caused by the creator is marked as a network rejection', function (string $code, int $status, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'error' => ['code' => $code, 'message' => 'Rejected'],+ ], $status)])->post(config('trypost.platforms.tiktok.api').'/post/publish/video/init/');++ expect(TikTokPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'missing video.publish grant' => ['scope_not_authorized', 401, true],+ 'grant revoked by the creator' => ['scope_permission_missed', 401, true],+ 'per user token rate limit' => ['rate_limit_exceeded', 429, true],+ 'file outside the specs' => ['invalid_file_upload', 400, true],+ 'creator daily post cap' => ['spam_risk_too_many_posts', 403, true],+ 'creator banned' => ['spam_risk_user_banned_from_posting', 403, true],+ 'our domain not verified' => ['url_ownership_unverified', 403, false],+ 'our app not audited' => ['unaudited_client_can_only_post_to_private_accounts', 403, false],+ 'our invalid params' => ['invalid_param', 400, false],+ 'MEDIA_UPLOAD app version, a mode we never send' => ['app_version_check_failed', 400, false],+ 'our client active user cap' => ['reached_active_user_cap', 403, false],+ 'privacy options we must honor' => ['privacy_level_option_mismatch', 403, false],+]);++test('only a fail reason caused by the creator is marked as a network rejection', function (string $failReason, bool $marked) {+ expect(TikTokPublishException::fromFailReason($failReason)->isNetworkRejection())->toBe($marked);+})->with([+ 'unsupported media format' => ['file_format_check_failed', true],+ 'video duration outside the limits' => ['duration_check_failed', true],+ 'unsupported frame rate' => ['frame_rate_check_failed', true],+ 'picture size outside the limits' => ['picture_size_check_failed', true],+ 'spammy description' => ['spam_risk_text', true],+ 'access removed by the creator' => ['auth_removed', true],+ 'a developer cancel' => ['publish_cancelled', false],+ 'a request flagged without a cause' => ['spam_risk', false],+]);diff --git a/tests/Unit/Exceptions/Social/XPublishExceptionTest.php b/tests/Unit/Exceptions/Social/XPublishExceptionTest.phpindex 42fcf5ba4..0eef021af 100644--- a/tests/Unit/Exceptions/Social/XPublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/XPublishExceptionTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\SocialAccount\Platform;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\XPublishException;use App\Exceptions\TokenExpiredException;@@ -89,7 +90,7 @@ test('HTTP 413 with empty body maps to MediaFormat category', function () {->and($exception->platformErrorCode)->toBe('413');});-test('unknown type maps to Unknown category with detail as message', function () {+test('an unmapped type shows the detail X sent', function () {$response = Http::response(['type' => 'https://api.x.com/2/problems/some-unknown-problem','title' => 'Some Unknown Problem',@@ -104,67 +105,39 @@ test('unknown type maps to Unknown category with detail as message', function ()->and($exception->userMessage)->toBe('An unknown issue occurred.');});-test('body containing "invalid URL" maps to ContentPolicy category', function () {+test('a duplicate post has no documented code and stays unclassified', function () {$response = Http::response([- 'type' => 'https://api.x.com/2/problems/invalid-request',- 'title' => 'Invalid Request',- 'detail' => 'The post contains an invalid URL in the content.',- ], 400);-- $fakeResponse = Http::fake(['*' => $response])->post('https://api.x.com/test');-- $exception = XPublishException::fromApiResponse($fakeResponse);-- expect($exception->category)->toBe(ErrorCategory::ContentPolicy)- ->and($exception->userMessage)->toBe('Post contains an invalid URL.');-});--test('body containing "video longer than 2 minutes" maps to MediaFormat category', function () {- $response = Http::response([- 'type' => 'https://api.x.com/2/problems/invalid-request',- 'title' => 'Invalid Request',- 'detail' => 'The video longer than 2 minutes cannot be uploaded.',- ], 400);-- $fakeResponse = Http::fake(['*' => $response])->post('https://api.x.com/test');-- $exception = XPublishException::fromApiResponse($fakeResponse);-- expect($exception->category)->toBe(ErrorCategory::MediaFormat)- ->and($exception->userMessage)->toBe('Video exceeds the 2-minute limit.');-});--test('invalid media IDs maps to MediaFormat category', function () {- $response = Http::response([- 'type' => 'https://api.x.com/2/problems/invalid-request',- 'title' => 'Invalid Request',- 'detail' => 'One or more parameters to your request was invalid.',- 'errors' => [['message' => 'Your media IDs are invalid.']],- ], 400);+ 'detail' => 'You are not allowed to create a Tweet with duplicate content.',+ 'type' => 'about:blank',+ 'title' => 'Forbidden',+ 'status' => 403,+ ], 403);- $fakeResponse = Http::fake(['*' => $response])->post('https://api.x.com/test');+ $fakeResponse = Http::fake(['*' => $response])->post(config('trypost.platforms.x.api').'/tweets');$exception = XPublishException::fromApiResponse($fakeResponse);- expect($exception->category)->toBe(ErrorCategory::MediaFormat)- ->and($exception->userMessage)->toBe('X rejected the attached media. Please re-upload and try again.');+ expect($exception->category)->toBe(ErrorCategory::Unknown);});-test('JSON object body requirement maps to ServerError category', function () {- $response = Http::response([+test('the free-text detail never changes how an invalid-request is classified', function (array $body) {+ $fakeResponse = Http::fake(['*' => Http::response(['type' => 'https://api.x.com/2/problems/invalid-request','title' => 'Invalid Request',- 'detail' => 'One or more parameters to your request was invalid.',- 'errors' => [['message' => 'Request body must be a JSON object.']],- ], 400);-- $fakeResponse = Http::fake(['*' => $response])->post('https://api.x.com/test');+ ...$body,+ ], 400)])->post(config('trypost.platforms.x.api').'/tweets');$exception = XPublishException::fromApiResponse($fakeResponse);- expect($exception->category)->toBe(ErrorCategory::ServerError)- ->and($exception->userMessage)->toBe('X rejected the media upload request. Please try again.');-});+ expect($exception->category)->toBe(ErrorCategory::ContentPolicy)+ ->and($exception->userMessage)->toBe('Invalid request. Check your post content.')+ ->and($exception->platformErrorCode)->toBe('invalid-request');+})->with([+ 'invalid URL' => [['detail' => 'The post contains an invalid URL in the content.']],+ 'video longer than 2 minutes' => [['detail' => 'The video longer than 2 minutes cannot be uploaded.']],+ 'invalid media IDs' => [['detail' => 'One or more parameters to your request was invalid.', 'errors' => [['message' => 'Your media IDs are invalid.']]]],+ 'JSON body requirement' => [['detail' => 'One or more parameters to your request was invalid.', 'errors' => [['message' => 'Request body must be a JSON object.']]]],+]);test('platform returns x', function () {$response = Http::response([@@ -179,3 +152,57 @@ test('platform returns x', function () {expect($exception->platform())->toBe('x');});++test('only a problem type X documents as caused by the account is marked as a network rejection', function (int $status, string $type, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'type' => "https://api.twitter.com/2/problems/{$type}",+ 'title' => 'Rejected',+ ], $status)])->post(config('trypost.platforms.x.api').'/tweets');++ expect(XPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'no access to protected content' => [403, 'not-authorized-for-resource', true],+ 'our app is not enrolled' => [403, 'client-forbidden', false],+ 'our malformed request' => [400, 'invalid-request', false],+ 'an id we sent that does not exist' => [404, 'resource-not-found', false],+ 'our app usage cap' => [429, 'usage-capped', false],+ 'a user or app rate limit' => [429, 'rate-limit-exceeded', false],+]);++test('a payload too large and a bare 429 from X are not network rejections', function (int $status) {+ $fakeResponse = Http::fake(['*' => Http::response([], $status)])+ ->post(config('trypost.platforms.x.api').'/media/upload');++ expect(XPublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBeFalse();+})->with([413, 429]);++test('an unmapped type without a valid detail shows the title X sent', function (mixed $detail) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'type' => 'about:blank',+ 'title' => 'Forbidden',+ 'detail' => $detail,+ ], 403)])->post(config('trypost.platforms.x.api').'/tweets');++ expect(XPublishException::fromApiResponse($fakeResponse)->userMessage)->toBe('Forbidden');+})->with([+ 'empty string' => [''],+ 'whitespace' => [" \t\n"],+ 'null' => [null],+ 'number' => [42],+ 'zero' => [0],+ 'boolean' => [false],+ 'array' => [['message' => 'Invalid shape']],+]);++test('an unmapped error shows the generic message when X sent no explanation', function (int $status, array $body) {+ $fakeResponse = Http::fake(['*' => Http::response($body, $status)])+ ->post(config('trypost.platforms.x.api').'/tweets');++ $exception = XPublishException::fromApiResponse($fakeResponse);++ expect($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->userMessage)->toBe(__('posts.errors.unrecognized_error', ['platform' => Platform::X->label()]));+})->with([+ 'no message' => [400, ['type' => 'about:blank']],+ 'an unlisted 5xx' => [501, ['type' => 'about:blank', 'title' => 'Not Implemented', 'detail' => 'Upstream failed.']],+]);diff --git a/tests/Unit/Exceptions/Social/YouTubePublishExceptionTest.php b/tests/Unit/Exceptions/Social/YouTubePublishExceptionTest.phpindex da75f648b..13d2c3614 100644--- a/tests/Unit/Exceptions/Social/YouTubePublishExceptionTest.php+++ b/tests/Unit/Exceptions/Social/YouTubePublishExceptionTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\SocialAccount\Platform;use App\Exceptions\Social\ErrorCategory;use App\Exceptions\Social\YouTubePublishException;use App\Exceptions\TokenExpiredException;@@ -58,13 +59,48 @@ test('unauthorized reason throws TokenExpiredException', function () {YouTubePublishException::fromGoogleException($e);})->throws(TokenExpiredException::class);-test('unknown reason falls through to Unknown category with original message', function () {+test('an unknown reason shows the message Google sent', function () {$e = new Exception('original error message', 400, null, [['reason' => 'someUnknownReason', 'message' => 'original error message']]);$exception = YouTubePublishException::fromGoogleException($e);expect($exception->category)->toBe(ErrorCategory::Unknown)- ->and($exception->userMessage)->toBe('original error message');+ ->and($exception->userMessage)->toBe('original error message')+ ->and($exception->rawResponse)->toBe('original error message');+});++test('a Google 5xx that reaches the mapper fails as an unconfirmed upload', function (int $status, array $errors) {+ $e = new Exception('<!DOCTYPE html><html lang=en><title>Error 502 (Server Error)!!1</title></html>', $status, null, $errors);++ $exception = YouTubePublishException::fromGoogleException($e);++ expect(YouTubePublishException::isServerError($e))->toBeTrue()+ ->and($exception->category)->toBe(ErrorCategory::ServerError)+ ->and($exception->userMessage)->toBe(__('posts.errors.youtube.upload_unconfirmed'));+})->with([+ '502 html page' => [502, []],+ '503 backendError' => [503, [['reason' => 'backendError', 'message' => 'Backend Error']]],+ '500 internalError' => [500, [['reason' => 'internalError', 'message' => 'Internal error']]],+ '400 backendError' => [400, [['reason' => 'backendError', 'message' => 'Backend Error']]],+ 'internalError without a status' => [0, [['reason' => 'internalError', 'message' => 'Internal error']]],+ '504 gateway timeout' => [504, []],+]);++test('a 5xx the resumable upload guide does not list as retryable is not a server error', function () {+ $e = new Exception('Not implemented', 501, null, [['reason' => 'notImplemented', 'message' => 'Not implemented']]);++ expect(YouTubePublishException::isServerError($e))->toBeFalse();+});++test('a failure without a documented reason never reaches the user message', function () {+ $e = new Exception('<!DOCTYPE html><html lang=en><p><b>400.</b> That’s an error.</html>', 400);++ $exception = YouTubePublishException::fromGoogleException($e);++ expect($exception->category)->toBe(ErrorCategory::Unknown)+ ->and($exception->userMessage)->toBe(__('posts.errors.unrecognized_error', ['platform' => Platform::YouTube->label()]))+ ->and($exception->userMessage)->not->toContain('<')+ ->and($exception->rawResponse)->toContain('<!DOCTYPE html>');});test('platform returns youtube', function () {@@ -99,7 +135,7 @@ test('fromApiResponse with invalidTitle reason maps to ContentPolicy', function->and($exception->platformErrorCode)->toBe('invalidTitle');});-test('fromApiResponse with unknown reason uses fallback message and Unknown category', function () {+test('fromApiResponse with an unknown reason shows the message Google sent', function () {$response = Http::response(['error' => ['code' => 400,@@ -117,3 +153,48 @@ test('fromApiResponse with unknown reason uses fallback message and Unknown cateexpect($exception->category)->toBe(ErrorCategory::Unknown)->and($exception->userMessage)->toBe('Something went wrong on YouTube.');});++test('only a reason YouTube documents as caused by the user is marked as a network rejection', function (string $reason, int $status, bool $marked) {+ $fakeResponse = Http::fake(['*' => Http::response([+ 'error' => ['code' => $status, 'message' => 'Rejected', 'errors' => [['reason' => $reason, 'message' => 'Rejected']]],+ ], $status)])->post(config('trypost.platforms.youtube.data_api').'/videos');++ expect(YouTubePublishException::fromApiResponse($fakeResponse)->isNetworkRejection())->toBe($marked);+})->with([+ 'invalid title' => ['invalidTitle', 400, true],+ 'channel upload limit' => ['uploadLimitExceeded', 400, true],+ 'invalid description' => ['invalidDescription', 400, true],+ 'channel upload rate limit' => ['uploadRateLimitExceeded', 403, true],+ 'our project quota' => ['quotaExceeded', 403, false],+ 'category we send' => ['invalidCategoryId', 400, false],+ 'privacy value we send' => ['forbiddenPrivacySetting', 403, false],+ 'undescribed forbidden' => ['forbidden', 403, false],+ 'video body missing from our request' => ['mediaBodyRequired', 400, false],+]);++test('a Google exception is marked only for a reason caused by the user', function (string $reason, bool $marked) {+ $exception = new Exception('Rejected', 400, null, [['reason' => $reason, 'message' => 'Rejected']]);++ expect(YouTubePublishException::fromGoogleException($exception)->isNetworkRejection())->toBe($marked);+})->with([+ 'invalid title' => ['invalidTitle', true],+ 'our project quota' => ['quotaExceeded', false],+]);++test('an unknown reason without a Google message shows the generic message', function () {+ $e = new Exception('{"error":{}}', 400, null, [['reason' => 'someUnknownReason']]);++ expect(YouTubePublishException::fromGoogleException($e)->userMessage)+ ->toBe(__('posts.errors.unrecognized_error', ['platform' => Platform::YouTube->label()]));+});++test('fromApiResponse shows the generic message without a Google message or on a 5xx', function (int $status, array $body) {+ $fakeResponse = Http::fake(['*' => Http::response($body, $status)])+ ->post(config('trypost.platforms.youtube.data_api').'/videos');++ expect(YouTubePublishException::fromApiResponse($fakeResponse)->userMessage)+ ->toBe(__('posts.errors.unrecognized_error', ['platform' => Platform::YouTube->label()]));+})->with([+ 'no message' => [400, ['error' => ['code' => 400, 'errors' => [['reason' => 'weirdUnknownReason']]]]],+ 'a 5xx' => [503, ['error' => ['code' => 503, 'message' => 'Backend unavailable', 'errors' => [['reason' => 'weirdUnknownReason']]]]],+]);diff --git a/tests/Unit/Support/Social/PublishCheckpointTest.php b/tests/Unit/Support/Social/PublishCheckpointTest.phpindex b650ffd4c..cd2d6f63e 100644--- a/tests/Unit/Support/Social/PublishCheckpointTest.php+++ b/tests/Unit/Support/Social/PublishCheckpointTest.php@@ -45,3 +45,23 @@ test('instagramStatus reads a non-empty status', function () {->and(PublishCheckpoint::instagramStatus(['instagram_status' => '']))->toBeNull()->and(PublishCheckpoint::instagramStatus(null))->toBeNull();});++test('xMedia keeps only non-empty scalar ids as strings', function () {+ expect(PublishCheckpoint::xMedia([+ PublishCheckpoint::X_MEDIA => [+ 'image' => 'media_1',+ 'video' => 1234567890,+ 'empty' => '',+ 'missing' => null,+ 'nested' => ['id' => 'media_2'],+ ],+ ]))->toBe(['image' => 'media_1', 'video' => '1234567890']);+});++test('xMedia returns an empty list when the checkpoint is not an array', function (?array $context) {+ expect(PublishCheckpoint::xMedia($context))->toBe([]);+})->with([+ 'no context' => [null],+ 'no checkpoint' => [[]],+ 'scalar checkpoint' => [[PublishCheckpoint::X_MEDIA => 'media_1']],+]);