diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index c0dacdac00..d6810bdd3d 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -149,7 +149,9 @@ A developer who isn't here yet gets a page with their GitHub avatar, name, handl Its page shows how many members are waiting to follow them: the members who followed them on GitHub when they were looked up, and the ones who clicked **Follow** on their page, which then reads **Waiting** and can be clicked again to stop waiting. Members also see the people they follow among them. When the developer signs up, everyone waiting follows them, and their notifications show those follows like any others. Who you wait to follow is in your data export, and goes when you delete your account. If you delete your account, your page doesn't come back as one of these, until you sign in again. -Sources: [looking handles up](app/Http/Controllers/ProfileLookupController.php), [lookup page](resources/js/pages/profile/lookup.tsx), [developer page](resources/js/pages/profile/unclaimed.tsx), [GitHub lookups](app/Actions/CreateGitHubProfile.php). +Like an organization's page, it has a **Commits** tab and a **Mentions** tab. **Commits** stays empty until they sign up. **Mentions** lists the commits and replies that mention them, newest first, a reply with the commit it answers, with the usual visibility: guests see approved commits only, and commits across a block or by people you muted are left out. A commit is linked to them as it is posted when they already have a page, and the commits written before they had one are found shortly after their page is first looked up. A commit stays listed after they rename on GitHub, since it is linked to them rather than to the handle; if someone else takes their old handle, the page and its mentions go, and the page of whoever has the handle now only lists the commits posted after it. Nobody is notified of these mentions. + +Sources: [looking handles up](app/Http/Controllers/ProfileLookupController.php), [lookup page](resources/js/pages/profile/lookup.tsx), [developer page](resources/js/pages/profile/unclaimed.tsx), [GitHub lookups](app/Actions/CreateGitHubProfile.php), [mentions](app/Queries/UnclaimedProfileMentionsQuery.php), [earlier mentions](app/Actions/CreateUnclaimedProfileTopics.php). ### Going live @@ -265,7 +267,7 @@ The smiley button in the commit, reply and quote composers opens the same search In commits, replies, and remotes, start a line with `>` to render a quote block. Consecutive quoted lines stay together; an unquoted line ends the block. Quotes keep inline code, links, mentions, and emoji formatting. A `>` inside code or in the middle of a line stays literal. -Typing **@** in a composer opens developer suggestions. Use ↑/↓ to move, Enter or Tab to select, and Esc to dismiss. A bare @ suggests people you follow; typing more searches names and usernames. In replies, matching suggestions put the direct recipient first, then the root commit author, then other visible participants in that thread, followed by ordinary suggestions. Quotes prioritize only the quoted commit author. These priorities also apply to a bare @; typing a term still filters everyone, and yourself, muted developers, and blocked developers are excluded. In an org's messages, suggestions search the loaded member list instantly and update as membership refreshes. Suggestions are limited to the org's members, but you can still type anyone's handle yourself. Mentions link to profiles and can notify the mentioned developer after approval. Mentioning a GitHub organization, like `@laravel`, links to its [organization page](#organization-pages) and notifies its members: a known organization links right away, one mentioned for the first time once the commit is approved and GitHub confirms it is an organization. Typing @ followed by a few letters also suggests organizations that already have a page, after developers. Organization mentions only link in commits and replies, not in remotes. In commits and replies, but not in remotes, a mention of anyone else links to `/@handle` too, where signed-in members can [look them up on GitHub](#developers-not-on-devnull-yet); it never notifies anyone who isn't on /dev/null. Email addresses and scoped packages such as `@inertiajs/react` are not treated as mentions. +Typing **@** in a composer opens developer suggestions. Use ↑/↓ to move, Enter or Tab to select, and Esc to dismiss. A bare @ suggests people you follow; typing more searches names and usernames. In replies, matching suggestions put the direct recipient first, then the root commit author, then other visible participants in that thread, followed by ordinary suggestions. Quotes prioritize only the quoted commit author. These priorities also apply to a bare @; typing a term still filters everyone, and yourself, muted developers, and blocked developers are excluded. In an org's messages, suggestions search the loaded member list instantly and update as membership refreshes. Suggestions are limited to the org's members, but you can still type anyone's handle yourself. Mentions link to profiles and can notify the mentioned developer after approval. Mentioning a GitHub organization, like `@laravel`, links to its [organization page](#organization-pages) and notifies its members: a known organization links right away, one mentioned for the first time once the commit is approved and GitHub confirms it is an organization. Typing @ followed by a few letters also suggests organizations that already have a page, after developers. Organization mentions only link in commits and replies, not in remotes. In commits and replies, but not in remotes, a mention of anyone else links to `/@handle` too, where signed-in members can [look them up on GitHub](#developers-not-on-devnull-yet), and once they have a page it shows on their **Mentions** tab; it never notifies anyone who isn't on /dev/null. Email addresses and scoped packages such as `@inertiajs/react` are not treated as mentions. Typing **#123** in a composer looks up that exact issue or pull request in the /dev/null repository, `dev-null-sh/dev-null.sh`. The matching title appears beneath the number; click it or use Enter or Tab to insert its GitHub URL, just like choosing an emoji suggestion. A space or punctuation leaves the number as typed and dismisses the suggestion. Missing numbers and failed lookups leave the text unchanged. Code, URL fragments, and references qualified with another repository are not expanded. diff --git a/app/Actions/CreateCommit.php b/app/Actions/CreateCommit.php index a08c3c009b..f70a9405e5 100644 --- a/app/Actions/CreateCommit.php +++ b/app/Actions/CreateCommit.php @@ -25,6 +25,7 @@ use App\Models\User; use App\Queries\AdminsQuery; use App\Queries\MentionedOrganizationsQuery; +use App\Queries\MentionedUnclaimedProfilesQuery; use App\Queries\MentionedUsersQuery; use App\Queries\TomQuery; use App\Services\EmojiShortcodes; @@ -48,6 +49,7 @@ public function __construct( private Urls $urls, private MentionedUsersQuery $mentionedUsers, private MentionedOrganizationsQuery $mentionedOrganizations, + private MentionedUnclaimedProfilesQuery $mentionedUnclaimedProfiles, private CreateCommitTopics $createCommitTopics, private TomQuery $tomQuery, private AdminsQuery $admins, @@ -90,7 +92,7 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit 'created_at' => $createdAt, ]); - $this->createCommitTopics->handle($commit, $this->mentionedOrganizations->get($body, $mentions)); + $this->createCommitTopics->handle($commit, $this->mentionedOrganizations->get($body, $mentions), $this->mentionedUnclaimedProfiles->get($body, $mentions)); $this->createCommitImages->handle($commit, $images, $imageDescriptions); if ($poll instanceof NewPoll) { diff --git a/app/Actions/CreateCommitTopics.php b/app/Actions/CreateCommitTopics.php index 909dda3c25..e6d155bbe0 100644 --- a/app/Actions/CreateCommitTopics.php +++ b/app/Actions/CreateCommitTopics.php @@ -11,18 +11,25 @@ final readonly class CreateCommitTopics { /** - * Links the commit to the organizations it mentions, by the lowercase handle written in its body. A reference the - * commit is already linked by keeps what it was linked to. A handle of digits only is still a string reference. + * Links the commit to the organizations it mentions, and to the developers it mentions who aren't on /dev/null + * yet, by the lowercase handle written in its body. A reference the commit is already linked by keeps what it was + * linked to. A handle of digits only is still a string reference. * * @param array $organizations + * @param array $developers */ - public function handle(Commit $commit, array $organizations): void + public function handle(Commit $commit, array $organizations, array $developers = []): void { - DB::table('commit_topics')->insertOrIgnore(array_map(fn (int|string $reference, string $id): array => [ + $topics = fn (array $topics, TopicType $type): array => array_map(fn (int|string $reference, string $id): array => [ 'commit_id' => $commit->id, 'reference' => (string) $reference, - 'topic_type' => TopicType::Organization->value, + 'topic_type' => $type->value, 'topic_id' => $id, - ], array_keys($organizations), $organizations)); + ], array_keys($topics), $topics); + + DB::table('commit_topics')->insertOrIgnore([ + ...$topics($organizations, TopicType::Organization), + ...$topics($developers, TopicType::Developer), + ]); } } diff --git a/app/Actions/CreateGitHubProfile.php b/app/Actions/CreateGitHubProfile.php index 6063fc91c0..41dcfe94d7 100644 --- a/app/Actions/CreateGitHubProfile.php +++ b/app/Actions/CreateGitHubProfile.php @@ -7,11 +7,13 @@ use App\Contracts\Services\GitHubProvider; use App\Dto\GitHubProfile; use App\Enums\ProfileType; +use App\Jobs\LinkUnclaimedProfileTopics; use App\Models\Profile; use App\Models\User; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Str; final readonly class CreateGitHubProfile { @@ -25,7 +27,8 @@ public function __construct( /** * Gives the handle a page from its GitHub account: an organization's, or an unclaimed developer's, which keeps only - * what the page shows, with the members following them on GitHub waiting to follow them here. A user here who + * what the page shows, with the members following them on GitHub waiting to follow them here, and the commits that + * mentioned them linked to it, unless the handle was another page's here. A user here who * renamed on GitHub moves to the handle. A handle that is no GitHub account, or the account of someone who deleted * theirs here, is remembered for a day, so the page says so without asking GitHub again. */ @@ -56,6 +59,10 @@ public function handle(string $handle): void : $this->github->followerIds($profile->handle, CreateUserGitHubFollows::MaxPages); DB::transaction(function () use ($profile, $githubId, $followerIds): void { + // Read before the stale handles move, as the earlier mentions of a handle that was someone else's page + // here were meant for them... + $wasAnothersHandle = Profile::query()->where('handle', $profile->handle)->where('github_id', '!=', $githubId)->exists(); + $this->updateStaleHandles->handle($profile->handle, $githubId); $existing = Profile::query()->where('type', ProfileType::User)->firstWhere('github_id', $githubId); @@ -67,7 +74,7 @@ public function handle(string $handle): void return; } - Profile::query()->updateOrCreate(['github_id' => $githubId, 'type' => ProfileType::User], [ + $unclaimed = Profile::query()->updateOrCreate(['github_id' => $githubId, 'type' => ProfileType::User], [ 'handle' => $profile->handle, 'name' => $profile->name, 'avatar_url' => $profile->avatarUrl, @@ -75,6 +82,12 @@ public function handle(string $handle): void 'github_synced_at' => now(), ]); + // The commits that mentioned them before are linked to their page, at its new handle too, unless they + // meant whoever had the handle here before... + if (! $wasAnothersHandle && ($unclaimed->wasRecentlyCreated || $this->movedHandle($unclaimed))) { + dispatch(new LinkUnclaimedProfileTopics($unclaimed))->afterCommit(); + } + // Those still waiting from before the profile last went are kept... DB::table('pending_follows')->insertOrIgnoreUsing( ['user_id', 'github_id', 'created_at'], @@ -82,4 +95,15 @@ public function handle(string $handle): void ); }); } + + /** + * A handle is one whatever its case, so only a new one moves the page: a change of case leaves its mentions as + * they are. + */ + private function movedHandle(Profile $profile): bool + { + $previous = $profile->getPrevious()['handle'] ?? null; + + return is_string($previous) && Str::lower($previous) !== Str::lower($profile->handle); + } } diff --git a/app/Actions/CreateUnclaimedProfileTopics.php b/app/Actions/CreateUnclaimedProfileTopics.php new file mode 100644 index 0000000000..93ffcbb0ba --- /dev/null +++ b/app/Actions/CreateUnclaimedProfileTopics.php @@ -0,0 +1,106 @@ +developers($profiles); + + if ($developers === []) { + return; + } + + $this->link(Commit::withTrashed() + ->where(function (Builder $query) use ($developers): void { + foreach (array_keys($developers) as $handle) { + $query->orWhere('body', 'ilike', '%@'.addcslashes((string) $handle, '\\%_').'%'); + } + }) + ->select(['id', 'body', 'mentions']) + ->lazyById(500), $developers); + } + + /** + * The given developers, or every one, who have a page but aren't on /dev/null yet, by lowercase handle. + * + * @param iterable|null $profiles + * @return array + */ + public function developers(?iterable $profiles = null): array + { + $developers = []; + + foreach ($profiles ?? Profile::query()->where('type', ProfileType::User)->whereDoesntHave('user')->lazyById(500) as $profile) { + // The query already left out the claimed ones... + if ($profiles === null || $profile->isUnclaimed()) { + $developers[Str::lower($profile->handle)] = $profile->id; + } + } + + return $developers; + } + + /** + * Links each of the commits to the developers it mentions among the given ones. A mention of a handle that was a + * user's when it was written stays that user's. Each commit is linked as it is, locked, so a commit erased in the + * meantime gets none. Returns how many commits were linked. + * + * @param iterable $commits + * @param array $developers + */ + public function link(iterable $commits, array $developers): int + { + $linked = 0; + + foreach ($commits as $commit) { + if ($this->mentioned($commit, $developers) === []) { + continue; + } + + $linked += DB::transaction(function () use ($commit, $developers): int { + $commit = Commit::withTrashed()->lockForUpdate()->find($commit->id); + $mentioned = $commit instanceof Commit ? $this->mentioned($commit, $developers) : []; + + if (! $commit instanceof Commit || $mentioned === []) { + return 0; + } + + $this->createCommitTopics->handle($commit, [], $mentioned); + + return 1; + }); + } + + return $linked; + } + + /** + * @param array $developers + * @return array + */ + private function mentioned(Commit $commit, array $developers): array + { + return array_intersect_key($developers, array_flip($commit->mentionedNonUsers())); + } +} diff --git a/app/Actions/DeleteUser.php b/app/Actions/DeleteUser.php index e711d5438f..af7f176b26 100644 --- a/app/Actions/DeleteUser.php +++ b/app/Actions/DeleteUser.php @@ -6,6 +6,7 @@ use App\Enums\CommitUpdate; use App\Enums\ConversationKind; +use App\Enums\TopicType; use App\Enums\UserUpdate; use App\Events\CommitsUpdated; use App\Events\UsersUpdated; @@ -76,6 +77,8 @@ public function handle(User $user): void resolve(DeleteStoredFiles::class)->retain($imagePaths); DB::table('commit_topics')->whereIn('commit_id', $this->touchedCommits($user)->select('id'))->delete(); + // What mentioned them before they signed up was linked to their profile, which goes... + DB::table('commit_topics')->where('topic_type', TopicType::Developer)->where('topic_id', $user->id)->delete(); Headline::query()->whereIn('id', DB::table('commit_headline')->select('headline_id') ->whereIn('commit_id', $this->touchedCommits($user)->select('id'))) ->update(['summary' => null, 'summary_created_at' => null]); diff --git a/app/Actions/UpdateCommitTopics.php b/app/Actions/UpdateCommitTopics.php index 4e54eeaee1..4f7dda0f36 100644 --- a/app/Actions/UpdateCommitTopics.php +++ b/app/Actions/UpdateCommitTopics.php @@ -6,6 +6,7 @@ use App\Models\Commit; use App\Queries\MentionedOrganizationsQuery; +use App\Queries\MentionedUnclaimedProfilesQuery; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\DB; @@ -14,15 +15,16 @@ public function __construct( private UpdateMentionedOrganizations $updateMentionedOrganizations, private MentionedOrganizationsQuery $mentionedOrganizations, + private MentionedUnclaimedProfilesQuery $mentionedUnclaimedProfiles, private CreateCommitTopics $createCommitTopics, ) { // } /** - * Looks the organizations the commit mentions up, then links the commit to them. The links come from the commit as - * it is after the lookups, locked, so a commit erased in the meantime gets none. Returns when to try again if the - * rate limit cut the lookups short. + * Looks the organizations the commit mentions up, then links the commit to them, and to the developers it mentions + * who have a page but aren't on /dev/null yet. The links come from the commit as it is after the lookups, locked, + * so a commit erased in the meantime gets none. Returns when to try again if the rate limit cut the lookups short. */ public function handle(Commit $commit): ?CarbonImmutable { @@ -38,7 +40,11 @@ public function handle(Commit $commit): ?CarbonImmutable $commit = Commit::withTrashed()->lockForUpdate()->find($commit->id); if ($commit instanceof Commit) { - $this->createCommitTopics->handle($commit, $this->mentionedOrganizations->get($commit->body, $commit->mentions ?? [])); + $this->createCommitTopics->handle( + $commit, + $this->mentionedOrganizations->get($commit->body, $commit->mentions ?? []), + $this->mentionedUnclaimedProfiles->get($commit->body, $commit->mentions ?? []), + ); } }); diff --git a/app/Actions/UpdateStaleHandles.php b/app/Actions/UpdateStaleHandles.php index 01497cd139..06af44be3c 100644 --- a/app/Actions/UpdateStaleHandles.php +++ b/app/Actions/UpdateStaleHandles.php @@ -4,7 +4,9 @@ namespace App\Actions; +use App\Enums\TopicType; use App\Models\Profile; +use Illuminate\Support\Facades\DB; final readonly class UpdateStaleHandles { @@ -12,8 +14,8 @@ * GitHub handles are unique case-insensitively, so another profile holding this one renamed away on GitHub. The * placeholder starts with an underscore, which no GitHub handle can, and their next sync restores a real one. * Bots keep their identity under reserved handles so they can continue replying. An unclaimed profile, a developer - * looked up from GitHub who never signed in, has nothing of its own, so it goes: looking its new handle up brings it - * back, with the members waiting for it, kept by its GitHub ID. + * looked up from GitHub who never signed in, has nothing of its own, so it goes, with the mentions linked to it: + * looking its new handle up brings it back, with the members waiting for it, kept by its GitHub ID. */ public function handle(string $handle, string $githubId): void { @@ -22,6 +24,7 @@ public function handle(string $handle, string $githubId): void ->where('github_id', '!=', $githubId) ->each(function (Profile $profile): void { if ($profile->isUnclaimed()) { + DB::table('commit_topics')->where('topic_type', TopicType::Developer)->where('topic_id', $profile->id)->delete(); $profile->delete(); return; diff --git a/app/Console/Commands/LinkCommitDevelopersCommand.php b/app/Console/Commands/LinkCommitDevelopersCommand.php new file mode 100644 index 0000000000..aa8ebb69f4 --- /dev/null +++ b/app/Console/Commands/LinkCommitDevelopersCommand.php @@ -0,0 +1,34 @@ +developers(); + + $linked = $developers === [] ? 0 : $createUnclaimedProfileTopics->link( + Commit::withTrashed()->where('body', 'like', '%@%')->select(['id', 'body', 'mentions'])->lazyById(500), + $developers, + ); + + $this->components->info("Linked {$linked} commits to the developers they mention."); + + return self::SUCCESS; + } +} diff --git a/app/Enums/TopicType.php b/app/Enums/TopicType.php index a964300138..6b0fc71ad4 100644 --- a/app/Enums/TopicType.php +++ b/app/Enums/TopicType.php @@ -5,10 +5,11 @@ namespace App\Enums; /** - * What a commit topic is, stored in `commit_topics.topic_type` next to its id. Only GitHub organizations so far, whose - * id is their profile's. + * What a commit topic is, stored in `commit_topics.topic_type` next to its id: a GitHub organization, or a developer + * who wasn't on /dev/null yet when the commit mentioned them. Either way, the id is their profile's. */ enum TopicType: string { case Organization = 'organization'; + case Developer = 'developer'; } diff --git a/app/Http/Controllers/UnclaimedProfileController.php b/app/Http/Controllers/UnclaimedProfileController.php index 7af73204ba..a5d231699c 100644 --- a/app/Http/Controllers/UnclaimedProfileController.php +++ b/app/Http/Controllers/UnclaimedProfileController.php @@ -5,11 +5,14 @@ namespace App\Http\Controllers; use App\Http\Requests\ShowUnclaimedProfileRequest; +use App\Http\Resources\ShownStreams; use App\Models\Profile; use App\Models\User; +use App\Queries\UnclaimedProfileMentionsQuery; use App\Services\PageMetadata; use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\RedirectResponse; +use Illuminate\Pagination\CursorPaginator; use Illuminate\Support\Facades\DB; use Inertia\Inertia; use Inertia\Response; @@ -19,9 +22,10 @@ /** * A developer looked up from GitHub who isn't on /dev/null yet has a page at their "@handle", with what GitHub * shows of them but where they are, for anyone with the link, but kept out of search engines, with how many members - * wait to follow them. Signing in as them makes it theirs. Like users' pages, it moves for good to the handle's own case. + * wait to follow them and, like an organization's, the commits that mention them. Their own Commits tab stays + * empty until signing in as them makes the page theirs. Like users' pages, it moves for good to the handle's own case. */ - public function show(ShowUnclaimedProfileRequest $request, #[CurrentUser] ?User $currentUser, PageMetadata $metadata): RedirectResponse|Response + public function show(ShowUnclaimedProfileRequest $request, #[CurrentUser] ?User $currentUser, UnclaimedProfileMentionsQuery $mentions, PageMetadata $metadata): RedirectResponse|Response { $profile = $request->profile(); assert($profile instanceof Profile); @@ -37,6 +41,10 @@ public function show(ShowUnclaimedProfileRequest $request, #[CurrentUser] ?User return Inertia::render('profile/unclaimed', [ 'profile' => $profile->only(['id', 'handle', 'name', 'avatar_url', 'bio']), + 'tab' => $request->tab(...), + 'commits' => Inertia::scroll(fn (): CursorPaginator => $request->tab() === 'mentions' + ? ShownStreams::page($mentions->builder($profile, $currentUser)->cursorPaginate(20)->appends(['tab' => 'mentions'])) + : new CursorPaginator([], 20, options: ['path' => $request->url()])), 'waitingCount' => fn (): int => $waiting->clone()->count(), 'isWaiting' => fn (): bool => $currentUser instanceof User && $waiting->clone()->where('user_id', $currentUser->id)->exists(), // Who follows whom is for members, so only they see who is waiting, among the people they follow... diff --git a/app/Http/Requests/ShowUnclaimedProfileRequest.php b/app/Http/Requests/ShowUnclaimedProfileRequest.php index 81f039fd5e..3d6a186611 100644 --- a/app/Http/Requests/ShowUnclaimedProfileRequest.php +++ b/app/Http/Requests/ShowUnclaimedProfileRequest.php @@ -18,11 +18,21 @@ public function authorize(): Response } /** - * @return array{} + * @return array> */ public function rules(): array { - return []; + return [ + 'tab' => ['nullable', 'string', 'in:commits,mentions'], + ]; + } + + /** + * Their own commits first, which wait for them to sign up, then the commits that mention them. + */ + public function tab(): string + { + return $this->string('tab')->value() === 'mentions' ? 'mentions' : 'commits'; } /** diff --git a/app/Jobs/LinkUnclaimedProfileTopics.php b/app/Jobs/LinkUnclaimedProfileTopics.php new file mode 100644 index 0000000000..bc3434a4e3 --- /dev/null +++ b/app/Jobs/LinkUnclaimedProfileTopics.php @@ -0,0 +1,31 @@ +handle($this->profile); + } +} diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 805af50de6..76283e9ec5 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -33,6 +33,7 @@ * @property-read string $body * @property-read array|null $mentions * @property-read array|null $organization_mentions + * @property-read array|null $developer_mentions * @property-read CommitStatus $status * @property-read string|null $link_preview_id * @property-read string|null $quoted_commit_id @@ -126,6 +127,7 @@ public function casts(): array 'body' => 'string', 'mentions' => 'array', 'organization_mentions' => 'array', + 'developer_mentions' => 'array', 'status' => CommitStatus::class, 'link_preview_id' => 'string', 'quoted_commit_id' => 'string', diff --git a/app/Queries/CommitBuilder.php b/app/Queries/CommitBuilder.php index 34f06f2918..744f3c4b8e 100644 --- a/app/Queries/CommitBuilder.php +++ b/app/Queries/CommitBuilder.php @@ -5,10 +5,12 @@ namespace App\Queries; use App\Enums\CommitStatus; +use App\Enums\ProfileType; use App\Enums\RepliesPerPage; use App\Enums\TopicType; use App\Models\Commit; use App\Models\Organization; +use App\Models\Profile; use App\Models\User; use App\Services\CommitTranslations; use Illuminate\Contracts\Database\Query\Expression; @@ -39,10 +41,17 @@ final class CommitBuilder extends Builder */ private const string ORGANIZATION_MENTIONS = "(select json_object_agg(reference, topic_id) from commit_topics where commit_topics.commit_id = commits.id and topic_type = 'organization') as organization_mentions"; + /** + * The developers a commit mentions who weren't on /dev/null yet, by lowercase handle, from its topics of type + * TopicType::Developer. + */ + private const string DEVELOPER_MENTIONS = "(select json_object_agg(reference, topic_id) from commit_topics where commit_topics.commit_id = commits.id and topic_type = 'developer') as developer_mentions"; + /** * Embeddings are only ever compared within the database, so commits are loaded without theirs rather than carry - * kilobytes of numbers each that nothing reads. They come with the organizations they mention instead, by lowercase - * handle, read from their topics in the same query, so rendering a page of commits takes no query more. + * kilobytes of numbers each that nothing reads. They come with the organizations they mention instead, and the + * developers who weren't on /dev/null yet, by lowercase handle, read from their topics in the same query, so + * rendering a page of commits takes no query more. * * @param array|string $columns * @return array @@ -53,7 +62,7 @@ public function getModels($columns = ['*']): array $this->query->columns = array_merge(...array_map( fn (Expression|string $column): array => $this->isEveryColumn($column) - ? [...array_map($this->qualifyColumn(...), self::COLUMNS_BUT_EMBEDDING), new QueryExpression(self::ORGANIZATION_MENTIONS)] + ? [...array_map($this->qualifyColumn(...), self::COLUMNS_BUT_EMBEDDING), new QueryExpression(self::ORGANIZATION_MENTIONS), new QueryExpression(self::DEVELOPER_MENTIONS)] : [$column], $selected ?? (array) $columns, )); @@ -217,15 +226,16 @@ public function approved(): self } /** - * The commits linked to the organization by a mention, whatever handle it had when they were written. + * The commits linked by a mention to the organization, or to the developer who wasn't on /dev/null yet when they + * were written, whatever handle it had then. */ - public function mentioning(Organization $organization): self + public function mentioning(Organization|Profile $mentioned): self { return $this->whereExists(fn (QueryBuilder $query): QueryBuilder => $query ->from('commit_topics') ->whereColumn('commit_topics.commit_id', $this->qualifyColumn('id')) - ->where('commit_topics.topic_type', TopicType::Organization) - ->where('commit_topics.topic_id', $organization->id)); + ->where('commit_topics.topic_type', $mentioned instanceof Organization || $mentioned->type === ProfileType::Organization ? TopicType::Organization : TopicType::Developer) + ->where('commit_topics.topic_id', $mentioned->id)); } /** diff --git a/app/Queries/MentionedUnclaimedProfilesQuery.php b/app/Queries/MentionedUnclaimedProfilesQuery.php new file mode 100644 index 0000000000..92625e0673 --- /dev/null +++ b/app/Queries/MentionedUnclaimedProfilesQuery.php @@ -0,0 +1,42 @@ + $mentionedUsers + * @return array + */ + public function get(string $body, array $mentionedUsers): array + { + $handles = array_values(array_diff($this->mentions->handles($body), array_keys($mentionedUsers))); + + if ($handles === []) { + return []; + } + + return Profile::query() + ->where('type', ProfileType::User) + ->whereIn('handle', $handles) + ->whereDoesntHave('user') + ->get() + ->mapWithKeys(fn (Profile $profile): array => [Str::lower($profile->handle) => $profile->id]) + ->all(); + } +} diff --git a/app/Queries/UnclaimedProfileMentionsQuery.php b/app/Queries/UnclaimedProfileMentionsQuery.php new file mode 100644 index 0000000000..e3cc6ddc09 --- /dev/null +++ b/app/Queries/UnclaimedProfileMentionsQuery.php @@ -0,0 +1,34 @@ +mentioning($profile) + ->visibleTo($viewer) + ->withoutMutedAuthorsFor($viewer) + ->with(['parent' => fn (BelongsTo $query): BelongsTo => $query + ->where(fn (CommitBuilder $query): CommitBuilder => $query->visibleTo($viewer)) + ->with('author')]) + ->withVisibleReplyCount($viewer) + ->withReplyPreviews($viewer) + ->withCardDataFor($viewer) + ->latest() + ->latest('id'); + } +} diff --git a/resources/js/components/commit-feed.tsx b/resources/js/components/commit-feed.tsx index 32a573ab0a..837dff644c 100644 --- a/resources/js/components/commit-feed.tsx +++ b/resources/js/components/commit-feed.tsx @@ -62,6 +62,14 @@ export function CommitFeed({ page.component === 'organization/show' ? (page.props.organization as { id: string }).id : null; + // A developer who isn't here yet has a Mentions tab like an organization's, which lists replies too, and a + // Commits tab that stays empty until they sign up. + const unclaimedProfileId = + page.component === 'profile/unclaimed' + ? (page.props.profile as { id: string }).id + : null; + const isUnclaimedMentions = + unclaimedProfileId !== null && page.props.tab === 'mentions'; const [highlightedAuthor, setHighlightedAuthor] = useState( null, ); @@ -152,13 +160,18 @@ export function CommitFeed({ const belongsInFeed = (isStarred ? restored.starred === true - : mentionedOrganizationId !== null - ? Object.values( - restored.organization_mentions ?? {}, - ).includes(mentionedOrganizationId) - : isProfileReplies - ? restored.parent_id !== null - : restored.parent_id === null) && + : unclaimedProfileId !== null + ? isUnclaimedMentions && + Object.values( + restored.developer_mentions ?? {}, + ).includes(unclaimedProfileId) + : mentionedOrganizationId !== null + ? Object.values( + restored.organization_mentions ?? {}, + ).includes(mentionedOrganizationId) + : isProfileReplies + ? restored.parent_id !== null + : restored.parent_id === null) && (profileUserId === null || (restored.author.id === profileUserId && !restored.is_pinned)); @@ -183,6 +196,8 @@ export function CommitFeed({ isModeration, isProfileReplies, mentionedOrganizationId, + unclaimedProfileId, + isUnclaimedMentions, isStarred, isRanked, ], diff --git a/resources/js/pages/profile/unclaimed.tsx b/resources/js/pages/profile/unclaimed.tsx index fc86284749..5d5791e6d9 100644 --- a/resources/js/pages/profile/unclaimed.tsx +++ b/resources/js/pages/profile/unclaimed.tsx @@ -4,8 +4,10 @@ import { useState } from 'react'; import PendingFollowController from '@/actions/App/Http/Controllers/PendingFollowController'; import { show } from '@/actions/App/Http/Controllers/UserController'; import { BioText } from '@/components/bio-text'; +import { CommitFeed, EmptyFeed } from '@/components/commit-feed'; import { useFollowHover } from '@/components/follow-button'; import { GitHubIcon } from '@/components/github-icon'; +import { PageTabs } from '@/components/page-tabs'; import { ProfileShareButton } from '@/components/profile-share-button'; import { Button } from '@/components/ui/button'; import { UserAvatar } from '@/components/user-avatar'; @@ -13,7 +15,7 @@ import AppLayout from '@/layouts/app-layout'; import { exactCountTitle, formatCount } from '@/lib/numbers'; import { toastWhenThrottled } from '@/lib/throttle'; import { login } from '@/routes'; -import type { User } from '@/types'; +import type { Commit, CursorPaginated, User } from '@/types'; type UnclaimedProfile = { id: string; @@ -24,16 +26,20 @@ type UnclaimedProfile = { }; /** - * A developer looked up from GitHub who isn't on /dev/null yet. Signing in as them makes the page theirs. Where they - * are is left out, even when GitHub shows it: they never chose to share it here. + * A developer looked up from GitHub who isn't on /dev/null yet, with the commits that mention them. Signing in as them + * makes the page theirs. Where they are is left out, even when GitHub shows it: they never chose to share it here. */ export default function UnclaimedProfile({ profile, + tab, + commits, waitingCount, isWaiting, waitingYouFollow, }: { profile: UnclaimedProfile; + tab: 'commits' | 'mentions'; + commits: CursorPaginated; waitingCount: number; isWaiting: boolean; waitingYouFollow: Pick[]; @@ -155,14 +161,51 @@ export default function UnclaimedProfile({ )} -
-

- $ git log --author={profile.handle} -

-

- @{profile.handle} hasn't committed here yet. When they sign - in with GitHub, this page becomes theirs. -

+
+ + + + Nobody has mentioned @{profile.handle} yet. + Mention them in a commit and it shows up here. + + ) : ( + + @{profile.handle} hasn't committed here yet. + When they sign in with GitHub, this page becomes + theirs. + + ) + } + />
); diff --git a/resources/js/types/commit.ts b/resources/js/types/commit.ts index 73c8df690e..adc3a81354 100644 --- a/resources/js/types/commit.ts +++ b/resources/js/types/commit.ts @@ -91,6 +91,7 @@ export type Commit = { body: string; mentions: Record | null; organization_mentions?: Record | null; + developer_mentions?: Record | null; body_segments: BodySegment[]; preview_segments: BodySegment[] | null; translation?: CommitTranslation | null; diff --git a/tests/Feature/Commands/LinkCommitDevelopersTest.php b/tests/Feature/Commands/LinkCommitDevelopersTest.php new file mode 100644 index 0000000000..4756451fdd --- /dev/null +++ b/tests/Feature/Commands/LinkCommitDevelopersTest.php @@ -0,0 +1,39 @@ +create(['handle' => 'octocat']); + $monalisa = Profile::factory()->create(['handle' => 'MonaLisa']); + $claimed = User::factory()->create(['handle' => 'hubot']); + $both = Commit::factory()->create(['body' => 'Thanks @OctoCat and @monalisa', 'mentions' => []]); + $deleted = tap(Commit::factory()->create(['body' => 'Hi @octocat', 'mentions' => []]))->delete(); + Commit::factory()->create(['body' => '`@octocat` in code', 'mentions' => []]); + Commit::factory()->create(['body' => 'Hi @hubot', 'mentions' => []]); + Commit::factory()->create(['body' => 'No mention']); + + DB::enableQueryLog(); + + $this->artisan('commits:link-developers') + ->expectsOutputToContain('Linked 2 commits to the developers they mention.') + ->assertSuccessful(); + + $scans = collect(DB::getQueryLog())->filter(fn (array $query): bool => str_contains($query['query'], 'from "commits" where "body"')); + DB::disableQueryLog(); + + expect($both->refresh()->developer_mentions)->toEqualCanonicalizing(['octocat' => $octocat->id, 'monalisa' => $monalisa->id]) + ->and(Commit::withTrashed()->findOrFail($deleted->id)->developer_mentions)->toBe(['octocat' => $octocat->id]) + ->and(DB::table('commit_topics')->where('topic_type', TopicType::Developer)->count())->toBe(3) + ->and(DB::table('commit_topics')->where('topic_id', $claimed->id)->exists())->toBeFalse() + ->and($scans)->toHaveCount(1); + + $this->artisan('commits:link-developers')->assertSuccessful(); + + expect(DB::table('commit_topics')->where('topic_type', TopicType::Developer)->count())->toBe(3); +}); diff --git a/tests/Feature/Controllers/UnclaimedProfileControllerTest.php b/tests/Feature/Controllers/UnclaimedProfileControllerTest.php index be3efd30e9..8030e0c774 100644 --- a/tests/Feature/Controllers/UnclaimedProfileControllerTest.php +++ b/tests/Feature/Controllers/UnclaimedProfileControllerTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +use App\Actions\CreateCommitTopics; +use App\Models\Commit; use App\Models\Profile; use App\Models\User; use Illuminate\Support\Facades\DB; @@ -80,3 +82,77 @@ ->where('isWaiting', true) ->where('waitingYouFollow', [$followed->only(['id', 'handle', 'name', 'avatar_url'])])); }); + +it('opens on their own commits, which wait for them to sign up', function (): void { + $profile = Profile::factory()->create(['handle' => 'octocat']); + $commit = Commit::factory()->create(['body' => 'Thanks @octocat']); + resolve(CreateCommitTopics::class)->handle($commit, [], ['octocat' => $profile->id]); + + $this->get('/@octocat') + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('profile/unclaimed') + ->where('tab', 'commits') + ->has('commits.data', 0) + ->where('commits.next_page_url', null)); +}); + +it('lists the commits and replies that mention them, newest first, to guests too', function (): void { + $profile = Profile::factory()->create(['handle' => 'octocat']); + $other = Profile::factory()->create(['handle' => 'monalisa']); + $mention = fn (Commit $commit, ?Profile $mentioned = null): Commit => tap($commit, fn () => resolve(CreateCommitTopics::class)->handle($commit, [], [($mentioned ?? $profile)->handle => ($mentioned ?? $profile)->id])); + + $older = $mention(Commit::factory()->create(['body' => 'Thanks @octocat', 'created_at' => now()->subHour()])); + $parent = Commit::factory()->create(['body' => 'Who made this?', 'created_at' => now()->subMinutes(30)]); + $reply = $mention(Commit::factory()->for($parent, 'parent')->create(['body' => '@octocat did'])); + $mention(Commit::factory()->pending()->create(['body' => 'Pending @octocat'])); + $mention(Commit::factory()->create(['body' => 'Deleted @octocat']))->delete(); + $mention(Commit::factory()->create(['body' => 'Thanks @monalisa']), $other); + + $this->get('/@octocat?tab=mentions') + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('profile/unclaimed') + ->where('tab', 'mentions') + ->has('commits.data', 2) + ->where('commits.data.0.id', $reply->id) + ->where('commits.data.0.parent.id', $parent->id) + ->where('commits.data.0.developer_mentions.octocat', $profile->id) + ->where('commits.data.1.id', $older->id)); +}); + +it('lists their mentions as the viewer may see them, without their muted authors', function (): void { + $viewer = User::factory()->create(); + $muted = User::factory()->create(); + $blocked = User::factory()->create(); + $viewer->muting()->attach($muted); + $viewer->blocking()->attach($blocked); + $profile = Profile::factory()->create(['handle' => 'octocat']); + $mention = fn (Commit $commit): Commit => tap($commit, fn () => resolve(CreateCommitTopics::class)->handle($commit, [], ['octocat' => $profile->id])); + + $pending = $mention(Commit::factory()->for($viewer)->pending()->create(['body' => 'Pending @octocat'])); + $hiddenParent = $mention(Commit::factory()->for(Commit::factory()->pending(), 'parent')->create(['body' => '@octocat', 'created_at' => now()->subMinute()])); + $mention(Commit::factory()->for($muted)->create(['body' => 'Muted @octocat'])); + $mention(Commit::factory()->for($blocked)->create(['body' => 'Blocked @octocat'])); + + $this->actingAs($viewer)->get('/@octocat?tab=mentions') + ->assertOk() + ->assertInertia(fn ($page) => $page + ->has('commits.data', 2) + ->where('commits.data.0.id', $pending->id) + ->where('commits.data.1.id', $hiddenParent->id) + ->where('commits.data.1.parent', null)); +}); + +it('pages through their mentions with the tab in the link to the next page', function (): void { + $profile = Profile::factory()->create(['handle' => 'octocat']); + + Commit::factory()->count(21)->sequence(fn ($sequence): array => ['created_at' => now()->subMinutes($sequence->index)])->create(['body' => 'Thanks @octocat']) + ->each(fn (Commit $commit) => resolve(CreateCommitTopics::class)->handle($commit, [], ['octocat' => $profile->id])); + + $this->get('/@octocat?tab=mentions') + ->assertOk() + ->assertInertia(fn ($page) => $page + ->has('commits.data', 20) + ->where('commits.next_page_url', fn (string $url): bool => str_contains($url, 'tab=mentions'))); +}); diff --git a/tests/Feature/UnclaimedProfileMentionsTest.php b/tests/Feature/UnclaimedProfileMentionsTest.php new file mode 100644 index 0000000000..945aa171ce --- /dev/null +++ b/tests/Feature/UnclaimedProfileMentionsTest.php @@ -0,0 +1,151 @@ + + */ +function developerTopics(): array +{ + return DB::table('commit_topics') + ->where('topic_type', TopicType::Developer) + ->orderBy('commit_id') + ->pluck('topic_id', 'commit_id') + ->all(); +} + +it('links a commit to the developers with a page who are not here yet, apart from users and organizations', function (): void { + Queue::fake(); + + $author = User::factory()->create(); + $tom = User::factory()->create(['handle' => 'tom']); + $laravel = Organization::factory()->create(['handle' => 'laravel']); + $octocat = Profile::factory()->create(['handle' => 'octocat']); + + $this->actingAs($author)->post('/commits', ['body' => 'Thanks @OctoCat, @tom, @laravel and @nobody'])->assertRedirect(); + + $commit = $author->commits()->sole(); + + expect($commit->mentions)->toBe(['tom' => $tom->id]) + ->and($commit->organization_mentions)->toBe(['laravel' => $laravel->id]) + ->and(developerTopics())->toBe([$commit->id => $octocat->id]); +}); + +it('links the commits that mentioned a developer before they had a page', function (): void { + $octocat = Profile::factory()->create(['handle' => 'octocat']); + $claimed = User::factory()->create(['handle' => 'monalisa']); + + $mention = Commit::factory()->create(['body' => 'Thanks @OctoCat!', 'mentions' => []]); + $reply = Commit::factory()->for(Commit::factory(), 'parent')->create(['body' => 'cc @octocat', 'mentions' => []]); + $deleted = tap(Commit::factory()->create(['body' => 'Hi @octocat', 'mentions' => []]))->delete(); + Commit::factory()->create(['body' => '`@octocat` in code', 'mentions' => []]); + Commit::factory()->create(['body' => 'Hi @octocat-fan and octocat@example.com', 'mentions' => []]); + Commit::factory()->create(['body' => 'Hi @octocat', 'mentions' => ['octocat' => $claimed->id]]); + Commit::factory()->create(['body' => 'Hi @monalisa', 'mentions' => []]); + + resolve(CreateUnclaimedProfileTopics::class)->handle($octocat, $claimed->profile); + resolve(CreateUnclaimedProfileTopics::class)->handle($octocat); + + expect(developerTopics())->toEqualCanonicalizing([ + $mention->id => $octocat->id, + $reply->id => $octocat->id, + $deleted->id => $octocat->id, + ]); +}); + +it('looks up the earlier mentions of a developer once they get a page, and at their new handle', function (): void { + Queue::fake([LinkUnclaimedProfileTopics::class]); + $account = ['login' => 'octocat', 'id' => 583231, 'type' => 'User', 'name' => 'The Octocat', 'avatar_url' => null, 'bio' => null, 'location' => null, 'blog' => '', 'company' => null]; + $github = $this->mock(GitHubProvider::class); + $github->shouldReceive('accountByLogin')->with('octocat')->andReturn($account); + $github->shouldReceive('accountByLogin')->with('octocat-new')->andReturn([...$account, 'login' => 'octocat-new']); + $github->shouldReceive('followerIds')->andReturn([]); + + resolve(CreateGitHubProfile::class)->handle('octocat'); + resolve(CreateGitHubProfile::class)->handle('octocat'); + + $profile = Profile::query()->sole(); + Queue::assertPushed(LinkUnclaimedProfileTopics::class, 1); + Queue::assertPushed(LinkUnclaimedProfileTopics::class, fn (LinkUnclaimedProfileTopics $job): bool => $job->profile->is($profile)); + + resolve(CreateGitHubProfile::class)->handle('octocat-new'); + + Queue::assertPushed(LinkUnclaimedProfileTopics::class, 2); +}); + +it('reads the commits again for a new handle, not a change of case', function (): void { + Queue::fake([LinkUnclaimedProfileTopics::class]); + $account = ['login' => 'OctoCat', 'id' => 583231, 'type' => 'User', 'name' => 'The Octocat', 'avatar_url' => null, 'bio' => null, 'location' => null, 'blog' => '', 'company' => null]; + $github = $this->mock(GitHubProvider::class); + $github->shouldReceive('accountByLogin')->with('octocat')->andReturn($account); + Profile::factory()->create(['github_id' => '583231', 'handle' => 'octocat']); + + resolve(CreateGitHubProfile::class)->handle('octocat'); + + expect(Profile::query()->sole()->handle)->toBe('OctoCat'); + Queue::assertNotPushed(LinkUnclaimedProfileTopics::class); +}); + +it('leaves the earlier mentions of a handle to whoever had its page here before', function (): void { + Queue::fake([LinkUnclaimedProfileTopics::class]); + $github = $this->mock(GitHubProvider::class); + $github->shouldReceive('accountByLogin')->with('octocat')->andReturn(['login' => 'octocat', 'id' => 583231, 'type' => 'User', 'name' => 'The Octocat', 'avatar_url' => null, 'bio' => null, 'location' => null, 'blog' => '', 'company' => null]); + $github->shouldReceive('followerIds')->andReturn([]); + $previous = Profile::factory()->create(['github_id' => '1', 'handle' => 'octocat']); + $commit = Commit::factory()->create(['body' => 'Thanks @octocat', 'mentions' => []]); + resolve(CreateCommitTopics::class)->handle($commit, [], ['octocat' => $previous->id]); + + resolve(CreateGitHubProfile::class)->handle('octocat'); + + $this->assertModelMissing($previous); + expect(Profile::query()->where('handle', 'octocat')->sole()->github_id)->toBe('583231') + ->and(developerTopics())->toBe([]); + Queue::assertNotPushed(LinkUnclaimedProfileTopics::class); +}); + +it('links the earlier mentions in the queue', function (): void { + $profile = Profile::factory()->create(['handle' => 'octocat']); + $commit = Commit::factory()->create(['body' => 'Thanks @octocat', 'mentions' => []]); + + dispatch_sync(new LinkUnclaimedProfileTopics($profile)); + + expect(developerTopics())->toBe([$commit->id => $profile->id]); +}); + +it('drops the mentions linked to a developer whose handle someone else took', function (): void { + $previous = Profile::factory()->create(['github_id' => '1', 'handle' => 'octocat']); + $laravel = Organization::factory()->create(['handle' => 'laravel']); + $commit = Commit::factory()->create(['body' => '@octocat @laravel']); + resolve(CreateCommitTopics::class)->handle($commit, ['laravel' => $laravel->id], ['octocat' => $previous->id]); + + resolve(UpdateStaleHandles::class)->handle('octocat', '2'); + + $this->assertModelMissing($previous); + expect(DB::table('commit_topics')->pluck('topic_id')->all())->toBe([$laravel->id]); +}); + +it('drops the mentions linked to them from before they signed up when a user deletes their account', function (): void { + $user = User::factory()->create(); + $other = Profile::factory()->create(); + $commit = Commit::factory()->create(['body' => 'Hi']); + resolve(CreateCommitTopics::class)->handle($commit, [], ['someone' => $user->id, 'other' => $other->id]); + + resolve(DeleteUser::class)->handle($user); + + expect(developerTopics())->toBe([$commit->id => $other->id]); +}); diff --git a/tests/Unit/Models/CommitTest.php b/tests/Unit/Models/CommitTest.php index 17baaae31e..1a09a319b3 100644 --- a/tests/Unit/Models/CommitTest.php +++ b/tests/Unit/Models/CommitTest.php @@ -30,6 +30,7 @@ 'hot_score', 'pasteis_count', 'organization_mentions', + 'developer_mentions', 'body_segments', 'preview_segments', 'is_checking', diff --git a/tests/Unit/Queries/CommitBuilderTest.php b/tests/Unit/Queries/CommitBuilderTest.php index cc14f42633..2ff2fd7eb9 100644 --- a/tests/Unit/Queries/CommitBuilderTest.php +++ b/tests/Unit/Queries/CommitBuilderTest.php @@ -24,9 +24,9 @@ DB::disableQueryLog(); }); -it('loads commits with every column but the embedding, which stays stored, and the organizations they mention', function (): void { +it('loads commits with every column but the embedding, which stays stored, and the organizations and developers they mention', function (): void { $commit = Commit::factory()->create(['embedding' => embeddingVector(0)]); - $columns = [...array_values(array_diff(Schema::getColumnListing('commits'), ['embedding'])), 'organization_mentions']; + $columns = [...array_values(array_diff(Schema::getColumnListing('commits'), ['embedding'])), 'organization_mentions', 'developer_mentions']; expect(array_keys(Commit::query()->findOrFail($commit->id)->getAttributes()))->toBe($columns) ->and(array_keys(Commit::query()->withStarsFor(null)->findOrFail($commit->id)->getAttributes()))->toBe([...$columns, 'stars_count', 'starred'])