From 74ed3949952cba5c4ea7ceab5ffcf7a9d0511cba Mon Sep 17 00:00:00 2001 From: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:08:51 +0530 Subject: [PATCH 1/2] feat: render commit links as quote cards --- KNOWLEDGE_BASE.md | 3 + .../Controllers/CommitPreviewController.php | 13 ++ .../Requests/ShowCommitPreviewRequest.php | 28 ++++ app/Jobs/UnfurlLink.php | 9 +- app/Models/LinkPreview.php | 7 +- app/Queries/CommitPreviewQuery.php | 21 +++ app/Services/CommitLinks.php | 45 +++++++ .../js/components/commit-link-preview.tsx | 67 ++++++++++ resources/js/components/link-preview.tsx | 45 +++++-- resources/js/components/quoted-commit.tsx | 3 + resources/js/types/commit.ts | 1 + routes/web.php | 5 + .../CommitPreviewControllerTest.php | 86 ++++++++++++ tests/Unit/CommitLinkPreview.test.tsx | 126 ++++++++++++++++++ tests/Unit/Jobs/UnfurlLinkTest.php | 13 ++ tests/Unit/Models/LinkPreviewTest.php | 20 +++ tests/Unit/QuotedCommit.test.tsx | 51 ++++++- tests/Unit/Services/CommitLinksTest.php | 28 ++++ 18 files changed, 560 insertions(+), 11 deletions(-) create mode 100644 app/Http/Requests/ShowCommitPreviewRequest.php create mode 100644 app/Queries/CommitPreviewQuery.php create mode 100644 app/Services/CommitLinks.php create mode 100644 resources/js/components/commit-link-preview.tsx create mode 100644 tests/Unit/CommitLinkPreview.test.tsx create mode 100644 tests/Unit/Services/CommitLinksTest.php diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 888e7ce8f0..886f6425d5 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -297,6 +297,9 @@ Sources: [image picker](resources/js/components/commit-image-picker.tsx), [image ### Links, link cards, and embedded players +Links to commits on this site show the linked commit in a card with its author, text, images, and poll. The card only shows content the viewer may see; unavailable commits show an unavailable placeholder. This is a link preview and does not create a quote or notify the linked author. Linked cards do not expand into further linked cards. + + Each link in a commit or reply counts as at most **23 characters** toward the 4,000-character allowance; shorter links count at their actual length. This also applies to quotes, scheduled commits, previews, and terminal and app submissions. The full URL is stored and followed directly, not through a redirect service. Prose URLs longer than **2,048 characters** are rejected, including the inferred `https://` scheme for bare domains. Code still counts literally toward the 4,000-character allowance. Bodies are additionally capped at 40,000 raw characters to bound storage and processing. Private messages and issue drafts keep their existing literal character limits. URLs and bare domains in commits and replies become clickable links. Long URLs are shortened visually; hover reveals the full destination. GitHub repository links show as `owner/repo`, and issue or pull request links as `owner/repo#123`, with the GitHub mark. Links to /dev/null commits show as the author's username and a short hash. Code keeps its literal text. The first link normally gets a preview card with available title, description, and image. In the commit, reply, and quote composers, choose another link from the body or choose no card; terminal commits and app commits always use the first link. Missing site metadata may leave a link without a rich preview. Different ways of writing the same link share one card: the host's case, a default port, a lone trailing `/`, the highlight a browser adds to a link (`#:~:text=`), and tracking parameters such as `utm_*`, `fbclid` or YouTube's `si` don't make a new one, and a few sites share one card across their addresses, so `youtube.com/watch?v=…` and `youtu.be/…` show the same card, as do `twitter.com` and `x.com`. Any other `#fragment` stays part of the link, so a link to a news entry, a line of code or a comment keeps a card of its own. The card links to that shared address, while the commit keeps the link exactly as written. diff --git a/app/Http/Controllers/CommitPreviewController.php b/app/Http/Controllers/CommitPreviewController.php index b1e2d3ea70..2a094e3643 100644 --- a/app/Http/Controllers/CommitPreviewController.php +++ b/app/Http/Controllers/CommitPreviewController.php @@ -5,15 +5,28 @@ namespace App\Http\Controllers; use App\Http\Requests\CreateCommitPreviewRequest; +use App\Http\Requests\ShowCommitPreviewRequest; +use App\Models\Commit; +use App\Models\Profile; +use App\Models\User; +use App\Queries\CommitPreviewQuery; use App\Http\Resources\ShownGuildMentions; use App\Queries\MentionedOrganizationsQuery; use App\Queries\MentionedUsersQuery; use App\Services\CodeSpans; use App\Services\EmojiShortcodes; +use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\JsonResponse; final readonly class CommitPreviewController { + public function show(ShowCommitPreviewRequest $request, #[CurrentUser] ?User $currentUser, Profile $profile, Commit $commit, CommitPreviewQuery $preview): JsonResponse + { + return response()->json([ + 'commit' => $preview->get($commit, $profile, $currentUser), + ])->header('Cache-Control', 'private, no-store'); + } + /** * Highlighting and finding who a mention points to run on the server only, so the composer asks here to preview a * draft with code blocks or mentions. diff --git a/app/Http/Requests/ShowCommitPreviewRequest.php b/app/Http/Requests/ShowCommitPreviewRequest.php new file mode 100644 index 0000000000..4a8428e96b --- /dev/null +++ b/app/Http/Requests/ShowCommitPreviewRequest.php @@ -0,0 +1,28 @@ +route('commit'); + assert($commit instanceof Commit); + + return $commit->isVisibleTo($this->user()) ? Response::allow() : Response::denyAsNotFound(); + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Jobs/UnfurlLink.php b/app/Jobs/UnfurlLink.php index 5ef508274b..26182a6051 100644 --- a/app/Jobs/UnfurlLink.php +++ b/app/Jobs/UnfurlLink.php @@ -6,6 +6,7 @@ use App\Actions\UpdateLinkPreview; use App\Models\LinkPreview; +use App\Services\CommitLinks; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Queue\Attributes\Backoff; @@ -27,12 +28,18 @@ public function __construct(public readonly LinkPreview $linkPreview) /** * Commits that share a link may each queue this job before the first one runs, so only the first one fetches. */ - public function handle(UpdateLinkPreview $action): void + public function handle(UpdateLinkPreview $action, CommitLinks $commitLinks): void { if ($this->linkPreview->fetched_at !== null) { return; } + if ($commitLinks->previewUrl($this->linkPreview->url) !== null) { + $this->linkPreview->update(['fetched_at' => now()]); + + return; + } + $action->handle($this->linkPreview); } diff --git a/app/Models/LinkPreview.php b/app/Models/LinkPreview.php index c01fc48404..549667eb5c 100644 --- a/app/Models/LinkPreview.php +++ b/app/Models/LinkPreview.php @@ -4,6 +4,7 @@ namespace App\Models; +use App\Services\CommitLinks; use App\Services\Embeds; use Carbon\CarbonInterface; use Database\Factories\LinkPreviewFactory; @@ -73,6 +74,10 @@ public function commits(): HasMany */ public function toArray(): array { - return [...parent::toArray(), 'is_pending' => $this->fetched_at === null, 'embed' => resolve(Embeds::class)->for($this->url)?->toArray()]; + $commitPreviewUrl = resolve(CommitLinks::class)->previewUrl($this->url); + + return $commitPreviewUrl === null + ? [...parent::toArray(), 'is_pending' => $this->fetched_at === null, 'embed' => resolve(Embeds::class)->for($this->url)?->toArray()] + : ['url' => $this->url, 'title' => null, 'description' => null, 'image_url' => null, 'site_name' => null, 'is_pending' => false, 'embed' => null, 'commit_preview_url' => $commitPreviewUrl]; } } diff --git a/app/Queries/CommitPreviewQuery.php b/app/Queries/CommitPreviewQuery.php new file mode 100644 index 0000000000..eec0b1b42c --- /dev/null +++ b/app/Queries/CommitPreviewQuery.php @@ -0,0 +1,21 @@ +with(['images', 'linkPreview']) + ->withPollFor($viewer) + ->findOrFail($commit->id) + ->setRelation('author', $author); + } +} diff --git a/app/Services/CommitLinks.php b/app/Services/CommitLinks.php new file mode 100644 index 0000000000..dff613d1ef --- /dev/null +++ b/app/Services/CommitLinks.php @@ -0,0 +1,45 @@ +string('app.url')); + assert($site instanceof Url); + + if (! $parsed instanceof Url + || ! in_array($parsed->getScheme(), ['http', 'https'], true) + || $parsed->getAsciiHost() !== $site->getAsciiHost() + || $parsed->getPort() !== $site->getPort()) { + return null; + } + + $route = $this->router->getRoutes()->getByName('commit.show'); + assert($route instanceof Route); + + if (preg_match($route->toSymfonyRoute()->compile()->getRegex(), mb_rtrim($parsed->getPath(), '/'), $matches) !== 1 + || ! Str::isUuid($matches['commit'])) { + return null; + } + + return route('commit-preview.show', ['profile' => $matches['profile'], 'commit' => $matches['commit']], absolute: false); + } +} diff --git a/resources/js/components/commit-link-preview.tsx b/resources/js/components/commit-link-preview.tsx new file mode 100644 index 0000000000..933039d896 --- /dev/null +++ b/resources/js/components/commit-link-preview.tsx @@ -0,0 +1,67 @@ +import { useEffect, useState } from 'react'; +import { QuotedCommit } from '@/components/quoted-commit'; +import { Skeleton } from '@/components/ui/skeleton'; +import type { QuotedCommit as QuotedCommitData } from '@/types'; + +export function CommitLinkPreview({ + url, + isStatic = false, +}: { + url: string; + isStatic?: boolean; +}) { + const [commit, setCommit] = useState(); + + useEffect(() => { + const controller = new AbortController(); + + void fetch(url, { + headers: { Accept: 'application/json' }, + cache: 'no-store', + signal: controller.signal, + }) + .then(async (response) => { + const data = response.ok + ? ((await response.json()) as { commit: QuotedCommitData }) + : null; + + if (!controller.signal.aborted) { + setCommit(data?.commit ?? null); + } + }) + .catch(() => { + if (!controller.signal.aborted) { + setCommit(null); + } + }); + + return () => controller.abort(); + }, [url]); + + if (commit === undefined) { + return ( +
+
+ + +
+ + +
+ ); + } + + return ( + + ); +} diff --git a/resources/js/components/link-preview.tsx b/resources/js/components/link-preview.tsx index 4fb6c827e7..7f3fee0b3d 100644 --- a/resources/js/components/link-preview.tsx +++ b/resources/js/components/link-preview.tsx @@ -1,6 +1,7 @@ import { usePage } from '@inertiajs/react'; import type { ReactNode } from 'react'; import { useEffect, useState } from 'react'; +import { CommitLinkPreview } from '@/components/commit-link-preview'; import { LinkEmbed } from '@/components/link-embed'; import { Skeleton } from '@/components/ui/skeleton'; import type { RealtimeChannel } from '@/lib/realtime'; @@ -185,20 +186,48 @@ function LinkPreviewSkeleton() { ); } -export function LinkPreview({ - refreshUrl, - preview: initialPreview, - isStatic = false, - source, - footer, -}: { +type LinkPreviewProps = { refreshUrl: string; preview: LinkPreviewData; isStatic?: boolean; source?: LinkPreviewSource; /** Shown inside the card, under the page it links to. */ footer?: ReactNode; -}) { + suppressLinkedPreview?: boolean; +}; + +export function LinkPreview(props: LinkPreviewProps) { + const url = props.preview.commit_preview_url; + + if (url) { + if (props.suppressLinkedPreview) { + return null; + } + + const preview = ( + + ); + + return props.footer ? ( +
+ {preview} + {props.footer} +
+ ) : ( + preview + ); + } + + return ; +} + +function ExternalLinkPreview({ + refreshUrl, + preview: initialPreview, + isStatic = false, + source, + footer, +}: LinkPreviewProps) { const { preview, isWaiting } = useFetchedLinkPreview( refreshUrl, initialPreview, diff --git a/resources/js/components/quoted-commit.tsx b/resources/js/components/quoted-commit.tsx index 12de19f314..b3ffb98ff6 100644 --- a/resources/js/components/quoted-commit.tsx +++ b/resources/js/components/quoted-commit.tsx @@ -21,10 +21,12 @@ export function QuotedCommit({ commit, isPreview = false, label = 'Quoting', + suppressLinkedPreview = false, }: { commit: QuotedCommitData | DeletedCommit | null; isPreview?: boolean; label?: string; + suppressLinkedPreview?: boolean; }) { const now = useNow(); if (commit === null || isDeleted(commit)) { @@ -82,6 +84,7 @@ export function QuotedCommit({ refreshUrl={CommitLinkPreviewController.show.url(commit.id)} preview={commit.link_preview} isStatic + suppressLinkedPreview={suppressLinkedPreview} source={{ commitId: commit.id }} footer={ commit.link_topic && ( diff --git a/resources/js/types/commit.ts b/resources/js/types/commit.ts index 6caf8dc6aa..7b1709d7a8 100644 --- a/resources/js/types/commit.ts +++ b/resources/js/types/commit.ts @@ -16,6 +16,7 @@ export type Embed = { }; export type LinkPreview = { + commit_preview_url?: string | null; url: string; title: string | null; description: string | null; diff --git a/routes/web.php b/routes/web.php index e4b8c6961f..2b03bb4228 100644 --- a/routes/web.php +++ b/routes/web.php @@ -283,6 +283,11 @@ Route::get('@{profile:handle}/commits/{commit}', [CommitController::class, 'show']) ->scopeBindings() ->name('commit.show'); + Route::get('@{profile:handle}/commits/{commit}/preview', [CommitPreviewController::class, 'show']) + ->withoutMiddleware(RememberIntendedUrl::class) + ->scopeBindings() + ->whereUuid('commit') + ->name('commit-preview.show'); Route::get('@{profile:handle}/commits/{commit}/photos/{photo}', [CommitPhotoController::class, 'show']) ->scopeBindings() ->whereNumber('photo') diff --git a/tests/Feature/Controllers/CommitPreviewControllerTest.php b/tests/Feature/Controllers/CommitPreviewControllerTest.php index de549877fb..5c9a3a5684 100644 --- a/tests/Feature/Controllers/CommitPreviewControllerTest.php +++ b/tests/Feature/Controllers/CommitPreviewControllerTest.php @@ -2,8 +2,13 @@ declare(strict_types=1); +use App\Enums\CommitStatus; use App\Enums\Feature; use App\Models\Guild; +use App\Models\Commit; +use App\Models\CommitImage; +use App\Models\Poll; +use App\Models\PollVote; use App\Models\User; use App\Services\Features; @@ -17,6 +22,87 @@ ->assertJsonPath('guild_mentions.linux1️⃣.name', 'Linux'); }); +it('returns a visible commit with the content needed by its quote card', function (): void { + $commit = Commit::factory()->create(['body' => "Hello\n```php\nreturn true;\n```"]); + $image = CommitImage::factory()->for($commit)->create(); + + $this->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk() + ->assertHeader('Cache-Control', 'no-store, private') + ->assertJsonPath('commit.id', $commit->id) + ->assertJsonPath('commit.author.handle', $commit->author->handle) + ->assertJsonPath('commit.body', $commit->body) + ->assertJsonPath('commit.body_segments.1.type', 'block') + ->assertJsonPath('commit.images.0.id', $image->id) + ->assertJsonMissingPath('commit.embedding') + ->assertJsonMissingPath('commit.quoted_commit'); +}); + +it('does not replace the page a guest returns to after signing in', function (): void { + $commit = Commit::factory()->create(); + $intended = route('user.show', $commit->user); + + $this->withSession(['url.intended' => $intended]) + ->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk() + ->assertSessionHas('url.intended', $intended); +}); + +it('does not set a sign-in destination when a guest loads preview JSON', function (): void { + $commit = Commit::factory()->create(); + + $this->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk() + ->assertSessionMissing('url.intended'); +}); + +it('does not expose pending or rejected linked commits to other viewers', function (CommitStatus $status, bool $signedIn): void { + $commit = Commit::factory()->create(['status' => $status]); + + if ($signedIn) { + $this->actingAs(User::factory()->create()); + } + + $this->getJson(route('commit-preview.show', [$commit->author, $commit]))->assertNotFound(); +})->with([CommitStatus::Pending, CommitStatus::Rejected])->with([false, true]); + +it('lets the author preview their own unpublished commit', function (CommitStatus $status): void { + $commit = Commit::factory()->create(['status' => $status]); + + $this->actingAs($commit->user)->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk()->assertJsonPath('commit.id', $commit->id); +})->with([CommitStatus::Pending, CommitStatus::Rejected]); + +it('hides linked commits across a block in either direction', function (bool $viewerBlocks): void { + $viewer = User::factory()->create(); + $commit = Commit::factory()->create(); + $viewerBlocks ? $viewer->blocking()->attach($commit->user) : $commit->user->blocking()->attach($viewer); + + $this->actingAs($viewer)->getJson(route('commit-preview.show', [$commit->author, $commit]))->assertNotFound(); +})->with([false, true]); + +it('does not resolve deleted commits or a commit under the wrong author', function (): void { + $commit = Commit::factory()->create(); + + $this->getJson(route('commit-preview.show', [User::factory()->create()->profile, $commit]))->assertNotFound(); + $commit->delete(); + $this->getJson(route('commit-preview.show', [$commit->author, $commit]))->assertNotFound(); +}); + +it('shows linked poll results only when the viewer may see them', function (): void { + $viewer = User::factory()->create(); + $poll = Poll::factory()->withOptions('Tabs', 'Spaces')->create(); + $url = route('commit-preview.show', [$poll->commit->author, $poll->commit]); + + $this->getJson($url)->assertOk()->assertJsonPath('commit.poll.total_votes', null); + + PollVote::factory()->for($poll->options->first(), 'option')->for($viewer)->create(); + + $this->actingAs($viewer)->getJson($url)->assertOk() + ->assertJsonPath('commit.poll.total_votes', 1) + ->assertJsonPath('commit.poll.has_voted', true); +}); + it('renders a draft the way the commit it becomes is rendered', function (): void { $user = User::factory()->create(); User::factory()->create(['handle' => 'nunomaduro']); diff --git a/tests/Unit/CommitLinkPreview.test.tsx b/tests/Unit/CommitLinkPreview.test.tsx new file mode 100644 index 0000000000..3ccc13d25f --- /dev/null +++ b/tests/Unit/CommitLinkPreview.test.tsx @@ -0,0 +1,126 @@ +/// +import assert from 'node:assert/strict'; +import * as React from 'react'; +import type { ReactElement } from 'react'; +import { afterEach, test, vi } from 'vite-plus/test'; +import type { QuotedCommit as QuotedCommitData } from '../../resources/js/types'; + +let value: QuotedCommitData | null | undefined; +let effect: (() => () => void) | undefined; +let cleanup: (() => void) | undefined; + +vi.doMock('react', () => ({ + ...React, + useEffect: (callback: () => () => void) => { + effect = callback; + }, + useState: () => [value, (next: typeof value) => (value = next)], +})); + +const { CommitLinkPreview } = + await import('../../resources/js/components/commit-link-preview'); +const { LinkPreview } = + await import('../../resources/js/components/link-preview'); +const url = '/@author/commits/123e4567-e89b-12d3-a456-426614174000/preview'; + +afterEach(() => { + cleanup?.(); + cleanup = undefined; + effect = undefined; + value = undefined; + vi.unstubAllGlobals(); +}); + +function mount(): void { + CommitLinkPreview({ url }); + cleanup = effect?.(); +} + +test('fetches current commit data once instead of polling cached link metadata', async () => { + const commit = { id: 'linked' } as QuotedCommitData; + const fetch = vi + .fn() + .mockResolvedValue(new Response(JSON.stringify({ commit }))); + vi.stubGlobal('fetch', fetch); + mount(); + + await vi.waitFor(() => assert.deepEqual(value, commit)); + + const rendered = CommitLinkPreview({ url }) as ReactElement<{ + commit: QuotedCommitData; + label: string; + isPreview: boolean; + suppressLinkedPreview: boolean; + }>; + assert.deepEqual(rendered.props.commit, commit); + assert.equal(rendered.props.label, 'Linked commit'); + assert.equal(rendered.props.isPreview, false); + assert.equal(rendered.props.suppressLinkedPreview, true); + const staticCard = CommitLinkPreview({ url, isStatic: true }) as ReactElement<{ + isPreview: boolean; + }>; + assert.equal(staticCard.props.isPreview, true); + assert.equal(fetch.mock.calls.length, 1); + assert.equal(fetch.mock.calls[0][0], url); + assert.equal(fetch.mock.calls[0][1]?.cache, 'no-store'); +}); + +test('shows unavailable when the viewer cannot read the linked commit', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response(null, { status: 404 })), + ); + mount(); + + await vi.waitFor(() => assert.equal(value, null)); +}); + +test('handles a failed request without showing old preview content', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Offline'))); + mount(); + + await vi.waitFor(() => assert.equal(value, null)); +}); + +test('cancels the request when navigation removes the preview', async () => { + let finish: ((response: Response) => void) | undefined; + const fetch = vi + .fn() + .mockImplementation(() => new Promise((resolve) => (finish = resolve))); + vi.stubGlobal('fetch', fetch); + mount(); + cleanup?.(); + finish?.(new Response(JSON.stringify({ commit: { id: 'old-page' } }))); + await new Promise((resolve) => setTimeout(resolve, 0)); + + assert.equal(fetch.mock.calls[0][1]?.signal?.aborted, true); + assert.equal(value, undefined); +}); + +test('uses the actual commit preview and stops at one nesting level', () => { + const props = { + refreshUrl: '/unused-link-metadata', + preview: { + url: 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + title: 'Old cached content', + description: null, + image_url: null, + site_name: null, + is_pending: true, + commit_preview_url: url, + }, + }; + + const rendered = LinkPreview(props) as ReactElement<{ url: string }>; + + assert.equal(rendered.type, CommitLinkPreview); + assert.equal(rendered.props.url, url); + + // Static quotes keep the first linked card, but must not nest an interactive link. + const staticCard = LinkPreview({ ...props, isStatic: true }) as ReactElement<{ + isStatic: boolean; + }>; + assert.equal(staticCard.type, CommitLinkPreview); + assert.equal(staticCard.props.isStatic, true); + assert.equal(LinkPreview({ ...props, suppressLinkedPreview: true }), null); +}); diff --git a/tests/Unit/Jobs/UnfurlLinkTest.php b/tests/Unit/Jobs/UnfurlLinkTest.php index 194755436e..7f2611b309 100644 --- a/tests/Unit/Jobs/UnfurlLinkTest.php +++ b/tests/Unit/Jobs/UnfurlLinkTest.php @@ -38,6 +38,19 @@ function runNextQueuedJob(): void expect($linkPreview->refresh()->title)->toBe('Fetched before'); }); +it('does not fetch metadata for links to this sites commits', function (): void { + config(['app.url' => 'https://dev-null.sh']); + Http::fake(); + $preview = LinkPreview::factory()->create([ + 'url' => 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + ]); + + dispatch_sync(new UnfurlLink($preview)); + + Http::assertNothingSent(); + expect($preview->refresh()->fetched_at)->not->toBeNull(); +}); + it('retries a page that may be reachable later', function (): void { Exceptions::fake(); diff --git a/tests/Unit/Models/LinkPreviewTest.php b/tests/Unit/Models/LinkPreviewTest.php index 83447671b6..92a18353e7 100644 --- a/tests/Unit/Models/LinkPreviewTest.php +++ b/tests/Unit/Models/LinkPreviewTest.php @@ -21,6 +21,26 @@ ]); }); +it('replaces cached metadata of an internal commit with its private preview endpoint', function (): void { + config(['app.url' => 'https://dev-null.sh']); + $preview = LinkPreview::factory()->fetched()->create([ + 'url' => 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'title' => 'Previously public words', + 'description' => 'Cached content must not bypass visibility checks.', + 'image_url' => 'https://dev-null.sh/old-image.png', + ]); + + expect($preview->toArray())->toMatchArray([ + 'title' => null, + 'description' => null, + 'image_url' => null, + 'site_name' => null, + 'is_pending' => false, + 'embed' => null, + 'commit_preview_url' => '/@author/commits/123e4567-e89b-12d3-a456-426614174000/preview', + ]); +}); + it('is pending until it is fetched', function (): void { expect(LinkPreview::factory()->create()->toArray()['is_pending'])->toBeTrue() ->and(LinkPreview::factory()->fetched()->create()->toArray()['is_pending'])->toBeFalse() diff --git a/tests/Unit/QuotedCommit.test.tsx b/tests/Unit/QuotedCommit.test.tsx index b6eb97817f..8ba0faa1de 100644 --- a/tests/Unit/QuotedCommit.test.tsx +++ b/tests/Unit/QuotedCommit.test.tsx @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { createInertiaApp } from '@inertiajs/react'; import { renderToString } from 'react-dom/server'; -import { test } from 'vite-plus/test'; +import { test, vi } from 'vite-plus/test'; import { QuotedCommit } from '../../resources/js/components/quoted-commit'; import type { LinkPreview, @@ -29,6 +29,23 @@ const commit = { author: { id: 'author', name: 'Matthieu Napoli', handle: 'mnapoli' }, } as QuotedCommitData; +// The fetch lifecycle is covered in CommitLinkPreview.test.tsx. Here the linked +// commit is already loaded, so we can test its actual markup inside a quote. +let resolvedLinkedCommit: QuotedCommitData | null = null; + +vi.mock('../../resources/js/components/commit-link-preview', () => ({ + CommitLinkPreview: ({ isStatic }: { isStatic?: boolean }) => + resolvedLinkedCommit ? ( + + ) : ( +
+ ), +})); + const poll = { id: 'poll', closes_at: '2099-01-01T00:00:00.000000Z', @@ -155,6 +172,38 @@ test('keeps what others say about a link whose card has no title', async () => { assert.equal(body.match(/ { + const preview: LinkPreview = { + url: 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + title: null, + description: null, + image_url: null, + site_name: null, + is_pending: false, + commit_preview_url: + '/@author/commits/123e4567-e89b-12d3-a456-426614174000/preview', + }; + + resolvedLinkedCommit = { + ...commit, + id: 'linked', + body_segments: [{ type: 'text', text: 'Resolved linked commit' }], + preview_segments: null, + link_preview: preview, + }; + + try { + const body = await render(false, { ...commit, link_preview: preview }); + + assert.match(body, /Resolved linked commit/); + assert.equal(body.match(/data-test="quoted-commit"/g)?.length, 2); + assert.equal(body.match(/ { const body = await render(false, { ...commit, diff --git a/tests/Unit/Services/CommitLinksTest.php b/tests/Unit/Services/CommitLinksTest.php new file mode 100644 index 0000000000..9bb592c7b1 --- /dev/null +++ b/tests/Unit/Services/CommitLinksTest.php @@ -0,0 +1,28 @@ + 'https://dev-null.sh']); + $id = '123e4567-e89b-12d3-a456-426614174000'; + + expect(resolve(CommitLinks::class)->previewUrl("https://dev-null.sh/@author/commits/{$id}{$suffix}")) + ->toBe(route('commit-preview.show', ['profile' => 'author', 'commit' => $id], absolute: false)); +})->with(['', '?from=log#reply', '/']); + +it('does not resolve other sites or routes as commit previews', function (string $url): void { + config(['app.url' => 'https://dev-null.sh']); + + expect(resolve(CommitLinks::class)->previewUrl($url))->toBeNull(); +})->with([ + 'invalid url' => 'not a url', + 'other scheme' => 'ftp://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'other host' => 'https://example.com/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'lookalike host' => 'https://dev-null.sh.example.com/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'other port' => 'https://dev-null.sh:8443/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'profile' => 'https://dev-null.sh/@author', + 'invalid id' => 'https://dev-null.sh/@author/commits/not-a-uuid', + 'photo' => 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000/photos/1', +]); From 8d2cc450da2f19cb7e2443cb0286d65cb452ffd0 Mon Sep 17 00:00:00 2001 From: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:53:25 +0530 Subject: [PATCH 2/2] test: run TSX unit tests in the standard test command --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 376ea114ed..cc7182e5eb 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "lint": "NODE_OPTIONS='--experimental-strip-types' vp fmt resources/ && NODE_OPTIONS='--experimental-strip-types' vp lint --fix", "test:lint": "NODE_OPTIONS='--experimental-strip-types' vp fmt --check resources/ && NODE_OPTIONS='--experimental-strip-types' vp lint", "test:types": "tsc --noEmit && tsc --noEmit --project tests/tsconfig.json", - "test:unit": "php artisan wayfinder:generate --with-form && node --experimental-strip-types --test tests/Unit/*.test.ts" + "test:unit": "php artisan wayfinder:generate --with-form && node --experimental-strip-types --test tests/Unit/*.test.ts && vp test --config tests/draft-images.config.ts" }, "dependencies": { "@daypicker/react": "^10.0.2",