Skip to content

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

14.7 KB
Raw Blame
<?php

declare(strict_types=1);

use Amp\DeferredFuture;
use Amp\TimeoutCancellation;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Media;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Pest\Browser\Execution;

beforeEach(function () {
    Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
});

/**
 * @param  array<int, array<string, mixed>>  $media
 * @return array{0: Post, 1: SocialAccount}
 */
function seedLinkCardPreviewPost(
    Platform $platform,
    string $content = 'Draft without a link',
    array $media = [],
): array {
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create([
        'user_id' => $user->id,
        'account_id' => $user->account_id,
    ]);
    $workspace->members()->attach($user->id, membershipPivot('member'));
    $user->update(['current_workspace_id' => $workspace->id]);
    subscribeAccount($user->account);

    $account = SocialAccount::factory()->create([
        'workspace_id' => $workspace->id,
        'platform' => $platform,
        'scopes' => $platform->requiredPublishScopes(),
    ]);

    $post = Post::factory()->forAccount($account, match ($platform) {
        Platform::Facebook => ContentType::FacebookPost,
        Platform::LinkedIn => ContentType::LinkedInPost,
        Platform::Mastodon => ContentType::MastodonPost,
        Platform::Bluesky => ContentType::BlueskyPost,
        Platform::Threads => ContentType::ThreadsPost,
        default => throw new LogicException('Unsupported link-card browser test platform.'),
    })->create([
        'user_id' => $user->id,
        'content' => $content,
        'media' => $media,
    ]);

    test()->actingAs($user);

    return [$post, $account];
}

test('facebook linkedin and mastodon previews render fetched link cards', function (Platform $platform) {
    $url = "https://93.184.216.34/{$platform->value}";
    Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);

    [$post] = seedLinkCardPreviewPost($platform, "Read {$url}");
    $previewRequests = 0;
    Event::listen(RequestHandled::class, function (RequestHandled $event) use (&$previewRequests): void {
        if ($event->request->routeIs('app.posts.link-preview')) {
            $previewRequests++;
        }
    });

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, '@composer-preview-frame');
    waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");

    $page->assertSeeIn('@link-card-title', 'Article card')
        ->assertPresent('@link-card')
        ->assertNoJavaScriptErrors();

    expect($previewRequests)->toBe(1);
    Http::assertSentCount(1);
})->with([
    'Facebook' => Platform::Facebook,
]);

test('removing a url removes its visible card', function () {
    Http::fake(['https://93.184.216.34/*' => Http::response('<meta property="og:title" content="Article card">')]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article');

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@composer-caption-{$account->id}");
    waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");

    $page->assertSeeIn('@link-card-title', 'Article card')
        ->clear("@composer-caption-{$account->id}");
    waitForGone($page, '@link-card');

    $page->assertMissing('@link-card')
        ->assertNoJavaScriptErrors();
});

test('a failed fetch clears the previous card and a later url can recover', function () {
    Http::fake([
        'https://93.184.216.34/article' => Http::response('<meta property="og:title" content="Article card">'),
        'https://93.184.216.34/broken' => Http::response('', 500),
        'https://93.184.216.34/recovered' => Http::response('<meta property="og:title" content="Recovered card">'),
    ]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article');

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@composer-caption-{$account->id}");
    waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");

    $page->assertSeeIn('@link-card-title', 'Article card')
        ->fill("@composer-caption-{$account->id}", 'https://93.184.216.34/broken');

    Execution::instance()->waitForExpectation(fn () => Http::assertSentCount(2));
    waitForGone($page, '@link-card');

    $page->assertMissing('@link-card')
        ->fill("@composer-caption-{$account->id}", 'https://93.184.216.34/recovered');
    waitForState($page, '@link-card-title', "element.textContent.includes('Recovered card')");

    $page->assertSeeIn('@link-card-title', 'Recovered card')
        ->assertNoJavaScriptErrors();
});

test('a pending response cannot overwrite a newer card or revive a removed url', function (bool $removeUrl) {
    $release = new DeferredFuture;
    $started = false;
    Http::fake(function ($request) use ($release, &$started) {
        if ($request->url() === 'https://93.184.216.34/slow') {
            $started = true;
            $release->getFuture()->await(new TimeoutCancellation(20));

            return Http::response('<meta property="og:title" content="Stale card">');
        }

        return Http::response('<meta property="og:title" content="Current card">');
    });

    try {
        [$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/slow');
        $page = visit(route('app.posts.edit', $post));
        waitForOpen($page, '@post-composer-dialog');
        waitFor($page, "@composer-caption-{$account->id}");

        Execution::instance()->waitForExpectation(function () use (&$started) {
            expect($started)->toBeTrue();
        });

        $page->fill("@composer-caption-{$account->id}", $removeUrl ? '' : 'https://93.184.216.34/current');

        if (! $removeUrl) {
            waitForState($page, '@link-card-title', "element.textContent.includes('Current card')");
            $page->assertSeeIn('@link-card-title', 'Current card');
        }
    } finally {
        if (! $release->isComplete()) {
            $release->complete();
        }
    }

    $page->page()->waitForLoadState('networkidle');
    $page->assertDontSee('Stale card');

    if ($removeUrl) {
        $page->assertMissing('@link-card');
    } else {
        $page->assertSeeIn('@link-card-title', 'Current card');
    }

    $page->assertNoJavaScriptErrors();
})->with(['newer url' => false, 'removed url' => true]);

test('attached media suppresses fetching until it is removed', function () {
    Http::fake(['https://93.184.216.34/*' => Http::response('<meta property="og:title" content="Article card">')]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::LinkedIn, 'https://93.184.216.34/article', [[
        'id' => 'image-1',
        'type' => 'image',
        'mime_type' => 'image/png',
        'path' => 'uploads/image.png',
        'url' => 'data:image/png;base64,'.base64_encode(file_get_contents(__DIR__.'/../fixtures/1x1.png')),
        'size' => 68,
    ]]);

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@composer-{$account->id}-media-item");

    $page->assertPresent("@composer-{$account->id}-media-item")
        ->assertMissing('@link-card');

    Http::assertNothingSent();

    $page->click("@composer-{$account->id}-remove-0");
    waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");

    $page->assertSeeIn('@link-card-title', 'Article card')
        ->assertNoJavaScriptErrors();

    Http::assertSentCount(1);
});

test('the editor link card can be dropped and the post saves without it', function (Platform $platform) {
    $url = 'https://93.184.216.34/article';
    Http::fake([$url => Http::response('<meta property="og:title" content="Article card"><meta property="og:description" content="A great read">')]);
    [$post, $account] = seedLinkCardPreviewPost($platform, "Read {$url}");
    $card = "composer-link-card-{$account->id}";

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@{$card}");

    $page->assertSeeIn("@{$card}-title", 'Article card')
        ->assertPresent("@{$card}-replace")
        ->click("@{$card}-remove");
    waitForGone($page, "@{$card}");

    $page->assertMissing("@{$card}")
        ->assertMissing('@link-card')
        ->assertNoJavaScriptErrors()
        ->click('@composer-save-draft')
        ->assertMissing('@post-composer-dialog');

    expect($post->fresh()->meta)->toEqual(['link_preview' => false]);
})->with([
    'Facebook' => Platform::Facebook,
]);

test('the threads link card cannot be dropped because threads always shows it', function () {
    $url = 'https://93.184.216.34/article';
    Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::Threads, "Read {$url}");
    $card = "composer-link-card-{$account->id}";

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@{$card}");

    $page->assertPresent("@{$card}-replace")
        ->assertMissing("@{$card}-remove")
        ->assertNoJavaScriptErrors();
});

test('a threads poll fetches no link card for a link in its question', function () {
    $url = 'https://93.184.216.34/article';
    Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::Threads, "Best tool? {$url}");
    $post->forceFill(['content_type' => ContentType::ThreadsPoll, 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces']]]])->save();
    $previewRequests = 0;
    Event::listen(RequestHandled::class, function (RequestHandled $event) use (&$previewRequests): void {
        if ($event->request->routeIs('app.posts.link-preview')) {
            $previewRequests++;
        }
    });

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, '@threads-poll-choice-0');
    letPageRun($page, 1500);

    $page->assertMissing("@composer-link-card-{$account->id}")
        ->assertNoJavaScriptErrors();

    expect($previewRequests)->toBe(0);
    Http::assertNothingSent();
});

test('replacing the link card with media attaches the card image once, however fast it is clicked', function () {
    $url = 'https://93.184.216.34/article';
    $fake = UploadedFile::fake()->image('card.jpg', 1200, 630);
    $image = file_get_contents($fake->getPathname());
    Http::fake([
        $url => Http::response('<meta property="og:title" content="Article card"><meta property="og:image" content="https://93.184.216.34/card.jpg">'),
        'https://93.184.216.34/card.jpg' => Http::response($image, 200, ['Content-Type' => 'image/jpeg']),
    ]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::Facebook, "Read {$url}");
    $card = "composer-link-card-{$account->id}";

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@{$card}");

    $replace = jsSelector("@{$card}-replace");
    $page->script("const button = document.querySelector({$replace}); button.click(); button.click();");
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@composer-{$account->id}-media-item-0");

    $page->assertMissing("@{$card}")
        ->assertNoJavaScriptErrors()
        ->click('@composer-save-draft')
        ->assertMissing('@post-composer-dialog');

    $media = Media::query()->sole();

    expect($media->post_id)->toBe($post->id)
        ->and($post->fresh()->media)->toHaveCount(1)
        ->and(data_get($post->fresh()->media, '0.id'))->toBe($media->id);
});

test('the shared step editor shows no link card and the network card does', function () {
    $url = 'https://93.184.216.34/article';
    Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);
    [, $facebook] = seedLinkCardPreviewPost(Platform::Facebook);
    $linkedin = SocialAccount::factory()->create([
        'workspace_id' => $facebook->workspace_id,
        'platform' => Platform::LinkedIn,
        'scopes' => Platform::LinkedIn->requiredPublishScopes(),
    ]);

    $page = visit(route('app.posts.create'));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, '@composer-add-account');

    $page->fill('@composer-base-content', "Read {$url}")
        ->click('@composer-add-account')
        ->click("@composer-account-option-{$facebook->id}")
        ->click("@composer-account-option-{$linkedin->id}")
        ->click("@composer-account-{$facebook->id}");
    waitForState($page, '@link-card-title', "element.textContent.includes('Article card')");

    $page->assertPresent('@composer-next')
        ->assertPresent('@link-card')
        ->assertMissing("@composer-link-card-{$facebook->id}")
        ->assertMissing("@composer-link-card-{$linkedin->id}")
        ->click('@composer-next');
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@composer-link-card-{$facebook->id}");

    $page->assertSeeIn("@composer-link-card-{$facebook->id}-title", 'Article card')
        ->assertNoJavaScriptErrors();
});

test('a dropped link card comes back when the link changes', function () {
    $url = 'https://93.184.216.34/article';
    $other = 'https://93.184.216.34/other';
    Http::fake([
        $url => Http::response('<meta property="og:title" content="Article card">'),
        $other => Http::response('<meta property="og:title" content="Other card">'),
    ]);
    [$post, $account] = seedLinkCardPreviewPost(Platform::Facebook, "Read {$url}");
    $card = "composer-link-card-{$account->id}";

    $page = visit(route('app.posts.edit', $post));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@{$card}");

    $page->click("@{$card}-remove");
    waitForGone($page, "@{$card}");

    $page->fill("@composer-caption-{$account->id}", "Read {$other}");
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, "@{$card}");

    $page->assertSeeIn("@{$card}-title", 'Other card')
        ->assertNoJavaScriptErrors()
        ->click('@composer-save-draft')
        ->assertMissing('@post-composer-dialog');

    expect(data_get($post->fresh()->meta, 'link_preview'))->toBeNull();
});