From 537ec9c4f6445e2fba079cd2a7cd32fe4bbf9b06 Mon Sep 17 00:00:00 2001 From: WilliamShakesGibson <343627761+WilliamShakesGibson@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:08:43 -0600 Subject: [PATCH 1/4] feat: notify followers when a stream goes live Add per-follow and per-user live notification preferences, fan out a LiveStarted notification through the existing notifications table, and play an optional sound with a polling fallback. Includes focused PHP and TypeScript tests, plus deduplication and replay safeguards. --- app/Actions/CreateExport.php | 28 +- app/Actions/CreateUserFollow.php | 1 + app/Actions/UpdateUserLive.php | 74 +++- app/Actions/UpdateUserLiveNotification.php | 21 + app/Actions/UpdateUserLiveNotifications.php | 28 ++ app/Enums/NotificationType.php | 1 + app/Http/Controllers/UserController.php | 1 + .../UserLiveNotificationController.php | 28 ++ .../UserLiveNotificationsController.php | 21 + app/Http/Middleware/HandleInertiaRequests.php | 19 + .../CreateUserLiveNotificationRequest.php | 30 ++ .../UpdateUserLiveNotificationsRequest.php | 25 ++ app/Models/User.php | 16 +- app/Queries/NotificationBuilder.php | 10 +- app/Queries/NotificationGroupsQuery.php | 2 + database/factories/NotificationFactory.php | 18 + ...20000_add_notify_live_to_follows_table.php | 18 + ...e_notifications_enabled_to_users_table.php | 22 + .../components/live-notifications-setting.tsx | 89 ++++ .../notification-sounds-setting.tsx | 380 ++++++++++++++++++ resources/js/components/remotes-setting.tsx | 143 +------ resources/js/components/user-safety-menu.tsx | 79 +++- .../js/hooks/use-live-notification-sound.ts | 162 ++++++++ resources/js/layouts/app-layout.tsx | 53 ++- resources/js/lib/notification-polling.ts | 28 ++ resources/js/lib/remote-notifications.ts | 64 ++- resources/js/pages/notification/index.tsx | 39 +- resources/js/pages/user-profile/edit.tsx | 6 + resources/js/pages/user/show.tsx | 13 +- resources/js/types/auth.ts | 5 + resources/js/types/notification.ts | 6 + routes/web.php | 10 + .../Controllers/ExportControllerTest.php | 7 +- tests/Feature/LiveNotificationsTest.php | 167 ++++++++ tests/Unit/Enums/NotificationTypeTest.php | 1 + tests/Unit/LiveNotificationPolling.test.ts | 35 ++ tests/Unit/LiveNotificationQueriesTest.php | 65 +++ tests/Unit/LiveNotificationSettings.test.tsx | 249 ++++++++++++ tests/Unit/LiveNotificationSound.test.tsx | 224 +++++++++++ tests/Unit/LiveNotificationUi.test.tsx | 116 ++++++ 40 files changed, 2123 insertions(+), 181 deletions(-) create mode 100644 app/Actions/UpdateUserLiveNotification.php create mode 100644 app/Actions/UpdateUserLiveNotifications.php create mode 100644 app/Http/Controllers/UserLiveNotificationController.php create mode 100644 app/Http/Controllers/UserLiveNotificationsController.php create mode 100644 app/Http/Requests/CreateUserLiveNotificationRequest.php create mode 100644 app/Http/Requests/UpdateUserLiveNotificationsRequest.php create mode 100644 database/migrations/2026_11_15_120000_add_notify_live_to_follows_table.php create mode 100644 database/migrations/2026_11_17_120000_add_live_notifications_enabled_to_users_table.php create mode 100644 resources/js/components/live-notifications-setting.tsx create mode 100644 resources/js/components/notification-sounds-setting.tsx create mode 100644 resources/js/hooks/use-live-notification-sound.ts create mode 100644 resources/js/lib/notification-polling.ts create mode 100644 tests/Feature/LiveNotificationsTest.php create mode 100644 tests/Unit/LiveNotificationPolling.test.ts create mode 100644 tests/Unit/LiveNotificationQueriesTest.php create mode 100644 tests/Unit/LiveNotificationSettings.test.tsx create mode 100644 tests/Unit/LiveNotificationSound.test.tsx create mode 100644 tests/Unit/LiveNotificationUi.test.tsx diff --git a/app/Actions/CreateExport.php b/app/Actions/CreateExport.php index 26ff673e4a..0a28a85354 100644 --- a/app/Actions/CreateExport.php +++ b/app/Actions/CreateExport.php @@ -38,6 +38,7 @@ * @phpstan-type ExportPollVote array{commit_id: string, option: string, created_at: string} * @phpstan-type ExportMessage array{to: string|null, body: string, voice: string|null, created_at: string} * @phpstan-type ExportUser array{handle: string} + * @phpstan-type ExportFollow array{handle: string, notify_live: bool} * @phpstan-type ExportActiveDay array{date: string, web_app: bool, native_mobile_app: bool, lite_mobile_app: bool, mac_app: bool, other_app: bool} * @phpstan-type UserExport array{ * schema_version: int, @@ -49,8 +50,8 @@ * polls: Generator, * poll_votes: Generator, * stars: Generator, - * following: Generator, - * followers: Generator, + * following: Generator, + * followers: Generator, * muting: Generator, * blocking: Generator, * dismissed_suggestions: Generator, @@ -86,7 +87,7 @@ public function handle(User $user): array { return [ - 'schema_version' => 9, + 'schema_version' => 10, 'exported_at' => now()->toIso8601String(), 'profile' => [ 'github_id' => $user->github_id, @@ -110,6 +111,7 @@ public function handle(User $user): array 'pasteis_given_today' => $user->pasteis_given_today, 'pasteis_given_on' => $user->pasteis_given_on?->toDateString(), 'remotes_enabled' => $user->remotes_enabled, + 'live_notifications_enabled' => $user->live_notifications_enabled, 'remotes_from' => $user->remotes_from->value, 'pull_receipts' => $user->pull_receipts, 'push_follows' => $user->push_follows, @@ -133,8 +135,8 @@ public function handle(User $user): array 'polls' => $this->polls($user), 'poll_votes' => $this->pollVotes($user), 'stars' => $this->stars($user), - 'following' => $this->handles($user->following()), - 'followers' => $this->handles($user->followers()), + 'following' => $this->handlesWithLive($user->following()), + 'followers' => $this->handlesWithLive($user->followers()), 'muting' => $this->handles($user->muting()), 'blocking' => $this->handles($user->blocking()), 'dismissed_suggestions' => $this->handles($user->dismissedSuggestions()), @@ -429,6 +431,22 @@ private function handles(BelongsToMany $users): Generator } } + /** + * @param BelongsToMany $users + * @return Generator + */ + private function handlesWithLive(BelongsToMany $users): Generator + { + /** @var LazyCollection $users */ + $users = $users->join('profiles', 'profiles.id', '=', 'users.id')->toBase() + ->select(['users.id', 'profiles.handle', 'follows.notify_live']) + ->lazyById(500, 'users.id', 'id'); + + foreach ($users as $user) { + yield ['handle' => $user->handle, 'notify_live' => (bool) $user->notify_live]; + } + } + /** * @return array */ diff --git a/app/Actions/CreateUserFollow.php b/app/Actions/CreateUserFollow.php index c9f2a82322..34a75e6fdd 100644 --- a/app/Actions/CreateUserFollow.php +++ b/app/Actions/CreateUserFollow.php @@ -26,6 +26,7 @@ public function handle(User $follower, User $followed): void $follower->following()->newPivotStatement()->insertOrIgnore([ 'follower_id' => $follower->id, 'followed_id' => $followed->id, + 'notify_live' => true, 'created_at' => now(), 'updated_at' => now(), ]); diff --git a/app/Actions/UpdateUserLive.php b/app/Actions/UpdateUserLive.php index e44a0eaea7..d139a12522 100644 --- a/app/Actions/UpdateUserLive.php +++ b/app/Actions/UpdateUserLive.php @@ -4,24 +4,80 @@ namespace App\Actions; +use App\Dto\LiveStream; use App\Enums\LivePlatform; +use App\Enums\NotificationType; use App\Enums\UserUpdate; use App\Events\ProfilesUpdated; use App\Events\UsersUpdated; +use App\Models\Notification; use App\Models\User; +use Carbon\CarbonInterface; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Str; final readonly class UpdateUserLive { public function handle(User $user, LivePlatform $platform, string $url, int $hours): void { - $user->update([ - 'live_platform' => $platform, - 'live_url' => $platform->driver()->stream($url)->url, - 'live_ends_at' => now()->addHours($hours), - ]); - - event(new ProfilesUpdated([$user->id], changesLive: true)); - event(new UsersUpdated([$user->id], UserUpdate::Account)); - event(new UsersUpdated($user->followers()->pluck('users.id'), UserUpdate::Live)); + DB::transaction(function () use ($user, $platform, $url, $hours): void { + // Two go-live requests at once must not each fan out, so the previous stream is read from the locked row. + $locked = User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail(); + $wasLive = $locked->liveStream() instanceof LiveStream; + $endsAt = now()->addHours($hours); + + // Update the caller's model as before, so controllers answer with the stream they just saved, but only + // after the lock has decided whether this is a new stream. + $user->update([ + 'live_platform' => $platform, + 'live_url' => $platform->driver()->stream($url)->url, + 'live_ends_at' => $endsAt, + ]); + + event(new ProfilesUpdated([$user->id], changesLive: true)); + event(new UsersUpdated([$user->id], UserUpdate::Account)); + event(new UsersUpdated($user->followers()->pluck('users.id'), UserUpdate::Live)); + + if (! $wasLive) { + $this->notifyFollowers($user, $endsAt); + } + }); + } + + private function notifyFollowers(User $user, CarbonInterface $endsAt): void + { + $followerIds = $user->followers() + ->wherePivot('notify_live', true) + ->where('users.live_notifications_enabled', true) + ->whereNotIn('users.id', $user->mutedBy()->newPivotQuery()->select('muter_id')) + ->whereNotIn('users.id', $user->idsAcrossBlocks()) + ->pluck('users.id') + ->map(fn (mixed $id): string => is_scalar($id) ? (string) $id : '') + ->values() + ->all(); + + if ($followerIds === []) { + return; + } + + $now = now(); + $key = 'live_started:'.$user->id.':'.$endsAt->getTimestamp(); + + $notifications = array_map(fn (string $followerId): array => [ + 'id' => Str::uuid7()->toString(), + 'recipient_id' => $followerId, + 'actor_id' => $user->id, + 'type' => NotificationType::LiveStarted->value, + 'commit_id' => null, + 'key' => $key, + 'created_at' => $now, + 'updated_at' => $now, + ], $followerIds); + + foreach (array_chunk($notifications, 500) as $chunk) { + Notification::query()->insertOrIgnore($chunk); + } + + event(new UsersUpdated($followerIds, UserUpdate::Notifications)); } } diff --git a/app/Actions/UpdateUserLiveNotification.php b/app/Actions/UpdateUserLiveNotification.php new file mode 100644 index 0000000000..5cb8a240c4 --- /dev/null +++ b/app/Actions/UpdateUserLiveNotification.php @@ -0,0 +1,21 @@ +following()->updateExistingPivot($followed->id, [ + 'notify_live' => $notifyLive, + ]); + + event(new UsersUpdated([$follower->id], UserUpdate::Account)); + } +} diff --git a/app/Actions/UpdateUserLiveNotifications.php b/app/Actions/UpdateUserLiveNotifications.php new file mode 100644 index 0000000000..1bf989fffd --- /dev/null +++ b/app/Actions/UpdateUserLiveNotifications.php @@ -0,0 +1,28 @@ +update(['live_notifications_enabled' => $enabled]); + + if (! $enabled) { + $user->notifications() + ->where('type', NotificationType::LiveStarted) + ->whereNull('read_at') + ->update(['read_at' => now()]); + } + + event(new UsersUpdated([$user->id], UserUpdate::Account)); + event(new UsersUpdated([$user->id], UserUpdate::Notifications)); + } +} diff --git a/app/Enums/NotificationType.php b/app/Enums/NotificationType.php index 4f091a3409..b7ebde4aa4 100644 --- a/app/Enums/NotificationType.php +++ b/app/Enums/NotificationType.php @@ -7,6 +7,7 @@ enum NotificationType: string { case Followed = 'followed'; + case LiveStarted = 'live_started'; case Replied = 'replied'; case Mentioned = 'mentioned'; case Approved = 'approved'; diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index e5f1e0c4b5..479cdc0547 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -81,6 +81,7 @@ public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser 'isFollowing' => $relationship(fn (): bool => $currentUser?->isFollowing($user) ?? false), 'followsYou' => $relationship(fn (): bool => $currentUser instanceof User && $user->isFollowing($currentUser)), 'isMuting' => $relationship(fn (): bool => $currentUser?->isMuting($user) ?? false), + 'isNotifyingLive' => $relationship(fn (): bool => $currentUser?->isNotifyingLive($user) ?? false), 'followersYouKnow' => fn (): ?array => $currentUser instanceof User && $currentUser->isNot($user) ? $followersYouKnow->preview($user, $currentUser) : null, diff --git a/app/Http/Controllers/UserLiveNotificationController.php b/app/Http/Controllers/UserLiveNotificationController.php new file mode 100644 index 0000000000..9fb0bf8221 --- /dev/null +++ b/app/Http/Controllers/UserLiveNotificationController.php @@ -0,0 +1,28 @@ +handle($currentUser, $user, true); + + return back(); + } + + public function destroy(CreateUserLiveNotificationRequest $request, #[CurrentUser] User $currentUser, User $user, UpdateUserLiveNotification $action): RedirectResponse + { + $action->handle($currentUser, $user, false); + + return back(); + } +} diff --git a/app/Http/Controllers/UserLiveNotificationsController.php b/app/Http/Controllers/UserLiveNotificationsController.php new file mode 100644 index 0000000000..f0d8ff2fd5 --- /dev/null +++ b/app/Http/Controllers/UserLiveNotificationsController.php @@ -0,0 +1,21 @@ +handle($user, $request->boolean('enabled')); + + return back(); + } +} diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index 65ebb458d9..47feee66b2 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -9,11 +9,13 @@ use App\Enums\EventTheme; use App\Enums\Feature; use App\Enums\Log; +use App\Enums\NotificationType; use App\Enums\RepliesPerPage; use App\Enums\UserUpdate; use App\Http\Requests\ListNotificationsRequest; use App\Http\Resources\ShownStreams; use App\Models\Commit; +use App\Models\Notification; use App\Models\Organization; use App\Models\User; use App\Queries\BioProfilesQuery; @@ -136,6 +138,7 @@ public function share(Request $request): array ->all() : [], UserUpdate::Account), 'isAdmin' => $isAdmin, 'automaticTranslation' => $live(fn (): bool => $user->automatic_translation ?? true, UserUpdate::Account), + 'liveNotificationsEnabled' => $live(fn (): bool => $user instanceof User && $user->live_notifications_enabled, UserUpdate::Account), // The language translations are read in, saved or from the browser, so a change saved elsewhere reaches // the translations already shown. 'translationLanguage' => $live(fn (): string => resolve(CommitTranslations::class)->language(), UserUpdate::Account), @@ -144,6 +147,22 @@ public function share(Request $request): array 'log' => $live(fn (): ?Log => $request->user()?->log, UserUpdate::Account), // Each browser filters notifications its own way, and reloading the count goes through its cookie. 'unreadNotificationsCount' => $live(fn (): int => $user instanceof User ? resolve(NotificationGroupsQuery::class)->unreadCount($user, ListNotificationsRequest::rememberedType($request, $user)) : 0, UserUpdate::Notifications), + // The browser plays the live sound when this changes, so it needs the newest one even once read. + 'latestLiveNotificationId' => $live(function () use ($user): ?string { + if (! $user instanceof User) { + return null; + } + + $id = Notification::query() + ->where('recipient_id', $user->id) + ->where('type', NotificationType::LiveStarted) + ->relevant() + ->latest() + ->latest('id') + ->value('id'); + + return is_string($id) ? $id : null; + }, UserUpdate::Notifications), 'unreadMessagesCount' => $live(fn (): int => $user?->remotes_enabled ? resolve(ConversationsQuery::class)->unreadCount($user) : 0, UserUpdate::Messages, UserUpdate::Inbox), 'remotes' => $live(fn (): ?array => $user?->remotes_enabled ? [ 'from' => $user->remotes_from, diff --git a/app/Http/Requests/CreateUserLiveNotificationRequest.php b/app/Http/Requests/CreateUserLiveNotificationRequest.php new file mode 100644 index 0000000000..57ae0e4f22 --- /dev/null +++ b/app/Http/Requests/CreateUserLiveNotificationRequest.php @@ -0,0 +1,30 @@ +user(); + assert($follower instanceof User); + + $followed = $this->route('user'); + assert($followed instanceof User); + + return $follower->isNot($followed) && $follower->isFollowing($followed); + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Http/Requests/UpdateUserLiveNotificationsRequest.php b/app/Http/Requests/UpdateUserLiveNotificationsRequest.php new file mode 100644 index 0000000000..096486be6a --- /dev/null +++ b/app/Http/Requests/UpdateUserLiveNotificationsRequest.php @@ -0,0 +1,25 @@ +> + */ + public function rules(): array + { + return [ + 'enabled' => ['required', 'boolean'], + ]; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 30b5b8716f..a6d58157a2 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -44,6 +44,7 @@ * @property-read string|null $lane_color * @property-read bool $pasteis_mode * @property-read bool $remotes_enabled + * @property-read bool $live_notifications_enabled * @property-read RemotesFrom $remotes_from * @property-read bool $pull_receipts * @property-read bool $push_follows @@ -106,6 +107,7 @@ 'lane_color', 'pasteis_mode', 'remotes_enabled', + 'live_notifications_enabled', 'pushSubscriptions', 'remotes_from', 'pull_receipts', @@ -166,6 +168,7 @@ final class User extends Authenticatable 'show_local_time' => false, 'pasteis_mode' => false, 'remotes_enabled' => true, + 'live_notifications_enabled' => true, 'remotes_from' => RemotesFrom::Following->value, 'pull_receipts' => true, 'push_follows' => true, @@ -209,6 +212,7 @@ public function casts(): array 'lane_color' => 'string', 'pasteis_mode' => 'boolean', 'remotes_enabled' => 'boolean', + 'live_notifications_enabled' => 'boolean', 'remotes_from' => RemotesFrom::class, 'pull_receipts' => 'boolean', 'push_follows' => 'boolean', @@ -413,7 +417,7 @@ public function hasStarred(Commit $commit): bool */ public function following(): BelongsToMany { - return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withTimestamps(); + return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withPivot('notify_live')->withTimestamps(); } /** @@ -421,7 +425,7 @@ public function following(): BelongsToMany */ public function followers(): BelongsToMany { - return $this->belongsToMany(self::class, 'follows', 'followed_id', 'follower_id')->withTimestamps(); + return $this->belongsToMany(self::class, 'follows', 'followed_id', 'follower_id')->withPivot('notify_live')->withTimestamps(); } /** @@ -566,6 +570,14 @@ public function isFollowing(self $user): bool return $this->following()->newPivotQuery()->where('followed_id', $user->id)->exists(); } + public function isNotifyingLive(self $user): bool + { + return $this->following()->newPivotQuery() + ->where('followed_id', $user->id) + ->where('notify_live', true) + ->exists(); + } + public function isMuting(self $user): bool { return $this->muting()->newPivotQuery()->where('muted_id', $user->id)->exists(); diff --git a/app/Queries/NotificationBuilder.php b/app/Queries/NotificationBuilder.php index 52404c1171..af8714e476 100644 --- a/app/Queries/NotificationBuilder.php +++ b/app/Queries/NotificationBuilder.php @@ -48,7 +48,15 @@ public function relevant(): self ->whereColumn('organization_members.organization_id', 'notifications.organization_id') ->whereColumn('organization_members.user_id', 'notifications.recipient_id'))) ->offset(0))) - ->orWhereIn('type', [NotificationType::LeveledUp, NotificationType::TimedOut])) + ->orWhereIn('type', [NotificationType::LeveledUp, NotificationType::TimedOut]) + // A stream the recipient turned off, or a muted or blocked streamer, is no longer their business. + ->orWhere(fn (Builder $query): Builder => $query + ->where('type', NotificationType::LiveStarted) + ->whereExists(fn (QueryBuilder $users): QueryBuilder => $users + ->from('users') + ->whereColumn('users.id', 'notifications.recipient_id') + ->where('users.live_notifications_enabled', true) + ->offset(0)))) ->withoutSilencedActors(); } diff --git a/app/Queries/NotificationGroupsQuery.php b/app/Queries/NotificationGroupsQuery.php index bda5e2b45a..10e8d9ef04 100644 --- a/app/Queries/NotificationGroupsQuery.php +++ b/app/Queries/NotificationGroupsQuery.php @@ -186,11 +186,13 @@ private function group(NotificationBuilder $visible, string $type = 'all', ?Noti CASE WHEN visible.type = 'starred' THEN 'starred' WHEN visible.type = 'replied' THEN 'replied' WHEN visible.type = 'timed_out' THEN 'timed_out' + WHEN visible.type = 'live_started' THEN 'live' WHEN visible.organization_id IS NOT NULL THEN CONCAT('organization:', visible.organization_id) ELSE 'activity' END AS topic_kind, CASE WHEN visible.type = 'followed' THEN visible.recipient_id WHEN visible.type = 'starred' THEN visible.commit_id WHEN visible.type = 'replied' THEN visible.id + WHEN visible.type = 'live_started' THEN visible.id ELSE COALESCE(ancestry.id, threads.id, visible.id) END AS topic_id, CASE WHEN visible.type = 'followed' THEN DATE(visible.created_at) END AS topic_day FROM visible LEFT JOIN threads ON threads.notification_id = visible.id diff --git a/database/factories/NotificationFactory.php b/database/factories/NotificationFactory.php index 9c0af8a032..2d57006c8d 100644 --- a/database/factories/NotificationFactory.php +++ b/database/factories/NotificationFactory.php @@ -9,6 +9,7 @@ use App\Models\Notification; use App\Models\User; use App\Models\UserTimeout; +use Carbon\CarbonInterface; use Illuminate\Database\Eloquent\Factories\Factory; /** @@ -39,6 +40,8 @@ public function configure(): self NotificationType::Starred => 'starred:'.$notification->commit_id.':'.$notification->actor_id, NotificationType::LeveledUp => 'leveled_up:'.$notification->level, NotificationType::TimedOut => 'timed_out:'.$notification->timeout_id, + // A live key carries the stream's end, which only the state knows: never overwrite it. + NotificationType::LiveStarted => $notification->key ?? 'live_started:'.$notification->actor_id.':'.now()->getTimestamp(), default => $notification->type->value.':'.($notification->commit_id ?? $notification->actor_id), }, ])) @@ -78,6 +81,21 @@ public function timedOut(UserTimeout $timeout): self ]); } + /** + * A stream from the actor that ends at the given time, with the key production uses for it. + */ + public function liveStarted(User $streamer, ?CarbonInterface $endsAt = null): self + { + $endsAt ??= now()->addHours(2); + + return $this->state(fn (array $attributes): array => [ + 'actor_id' => $streamer->id, + 'type' => NotificationType::LiveStarted, + 'commit_id' => null, + 'key' => 'live_started:'.$streamer->id.':'.$endsAt->getTimestamp(), + ]); + } + /** * An approved reply from the actor to one of the recipient's commits, or to the given one. */ diff --git a/database/migrations/2026_11_15_120000_add_notify_live_to_follows_table.php b/database/migrations/2026_11_15_120000_add_notify_live_to_follows_table.php new file mode 100644 index 0000000000..0dee7f18b0 --- /dev/null +++ b/database/migrations/2026_11_15_120000_add_notify_live_to_follows_table.php @@ -0,0 +1,18 @@ +boolean('notify_live')->default(true)->after('followed_id'); + }); + } +}; diff --git a/database/migrations/2026_11_17_120000_add_live_notifications_enabled_to_users_table.php b/database/migrations/2026_11_17_120000_add_live_notifications_enabled_to_users_table.php new file mode 100644 index 0000000000..20abde94cd --- /dev/null +++ b/database/migrations/2026_11_17_120000_add_live_notifications_enabled_to_users_table.php @@ -0,0 +1,22 @@ +boolean('live_notifications_enabled')->default(true)->after('remotes_enabled'); + }); + } +}; diff --git a/resources/js/components/live-notifications-setting.tsx b/resources/js/components/live-notifications-setting.tsx new file mode 100644 index 0000000000..6c861af76a --- /dev/null +++ b/resources/js/components/live-notifications-setting.tsx @@ -0,0 +1,89 @@ +import { router, usePage } from '@inertiajs/react'; +import { toast } from 'sonner'; +import { update } from '@/actions/App/Http/Controllers/UserLiveNotificationsController'; +import { usePicked } from '@/hooks/use-picked'; +import { cn } from '@/lib/utils'; + +export function LiveNotificationsSetting() { + const { auth } = usePage().props; + const { picked, pick } = usePicked(); + const processing = picked !== null; + const enabled = picked ?? auth.liveNotificationsEnabled; + + const toggle = () => { + if (processing) { + return; + } + + const next = !enabled; + const finish = pick(next); + + router.put( + update.url(), + { enabled: next }, + { + preserveScroll: true, + only: ['auth'], + onSuccess: () => { + finish(); + router.flushAll(); + }, + onError: () => { + finish(); + toast.error( + 'Could not save live notifications. Please try again.', + ); + }, + onCancel: finish, + }, + ); + }; + + return ( +
+
+
+

+ Live notifications +

+

+ Show in your notifications feed when someone you follow + goes live. +

+

+ When off, live alerts are hidden from your feed and + their sound is paused. Your per-profile live choices are + kept. +

+
+ +
+
+ ); +} diff --git a/resources/js/components/notification-sounds-setting.tsx b/resources/js/components/notification-sounds-setting.tsx new file mode 100644 index 0000000000..6741c82fa1 --- /dev/null +++ b/resources/js/components/notification-sounds-setting.tsx @@ -0,0 +1,380 @@ +import { usePage } from '@inertiajs/react'; +import { useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { toast } from 'sonner'; +import { RemoteSoundIcon } from '@/components/remote-sound-icon'; +import { Button } from '@/components/ui/button'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { useRemoteAlertsEnabled } from '@/hooks/use-chat'; +import type { + RemoteAlertChannel, + RemoteSound, +} from '@/lib/remote-notifications'; +import { + liveNotificationSound, + liveNotificationSoundChosen, + REMOTE_SOUNDS, + remoteSound, + remoteSoundSource, + setLiveNotificationSound, + setRemoteAlerts, + setRemoteSound, + subscribeRemoteAlerts, +} from '@/lib/remote-notifications'; +import { cn } from '@/lib/utils'; + +function SoundSwitch({ + checked, + disabled, + onClick, + testId, + labelId, + descriptionId, +}: { + checked: boolean; + disabled: boolean; + onClick: () => void; + testId: string; + labelId: string; + descriptionId: string; +}) { + return ( + + ); +} + +export function NotificationSoundsSetting() { + const { auth } = usePage().props; + const userId = auth.user?.id ?? null; + const remotesEnabled = auth.remotes !== null; + const liveNotificationsEnabled = auth.liveNotificationsEnabled; + const soundsEnabled = useRemoteAlertsEnabled(userId, 'sound'); + const remoteSoundsEnabled = useRemoteAlertsEnabled(userId, 'message-sound'); + const liveSoundsEnabled = useRemoteAlertsEnabled(userId, 'live-sound'); + const [saving, setSaving] = useState(false); + const remoteSoundSelection = useSyncExternalStore( + subscribeRemoteAlerts, + () => (userId === null ? 'msn' : remoteSound(userId)), + () => 'msn', + ); + const liveSoundSelection = useSyncExternalStore( + subscribeRemoteAlerts, + () => (userId === null ? 'msn' : liveNotificationSound(userId)), + () => 'msn', + ); + const liveSoundChosen = useSyncExternalStore( + subscribeRemoteAlerts, + () => userId !== null && liveNotificationSoundChosen(userId), + () => false, + ); + const preview = useRef(null); + + useEffect(() => () => preview.current?.pause(), []); + + const saveSound = async ( + channel: Extract< + RemoteAlertChannel, + 'sound' | 'message-sound' | 'live-sound' + >, + enabled: boolean, + label: string, + ) => { + if (auth.user === null || saving) return; + + setSaving(true); + + try { + if (!(await setRemoteAlerts(auth.user.id, enabled, channel))) { + toast.error( + `Could not save ${label}. Check your browser’s storage settings.`, + ); + } + } finally { + setSaving(false); + } + }; + + const previewSound = (selected: RemoteSound) => { + preview.current?.pause(); + preview.current ??= new Audio(); + preview.current.src = remoteSoundSource(selected); + preview.current.currentTime = 0; + void preview.current + .play() + .catch(() => + toast.error('Could not play the sound. Please try again.'), + ); + }; + + return ( +
+
+
+

+ Notification sounds +

+

+ Play sounds for remote messages and live alerts while + the site is open. +

+

+ Sound choices are saved in this browser. +

+
+ + void saveSound( + 'sound', + !soundsEnabled, + 'notification sounds', + ) + } + testId="notification-sounds-setting" + labelId="notification-sounds-label" + descriptionId="notification-sounds-description" + /> +
+ +
+
+

+ Remote message sound +

+

+ Play a sound for new remote messages. +

+ {!remotesEnabled && ( +

+ Remote messages are off, so this sound is paused. +

+ )} +
+ + void saveSound( + 'message-sound', + !remoteSoundsEnabled, + 'remote message sound', + ) + } + testId="remote-message-sound-setting" + labelId="remote-message-sound-label" + descriptionId="remote-message-sound-description" + /> +
+
+
+ + +
+
+ +
+
+

+ Live alert sound +

+

+ Play a sound when someone you follow goes live. +

+ {!liveSoundChosen && ( +

+ Until you change it, this follows the remote message + sound. +

+ )} + {!liveNotificationsEnabled && ( +

+ Live notifications are off, so this sound is paused. +

+ )} +
+ + void saveSound( + 'live-sound', + !liveSoundsEnabled, + 'live alert sound', + ) + } + testId="live-alert-sound-setting" + labelId="live-alert-sound-label" + descriptionId="live-alert-sound-description" + /> +
+
+
+ + +
+
+
+ ); +} diff --git a/resources/js/components/remotes-setting.tsx b/resources/js/components/remotes-setting.tsx index 3c45115fdc..308af42e0b 100644 --- a/resources/js/components/remotes-setting.tsx +++ b/resources/js/components/remotes-setting.tsx @@ -1,33 +1,14 @@ import { router, usePage } from '@inertiajs/react'; -import { useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { useState } from 'react'; import { toast } from 'sonner'; import { update } from '@/actions/App/Http/Controllers/UserRemotesController'; -import { RemoteSoundIcon } from '@/components/remote-sound-icon'; -import { Button } from '@/components/ui/button'; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@/components/ui/select'; import { useRemoteAlertsEnabled, useRemoteNotificationSupport, } from '@/hooks/use-chat'; import { usePicked } from '@/hooks/use-picked'; -import type { - RemoteAlertChannel, - RemoteSound, -} from '@/lib/remote-notifications'; -import { - REMOTE_SOUNDS, - remoteSound, - remoteSoundSource, - setRemoteAlerts, - setRemoteSound, - subscribeRemoteAlerts, -} from '@/lib/remote-notifications'; +import type { RemoteAlertChannel } from '@/lib/remote-notifications'; +import { setRemoteAlerts } from '@/lib/remote-notifications'; import { RemotePushValidationError } from '@/lib/remote-push'; import { cn } from '@/lib/utils'; @@ -40,25 +21,19 @@ export function RemotesSetting() { const processing = picked !== null; const enabled = picked ?? auth.remotes !== null; const alertsEnabled = useRemoteAlertsEnabled(auth.user?.id ?? null); - const soundEnabled = useRemoteAlertsEnabled(auth.user?.id ?? null, 'sound'); const supported = useRemoteNotificationSupport(); const offsiteEnabled = useRemoteAlertsEnabled( auth.user?.id ?? null, 'offsite', ); const [savingAlerts, setSavingAlerts] = useState(false); - const selectedSound = useSyncExternalStore( - subscribeRemoteAlerts, - () => (auth.user === null ? 'msn' : remoteSound(auth.user.id)), - () => 'msn', - ); - const preview = useRef(null); - - useEffect(() => () => preview.current?.pause(), []); const saveAlerts = ( enabled: boolean, - channel: RemoteAlertChannel = 'notifications', + channel: Extract< + RemoteAlertChannel, + 'notifications' | 'offsite' + > = 'notifications', ) => { if (auth.user === null || savingAlerts) return; setSavingAlerts(true); @@ -66,9 +41,7 @@ export function RemotesSetting() { .then((saved) => { if (!saved) toast.error( - channel === 'sound' - ? 'Could not save notification sound. Check your browser’s storage settings.' - : 'Could not save notifications. Check your browser’s site permissions and storage settings.', + 'Could not save notifications. Check your browser’s site permissions and storage settings.', ); }) .catch((error: unknown) => @@ -227,106 +200,6 @@ export function RemotesSetting() { /> -
-
-

- Notification sound -

-

- Play a sound for new messages while the site is open. -

-
- -
-
-
- - -
-

- Saved in this browser. -

-
); } diff --git a/resources/js/components/user-safety-menu.tsx b/resources/js/components/user-safety-menu.tsx index 14d123e2c9..3609ed3dff 100644 --- a/resources/js/components/user-safety-menu.tsx +++ b/resources/js/components/user-safety-menu.tsx @@ -1,9 +1,18 @@ import type { VisitOptions } from '@inertiajs/core'; -import { Link, router } from '@inertiajs/react'; -import { Ban, Ellipsis, MessagesSquare, Volume2, VolumeX } from 'lucide-react'; -import { useState } from 'react'; +import { Link, router, usePage } from '@inertiajs/react'; +import { + Ban, + Ellipsis, + MessagesSquare, + Radio, + RadioOff, + Volume2, + VolumeX, +} from 'lucide-react'; +import { useEffect, useState } from 'react'; import ConversationController from '@/actions/App/Http/Controllers/ConversationController'; import UserBlockController from '@/actions/App/Http/Controllers/UserBlockController'; +import UserLiveNotificationController from '@/actions/App/Http/Controllers/UserLiveNotificationController'; import UserMuteController from '@/actions/App/Http/Controllers/UserMuteController'; import { rememberBlock } from '@/components/follow-button'; import { clearMentionSuggestionsCache } from '@/components/mention-textarea'; @@ -23,7 +32,7 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; -import { useSharedState } from '@/hooks/use-shared-state'; +import { refreshSharedState, useSharedState } from '@/hooks/use-shared-state'; import { cn } from '@/lib/utils'; import type { User } from '@/types'; @@ -38,6 +47,8 @@ export function UserSafetyMenu({ user, isMuting: initialIsMuting, isBlocking, + isFollowing = false, + isNotifyingLive: initialIsNotifyingLive = true, canPush = false, className, onOpenChange, @@ -46,15 +57,32 @@ export function UserSafetyMenu({ user: Pick; isMuting: boolean; isBlocking: boolean; + isFollowing?: boolean; + isNotifyingLive?: boolean; canPush?: boolean; className?: string; onOpenChange?: (isOpen: boolean) => void; onBlockChange?: () => void; }) { + const { auth } = usePage().props; + const liveNotificationsEnabled = auth.liveNotificationsEnabled; const [isMenuOpen, setIsMenuOpen] = useState(false); const [isConfirmingBlock, setIsConfirmingBlock] = useState(false); const [isSaving, setIsSaving] = useState(false); const [isMuting, setIsMuting] = useIsMuting(user, initialIsMuting); + const notifyLiveKey = `is_notifying_live:${user.id}`; + const [isNotifyingLive, setIsNotifyingLive] = useSharedState( + notifyLiveKey, + isFollowing ? initialIsNotifyingLive : true, + ); + + useEffect(() => { + refreshSharedState( + new Map([ + [notifyLiveKey, isFollowing ? initialIsNotifyingLive : true], + ]), + ); + }, [initialIsNotifyingLive, isFollowing, notifyLiveKey]); const changeOpen = (menu: boolean, dialog: boolean) => { setIsMenuOpen(menu); @@ -102,6 +130,37 @@ export function UserSafetyMenu({ ); }; + const toggleLiveNotification = () => { + const next = !isNotifyingLive; + const rollBack = () => { + setIsNotifyingLive(isNotifyingLive); + setIsSaving(false); + }; + + router.visit( + next + ? UserLiveNotificationController.store(user) + : UserLiveNotificationController.destroy(user), + { + preserveScroll: true, + preserveState: true, + only: ['isNotifyingLive'], + onStart: () => { + setIsSaving(true); + setIsNotifyingLive(next); + }, + onSuccess: () => { + setIsSaving(false); + changeOpen(false, false); + }, + onError: rollBack, + onCancel: rollBack, + onNetworkError: rollBack, + onHttpException: rollBack, + }, + ); + }; + return ( <> )} + {isFollowing && !isMuting && liveNotificationsEnabled && ( + + {isNotifyingLive ? : } + {isNotifyingLive + ? 'Turn off Live notify' + : 'Notify when Live'} + + )} {isMuting ? : } {isMuting diff --git a/resources/js/hooks/use-live-notification-sound.ts b/resources/js/hooks/use-live-notification-sound.ts new file mode 100644 index 0000000000..f010971e2f --- /dev/null +++ b/resources/js/hooks/use-live-notification-sound.ts @@ -0,0 +1,162 @@ +import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'; +import { + liveNotificationSound, + remoteAlertsEnabled, + remoteSoundSource, + subscribeRemoteAlerts, +} from '@/lib/remote-notifications'; +import type { RemoteSound } from '@/lib/remote-notifications'; +import { readStorage, writeStorage } from '@/lib/storage'; + +/** + * Plays the live alert once when the newest live notification changes. The first ID is only a baseline, so opening the + * site never replays news from while the reader was away. + */ +export function useLiveNotificationSound( + latestNotificationId: string | null, + userId: string | null, + liveNotificationsEnabled: boolean, +): void { + const soundEnabled = useSyncExternalStore( + subscribeRemoteAlerts, + () => + userId !== null && + liveNotificationsEnabled && + remoteAlertsEnabled(userId, 'live-sound'), + () => false, + ); + const selectedSound = useSyncExternalStore( + subscribeRemoteAlerts, + () => (userId === null ? 'msn' : liveNotificationSound(userId)), + () => 'msn', + ); + const seen = useRef({ + userId, + notificationId: latestNotificationId, + armed: soundEnabled, + }); + const pending = useRef(null); + const audio = useRef(null); + + const play = useCallback(async () => { + const id = pending.current; + + if (id === null || userId === null || !soundEnabled) { + return; + } + + // One key per reader: a later alert replaces it, so the store never grows with every notification. + const playedKey = `live-alert-played:${userId}`; + const attempt = async () => { + if (pending.current !== id) { + return; + } + + if (readStorage(playedKey) === id) { + pending.current = null; + + return; + } + + const element = (audio.current ??= new Audio()); + element.src = remoteSoundSource(selectedSound); + element.currentTime = 0; + element.muted = false; + + try { + await element.play(); + } catch { + // Autoplay is still blocked; keep the alert pending for the next gesture. + return; + } + + pending.current = null; + writeStorage(playedKey, id); + }; + + try { + if (navigator.locks) { + await navigator.locks.request( + `live-alert-sound:${userId}`, + attempt, + ); + } else { + await attempt(); + } + } catch { + // Locks or storage may be restricted; the alert stays pending for another attempt. + } + }, [selectedSound, soundEnabled, userId]); + + useEffect(() => { + const previous = seen.current; + seen.current = { + userId, + notificationId: latestNotificationId, + armed: soundEnabled, + }; + + if (userId === null || previous.userId !== userId) { + pending.current = null; + + return; + } + + if (!soundEnabled || latestNotificationId === null) { + pending.current = null; + + return; + } + + // A quiet browser, including one that lost the ID because live alerts were off, starts from this alert. + if ( + !previous.armed || + previous.notificationId === latestNotificationId + ) { + return; + } + + pending.current = latestNotificationId; + void play(); + }, [latestNotificationId, play, soundEnabled, userId]); + + useEffect(() => { + if (!soundEnabled) { + return; + } + + function detach() { + window.removeEventListener('pointerdown', unlock); + window.removeEventListener('keydown', unlock); + } + + // Browsers only allow playback after an interaction, so unlock the audio quietly on the first one. + function unlock() { + const element = (audio.current ??= new Audio()); + element.muted = true; + void element + .play() + .then(async () => { + element.pause(); + element.currentTime = 0; + element.muted = false; + + if (pending.current !== null) { + await play(); + } + + if (pending.current === null) { + detach(); + } + }) + .catch(() => { + element.muted = false; + }); + } + + window.addEventListener('pointerdown', unlock); + window.addEventListener('keydown', unlock); + + return detach; + }, [play, soundEnabled]); +} diff --git a/resources/js/layouts/app-layout.tsx b/resources/js/layouts/app-layout.tsx index e0af24a906..4e6fb11b0f 100644 --- a/resources/js/layouts/app-layout.tsx +++ b/resources/js/layouts/app-layout.tsx @@ -1,5 +1,5 @@ import { Head, usePage, usePoll } from '@inertiajs/react'; -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useState, useSyncExternalStore } from 'react'; import { AppAside } from '@/components/app-aside'; import { AppNav, @@ -36,6 +36,7 @@ import { usePageDeletion } from '@/hooks/use-deleted-resources'; import { useFaviconDot } from '@/hooks/use-favicon-dot'; import { useFixedPage } from '@/hooks/use-fixed-page'; import { useKeyboardShortcuts } from '@/hooks/use-keyboard-shortcuts'; +import { useLiveNotificationSound } from '@/hooks/use-live-notification-sound'; import { useLiveStream } from '@/hooks/use-live-stream'; import { useNavOpen } from '@/hooks/use-nav-open'; import { useIsListening } from '@/hooks/use-realtime'; @@ -44,7 +45,15 @@ import { signIn } from '@/lib/auth'; import { backgroundPollOptions } from '@/lib/background-poll'; import { isPageGone } from '@/lib/deleted-resources'; import type { IssueKind } from '@/lib/issue-commands'; +import { + liveNotificationPollInterval, + shouldPollLiveNotifications, +} from '@/lib/notification-polling'; import { userChannel } from '@/lib/realtime'; +import { + remoteAlertsEnabled, + subscribeRemoteAlerts, +} from '@/lib/remote-notifications'; import type { SearchAction } from '@/lib/search-actions'; import { cn } from '@/lib/utils'; import type { AppLayoutProps } from '@/types'; @@ -110,13 +119,30 @@ export default function AppLayout({ children }: AppLayoutProps) { useTabSlide(); const unreadMessages = useUnreadMessages(); useFixedPage(isMessages); - useRemoteAlerts(auth.remotes !== null ? (auth.user?.id ?? null) : null); - useRemoteUpdates(auth.remotes !== null ? (auth.user?.id ?? null) : null); + const userId = auth.user?.id ?? null; + useRemoteAlerts(auth.remotes !== null ? userId : null); + useRemoteUpdates(auth.remotes !== null ? userId : null); + useLiveNotificationSound( + auth.latestLiveNotificationId ?? null, + userId, + auth.liveNotificationsEnabled, + ); + const liveSoundEnabled = useSyncExternalStore( + subscribeRemoteAlerts, + () => userId !== null && remoteAlertsEnabled(userId, 'live-sound'), + () => false, + ); useFaviconDot(auth.unreadNotificationsCount + unreadMessages > 0); const isOwnStreamLive = useLiveStream(auth.user) !== null; const isHearingCounts = useIsListening( auth.user === null ? null : userChannel(auth.user.id), ); + const shouldPollLive = shouldPollLiveNotifications({ + signedIn: auth.user !== null, + liveNotificationsEnabled: auth.liveNotificationsEnabled, + liveSoundEnabled, + isHearingCounts, + }); return ( <> @@ -135,6 +161,11 @@ export default function AppLayout({ children }: AppLayoutProps) { onNotFound={markPageDeleted} /> )} + {deletedPage === null && shouldPollLive && ( + + )}
void>(); const preferenceKey = (userId: string, channel: RemoteAlertChannel) => `remote-alerts:${userId}:${channel}`; -export function remoteSound(userId: string): RemoteSound { - const saved = readStorage(`remote-sound:${userId}`); +function savedSound(key: string, fallback: RemoteSound): RemoteSound { + const saved = readStorage(key); + + return Object.hasOwn(REMOTE_SOUNDS, saved) + ? (saved as RemoteSound) + : fallback; +} - return Object.hasOwn(REMOTE_SOUNDS, saved) ? (saved as RemoteSound) : 'msn'; +export function remoteSound(userId: string): RemoteSound { + return savedSound(`remote-sound:${userId}`, 'msn'); } export function setRemoteSound(userId: string, sound: RemoteSound): boolean { @@ -34,6 +45,27 @@ export function setRemoteSound(userId: string, sound: RemoteSound): boolean { return readStorage(`remote-sound:${userId}`) === sound; } +export function liveNotificationSound(userId: string): RemoteSound { + return savedSound(`live-notification-sound:${userId}`, remoteSound(userId)); +} + +export function liveNotificationSoundChosen(userId: string): boolean { + return Object.hasOwn( + REMOTE_SOUNDS, + readStorage(`live-notification-sound:${userId}`), + ); +} + +export function setLiveNotificationSound( + userId: string, + sound: RemoteSound, +): boolean { + writeStorage(`live-notification-sound:${userId}`, sound); + listeners.forEach((listener) => listener()); + + return readStorage(`live-notification-sound:${userId}`) === sound; +} + export function remoteSoundSource(sound: RemoteSound): string { return REMOTE_SOUNDS[sound].source; } @@ -44,10 +76,22 @@ export function remoteAlertsEnabled( ): boolean { if (channel === 'offsite') return remotePushOptedIn(userId); - return ( - (readStorage(preferenceKey(userId, channel)) || - readStorage(`remote-alerts:${userId}`)) !== 'off' - ); + const isSoundChild = + channel === 'message-sound' || channel === 'live-sound'; + + if (isSoundChild && !remoteAlertsEnabled(userId, 'sound')) { + return false; + } + + const saved = readStorage(preferenceKey(userId, channel)); + + if (channel === 'live-sound' && saved !== 'on' && saved !== 'off') { + return remoteAlertsEnabled(userId, 'message-sound'); + } + + return isSoundChild + ? saved !== 'off' + : (saved || readStorage(`remote-alerts:${userId}`)) !== 'off'; } export function remoteNotificationsSupported(): boolean { @@ -116,7 +160,7 @@ let pingedAt = 0; */ export function playPing(userId: string): void { if ( - !remoteAlertsEnabled(userId, 'sound') || + !remoteAlertsEnabled(userId, 'message-sound') || Date.now() - pingedAt < 2_000 ) { return; @@ -275,7 +319,7 @@ export function createRemoteAlerts( const showBanner = remoteAlertsEnabled(userId, 'offsite') && remoteNotificationsAllowed(); - const playSound = remoteAlertsEnabled(userId, 'sound'); + const playSound = remoteAlertsEnabled(userId, 'message-sound'); if (incoming === undefined) { return; diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index 1428874df4..c45430b61f 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -18,6 +18,7 @@ import { Hourglass, MessageSquareReply, Quote, + Radio, Star, UserPlus, X, @@ -87,7 +88,7 @@ const filterOptions: { { type: 'all', label: 'All', - empty: 'Nothing here yet. Follows, stars, replies, quotes, mentions, level-ups, and moderation updates for your commits will show up here.', + empty: 'Nothing here yet. Follows, live alerts, stars, replies, quotes, mentions, level-ups, and moderation updates for your commits will show up here.', }, { type: 'replies', @@ -735,6 +736,10 @@ function groupNoun(notification: NotificationGroup): string { return 'followers'; } + if (notification.type === 'live_started') { + return 'live alerts'; + } + if (notification.type === 'starred') { return 'stars'; } @@ -1144,6 +1149,10 @@ export function NotificationContent({ const { user } = useUser(); const actorRef = useRef(null); const { actor } = notification; + const liveUrl = + notification.type === 'live_started' && actor.type === 'user' + ? (actor.live?.url ?? null) + : null; const actors = summary && 'actors' in notification ? notification.actors : [actor]; const actorsCount = @@ -1178,7 +1187,8 @@ export function NotificationContent({ const isImageOnly = starredImages.length > 0 && notification.commit?.body_segments.length === 0; - const isActorsCommit = + const isActorActivity = + notification.type === 'live_started' || notification.type === 'replied' || notification.type === 'quoted' || notification.type === 'mentioned' || @@ -1186,6 +1196,7 @@ export function NotificationContent({ const level = notification.type === 'leveled_up' ? notification : null; const Icon = { followed: UserPlus, + live_started: Radio, leveled_up: ChevronsUp, replied: MessageSquareReply, quoted: Quote, @@ -1208,6 +1219,7 @@ export function NotificationContent({ ); const href = notification.type === 'followed' || + notification.type === 'live_started' || notification.type === 'timed_out' || notification.type === 'leveled_up' || (!summary && notification.type === 'starred') @@ -1232,6 +1244,7 @@ export function NotificationContent({ const whose = organization ? `@${organization.handle}'s` : 'your'; const action = { followed: 'followed you', + live_started: 'went live', replied: `replied to ${whose} commit`, quoted: `quoted ${whose} commit`, starred: isImageOnly @@ -1248,6 +1261,7 @@ export function NotificationContent({ }[notification.type]; const excerpt = notification.type === 'followed' || + notification.type === 'live_started' || isImageOnly ? null : notification.type === 'leveled_up' ? (

{notification.rank_description} @@ -1294,7 +1308,7 @@ export function NotificationContent({

); - if (!summary && isActorsCommit) { + if (!summary && isActorActivity) { return (
); - const rowLink = ( + const rowLink = liveUrl ? ( + + {action} + + ) : (
- {isActorsCommit ? ( + {isActorActivity ? ( <>
{isNew && ( diff --git a/resources/js/pages/user-profile/edit.tsx b/resources/js/pages/user-profile/edit.tsx index 13647835eb..57322e5a54 100644 --- a/resources/js/pages/user-profile/edit.tsx +++ b/resources/js/pages/user-profile/edit.tsx @@ -7,6 +7,8 @@ import DeleteUser from '@/components/delete-user'; import { GitHubProfile } from '@/components/github-profile'; import Heading from '@/components/heading'; import LanePicker from '@/components/lane-picker'; +import { LiveNotificationsSetting } from '@/components/live-notifications-setting'; +import { NotificationSoundsSetting } from '@/components/notification-sounds-setting'; import { PasteisModeSetting } from '@/components/pasteis-mode-setting'; import { RemotesSetting } from '@/components/remotes-setting'; import TimezonePicker from '@/components/timezone-picker'; @@ -135,6 +137,10 @@ export default function Edit({ + + + + )} {canPush && ( @@ -343,7 +347,12 @@ export default function Show({ isFollowing={isFollowing} followsYou={followsYou} className="min-w-28" - only={['auth', 'user', 'isFollowing']} + only={[ + 'auth', + 'user', + 'isFollowing', + 'isNotifyingLive', + ]} /> )} diff --git a/resources/js/types/auth.ts b/resources/js/types/auth.ts index 403424de26..fdbb91f145 100644 --- a/resources/js/types/auth.ts +++ b/resources/js/types/auth.ts @@ -53,6 +53,7 @@ export type Auth = { organizations: OrganizationAuthor[]; isAdmin: boolean; automaticTranslation: boolean; + liveNotificationsEnabled: boolean; /** * The language the reader reads translations in, saved or from the browser. */ @@ -61,6 +62,10 @@ export type Auth = { termsToAccept: string | null; log: Log | null; unreadNotificationsCount: number; + /** + * The newest live-start notification, which a page hears about to play the chosen alert sound. + */ + latestLiveNotificationId: string | null; unreadMessagesCount: number; remotes: { from: RemotesFrom; diff --git a/resources/js/types/notification.ts b/resources/js/types/notification.ts index 8a7a253337..bbe768d27d 100644 --- a/resources/js/types/notification.ts +++ b/resources/js/types/notification.ts @@ -41,6 +41,12 @@ export type Notification = subject_id: null; commit: null; }) + | (BaseNotification & { + type: 'live_started'; + commit_id: null; + subject_id: null; + commit: null; + }) | (BaseNotification & { type: 'replied' | 'starred'; commit_id: string; diff --git a/routes/web.php b/routes/web.php index e4b8c6961f..d4dd2468a1 100644 --- a/routes/web.php +++ b/routes/web.php @@ -158,6 +158,8 @@ use App\Http\Controllers\UserFollowingController; use App\Http\Controllers\UserLaneController; use App\Http\Controllers\UserLiveController; +use App\Http\Controllers\UserLiveNotificationController; +use App\Http\Controllers\UserLiveNotificationsController; use App\Http\Controllers\UserMuteController; use App\Http\Controllers\UserMutualsController; use App\Http\Controllers\UserPasteisModeController; @@ -710,6 +712,8 @@ Route::put('settings/remotes', [UserRemotesController::class, 'update'])->name('user-remotes.update'); + Route::put('settings/live-notifications', [UserLiveNotificationsController::class, 'update'])->name('user-live-notifications.update'); + // User Live... Route::put('settings/live', [UserLiveController::class, 'update']) ->middleware(PreventPostingInTimeout::class) @@ -766,6 +770,12 @@ ->middleware('throttle:follows') ->name('organization-follow.destroy'); + // User Live Notifications... + Route::post('@{user:handle}/live-notification', [UserLiveNotificationController::class, 'store']) + ->name('user-live-notification.store'); + Route::delete('@{user:handle}/live-notification', [UserLiveNotificationController::class, 'destroy']) + ->name('user-live-notification.destroy'); + // User Mute... Route::post('@{user:handle}/mute', [UserMuteController::class, 'store']) ->name('user-mute.store'); diff --git a/tests/Feature/Controllers/ExportControllerTest.php b/tests/Feature/Controllers/ExportControllerTest.php index ebd7b84f55..0d807738d1 100644 --- a/tests/Feature/Controllers/ExportControllerTest.php +++ b/tests/Feature/Controllers/ExportControllerTest.php @@ -97,7 +97,7 @@ $data = json_decode($response->streamedContent(), true, flags: JSON_THROW_ON_ERROR); expect($data)->toBe([ - 'schema_version' => 9, + 'schema_version' => 10, 'exported_at' => now()->toIso8601String(), 'profile' => [ 'github_id' => $user->github_id, @@ -121,6 +121,7 @@ 'pasteis_given_today' => 6, 'pasteis_given_on' => '2026-10-15', 'remotes_enabled' => true, + 'live_notifications_enabled' => true, 'remotes_from' => 'following', 'pull_receipts' => true, 'push_follows' => true, @@ -401,8 +402,8 @@ $response = $this->actingAs($user)->get(route('export')); $data = json_decode($response->streamedContent(), true, flags: JSON_THROW_ON_ERROR); - expect($data['following'])->toBe([['handle' => 'demo-developer']]) - ->and($data['followers'])->toBe([['handle' => 'demo-follower']]) + expect($data['following'])->toBe([['handle' => 'demo-developer', 'notify_live' => true]]) + ->and($data['followers'])->toBe([['handle' => 'demo-follower', 'notify_live' => true]]) ->and($response->streamedContent())->not->toContain( $followed->email, $followed->github_id, $followed->id, $followed->remember_token, $follower->email, $follower->id, $stranger->handle, diff --git a/tests/Feature/LiveNotificationsTest.php b/tests/Feature/LiveNotificationsTest.php new file mode 100644 index 0000000000..f234b76498 --- /dev/null +++ b/tests/Feature/LiveNotificationsTest.php @@ -0,0 +1,167 @@ +freezeTime(); + $streamer = User::factory()->create(); + $follower = User::factory()->create(); + $follower->following()->attach($streamer); + + resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 2); + + // The same stale model is still live in the database: a second request must not notify again. + resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 3); + + expect($follower->notifications()->where('type', NotificationType::LiveStarted)->count())->toBe(1) + ->and($follower->notifications()->sole()->key)->toBe('live_started:'.$streamer->id.':'.now()->addHours(2)->getTimestamp()); +}); + +it('only tells followers who still want to hear about this stream', function (): void { + $streamer = User::factory()->create(); + $watching = User::factory()->create(); + $optedOut = User::factory()->create(); + $muted = User::factory()->create(); + $blocked = User::factory()->create(); + $blocking = User::factory()->create(); + $turnedOff = User::factory()->create(['live_notifications_enabled' => false]); + + $watching->following()->attach($streamer); + $optedOut->following()->attach($streamer, ['notify_live' => false]); + $muted->following()->attach($streamer); + $muted->muting()->attach($streamer); + $blocked->following()->attach($streamer); + $streamer->blocking()->attach($blocked); + $blocking->following()->attach($streamer); + $blocking->blocking()->attach($streamer); + $turnedOff->following()->attach($streamer); + + resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 2); + + expect(Notification::query()->where('type', NotificationType::LiveStarted)->pluck('recipient_id')->all()) + ->toEqualCanonicalizing([$watching->id]); +}); + +it('keeps every per-profile switch while the account-wide switch is off', function (): void { + $streamer = User::factory()->create(); + $follower = User::factory()->create(); + $on = User::factory()->create(); + $off = User::factory()->create(); + + $follower->following()->attach($streamer); + $follower->following()->attach($on); + $follower->following()->attach($off, ['notify_live' => false]); + + $this->actingAs($follower) + ->put(route('user-live-notifications.update'), ['enabled' => false]) + ->assertRedirect(); + + expect($follower->refresh()->live_notifications_enabled)->toBeFalse() + ->and($follower->isNotifyingLive($on))->toBeTrue() + ->and($follower->isNotifyingLive($off))->toBeFalse(); + + resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 2); + $streamer->refresh(); + resolve(DeleteUserLive::class)->handle($streamer); + + expect(Notification::query()->where('type', NotificationType::LiveStarted)->exists())->toBeFalse(); + + $this->actingAs($follower) + ->put(route('user-live-notifications.update'), ['enabled' => true]) + ->assertRedirect(); + + expect($follower->refresh()->live_notifications_enabled)->toBeTrue() + ->and($follower->isNotifyingLive($on))->toBeTrue() + ->and($follower->isNotifyingLive($off))->toBeFalse(); + + $this->travel(1)->hour(); + resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 2); + + expect(Notification::query()->where('type', NotificationType::LiveStarted)->whereNull('read_at')->count())->toBe(1); +}); + +it("exports each follow's live alert choice without touching other relationships", function (): void { + $follower = User::factory()->create(); + $wanted = User::factory()->create(); + $silenced = User::factory()->create(); + + $follower->following()->attach($wanted); + $follower->following()->attach($silenced, ['notify_live' => false]); + $follower->muting()->attach($silenced); + + $export = resolve(CreateExport::class)->handle($follower); + + expect(iterator_to_array($export['following'])) + ->toEqualCanonicalizing([ + ['handle' => $wanted->handle, 'notify_live' => true], + ['handle' => $silenced->handle, 'notify_live' => false], + ]) + ->and(iterator_to_array($export['muting']))->toBe([['handle' => $silenced->handle]]); +}); + +it('only lets a follower change their own live alert for another developer', function (): void { + $follower = User::factory()->create(); + $followed = User::factory()->create(); + $stranger = User::factory()->create(); + + $follower->following()->attach($followed); + + $this->actingAs($follower)->post(route('user-live-notification.store', $followed))->assertRedirect(); + $this->actingAs($follower)->delete(route('user-live-notification.destroy', $followed))->assertRedirect(); + + expect($follower->isFollowing($followed))->toBeTrue() + ->and($follower->isNotifyingLive($followed))->toBeFalse(); + + $this->actingAs($follower)->postJson(route('user-live-notification.store', $stranger))->assertForbidden(); + $this->actingAs($follower)->deleteJson(route('user-live-notification.destroy', $stranger))->assertForbidden(); + $this->actingAs($follower)->postJson(route('user-live-notification.store', $follower))->assertForbidden(); + + expect($follower->isNotifyingLive($stranger))->toBeFalse() + ->and($follower->isNotifyingLive($follower))->toBeFalse(); +}); + +it('shares the newest live notification id, including once read, but not a silenced one', function (): void { + $recipient = User::factory()->create(); + $streamer = User::factory()->create(); + $endsAt = now()->addHours(2); + $createdAt = now()->subMinute(); + + Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer, $endsAt)->create([ + 'id' => '00000000-0000-7000-8000-000000000001', + 'created_at' => $createdAt, + 'updated_at' => $createdAt, + ]); + $newest = Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer, $endsAt->addHour())->read()->create([ + 'id' => '00000000-0000-7000-8000-000000000002', + 'created_at' => $createdAt, + 'updated_at' => $createdAt, + ]); + + $request = Request::create('/', 'GET'); + $request->setUserResolver(fn (): User => $recipient); + + $latest = new HandleInertiaRequests()->share($request)['auth']['latestLiveNotificationId']; + + expect($latest())->toBe($newest->id); + + $recipient->muting()->attach($streamer); + + expect($latest())->toBeNull(); +}); diff --git a/tests/Unit/Enums/NotificationTypeTest.php b/tests/Unit/Enums/NotificationTypeTest.php index 5f87c51bba..4997232592 100644 --- a/tests/Unit/Enums/NotificationTypeTest.php +++ b/tests/Unit/Enums/NotificationTypeTest.php @@ -7,6 +7,7 @@ it('has the types of a notification', function (): void { expect(array_column(NotificationType::cases(), 'value', 'name'))->toBe([ 'Followed' => 'followed', + 'LiveStarted' => 'live_started', 'Replied' => 'replied', 'Mentioned' => 'mentioned', 'Approved' => 'approved', diff --git a/tests/Unit/LiveNotificationPolling.test.ts b/tests/Unit/LiveNotificationPolling.test.ts new file mode 100644 index 0000000000..f3af06fa10 --- /dev/null +++ b/tests/Unit/LiveNotificationPolling.test.ts @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + liveNotificationPollInterval, + shouldPollLiveNotifications, +} from '../../resources/js/lib/notification-polling.ts'; + +const ready = { + signedIn: true, + liveNotificationsEnabled: true, + liveSoundEnabled: true, + isHearingCounts: false, +}; + +void test('polls live alert IDs when sound recipients have no realtime connection', () => { + assert.equal(shouldPollLiveNotifications(ready), true); +}); + +for (const [reason, context] of Object.entries({ + guest: { signedIn: false }, + 'live notifications disabled': { liveNotificationsEnabled: false }, + 'live sound disabled': { liveSoundEnabled: false }, + 'realtime connected': { isHearingCounts: true }, +})) { + void test(`does not poll for ${reason}`, () => { + assert.equal( + shouldPollLiveNotifications({ ...ready, ...context }), + false, + ); + }); +} + +void test('uses the remote-like fallback interval without realtime', () => { + assert.equal(liveNotificationPollInterval(), 15_000); +}); diff --git a/tests/Unit/LiveNotificationQueriesTest.php b/tests/Unit/LiveNotificationQueriesTest.php new file mode 100644 index 0000000000..648c21a128 --- /dev/null +++ b/tests/Unit/LiveNotificationQueriesTest.php @@ -0,0 +1,65 @@ +create(); + $streamer = User::factory()->create(); + $endsAt = now()->addHours(3); + + $notification = Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer, $endsAt)->create(); + + expect($notification->type)->toBe(NotificationType::LiveStarted) + ->and($notification->key)->toBe('live_started:'.$streamer->id.':'.$endsAt->getTimestamp()) + ->and(Notification::query()->whereKey($notification->id)->relevant()->exists())->toBeTrue(); +}); + +it('hides live notifications on read when the actor is muted or across a block', function (string $silence): void { + $recipient = User::factory()->create(); + $streamer = User::factory()->create(); + $notification = Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer)->create(); + + match ($silence) { + 'muted' => $recipient->muting()->attach($streamer), + 'recipient blocked' => $recipient->blocking()->attach($streamer), + 'actor blocked' => $streamer->blocking()->attach($recipient), + }; + + expect(Notification::query()->whereKey($notification->id)->relevant()->exists())->toBeFalse(); +})->with(['muted', 'recipient blocked', 'actor blocked']); + +it('marks live notifications read but keeps their per-follow settings when alerts are switched off', function (): void { + $recipient = User::factory()->create(); + $streamer = User::factory()->create(); + $other = Notification::factory()->for($recipient, 'recipient')->create(); + $live = Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer)->create(); + + resolve(UpdateUserLiveNotifications::class)->handle($recipient, false); + + expect(Notification::query()->whereKey($live->id)->relevant()->exists())->toBeFalse() + ->and($live->fresh()->read_at)->not->toBeNull() + ->and(Notification::query()->whereKey($other->id)->relevant()->exists())->toBeTrue() + ->and($other->fresh()->read_at)->toBeNull(); + + resolve(UpdateUserLiveNotifications::class)->handle($recipient, true); + + expect(Notification::query()->whereKey($live->id)->relevant()->exists())->toBeTrue() + ->and($live->fresh()->read_at)->not->toBeNull(); +}); + +it('groups each live notification on its own topic', function (): void { + $recipient = User::factory()->create(); + $streamer = User::factory()->create(); + + Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer, now()->addHours(2))->create(['created_at' => now()->subMinutes(10)]); + Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer, now()->addHours(3))->create(); + Notification::factory()->for($recipient, 'recipient')->create(); + + expect(resolve(NotificationGroupsQuery::class)->events($recipient)->where('group_rank', 1)->count())->toBe(3); +}); diff --git a/tests/Unit/LiveNotificationSettings.test.tsx b/tests/Unit/LiveNotificationSettings.test.tsx new file mode 100644 index 0000000000..0059f9b078 --- /dev/null +++ b/tests/Unit/LiveNotificationSettings.test.tsx @@ -0,0 +1,249 @@ +/// +import assert from 'node:assert/strict'; +import * as React from 'react'; +import type { ReactNode } from 'react'; +import { afterEach, beforeEach, test, vi } from 'vite-plus/test'; +import { find, hookHarness } from './HookHarness'; + +type Callbacks = { + onStart?: () => void; + onSuccess?: () => void; + onError?: () => void; + onCancel?: () => void; + onNetworkError?: () => void; + onHttpException?: () => void; + onFinish?: () => void; +}; + +const harness = hookHarness(); +const puts: Callbacks[] = []; +const visits: Callbacks[] = []; +const toasts: string[] = []; +let liveEnabled = false; + +vi.doMock('react', () => harness.react); +vi.doMock('@inertiajs/react', async () => ({ + ...(await vi.importActual('@inertiajs/react')), + usePage: () => ({ + props: { + auth: { + user: { id: 'viewer', handle: 'viewer' }, + remotes: null, + liveNotificationsEnabled: liveEnabled, + }, + }, + }), + router: { + put: (_url: string, data: unknown, options: Callbacks) => { + const requested = (data as { enabled: boolean }).enabled; + + puts.push({ + ...options, + onSuccess: () => { + liveEnabled = requested; + options.onSuccess?.(); + }, + }); + }, + visit: (_action: unknown, options: Callbacks) => visits.push(options), + flushAll: () => {}, + reload: () => {}, + on: () => () => {}, + }, +})); +vi.doMock('sonner', () => ({ + toast: { + error: (message: string) => toasts.push(message), + success: () => {}, + }, +})); +vi.doMock( + '@/actions/App/Http/Controllers/UserLiveNotificationsController', + () => ({ + update: { url: () => '/settings/live-notifications' }, + }), +); +vi.doMock( + '@/actions/App/Http/Controllers/UserLiveNotificationController', + () => ({ + default: { + store: (user: { id: string }) => ({ + url: `/@${user.id}/live`, + method: 'post', + }), + destroy: (user: { id: string }) => ({ + url: `/@${user.id}/live`, + method: 'delete', + }), + }, + }), +); +vi.doMock('@/actions/App/Http/Controllers/UserMuteController', () => ({ + default: { store: () => ({}), destroy: () => ({}) }, +})); +vi.doMock('@/actions/App/Http/Controllers/UserBlockController', () => ({ + default: { store: () => ({}), destroy: () => ({}) }, +})); +vi.doMock('@/actions/App/Http/Controllers/ConversationController', () => ({ + default: { show: () => ({}) }, +})); +vi.doMock('@/actions/App/Http/Controllers/UserFollowController', () => ({ + default: { store: () => ({}), destroy: () => ({}) }, +})); +vi.doMock('@/actions/App/Http/Controllers/IssueSuggestionController', () => ({ + index: () => ({}), +})); +vi.doMock('@/actions/App/Http/Controllers/MentionSuggestionController', () => ({ + default: { index: () => ({}) }, +})); +vi.doMock('@/routes', () => ({ login: () => ({ url: '/login' }) })); + +const { LiveNotificationsSetting } = + await import('../../resources/js/components/live-notifications-setting'); +const { UserSafetyMenu } = + await import('../../resources/js/components/user-safety-menu'); + +const menuProps: Parameters[0] = { + user: { id: 'target', handle: 'target' }, + isMuting: false, + isBlocking: false, + isFollowing: true, + isNotifyingLive: false, +}; + +function setting(): ReactNode { + return harness.render(LiveNotificationsSetting, {}); +} + +function menuView(): ReactNode { + return harness.render(UserSafetyMenu, menuProps); +} + +function settingSwitch(node: ReactNode) { + const button = find( + node, + (props) => props['data-test'] === 'live-notifications-setting', + ); + assert.ok(button); + + return button; +} + +function menu(node: ReactNode) { + const dropdown = find( + node, + (props) => 'modal' in props && 'onOpenChange' in props, + ); + assert.ok(dropdown); + + return dropdown; +} + +function liveItem(node: ReactNode) { + const item = find( + node, + (props) => props['data-test'] === 'live-notification-toggle', + ); + assert.ok(item); + + return item; +} + +beforeEach(() => { + liveEnabled = false; + puts.length = 0; + visits.length = 0; + toasts.length = 0; + vi.stubGlobal('window', { + addEventListener() {}, + removeEventListener() {}, + matchMedia: () => ({ + matches: false, + addEventListener() {}, + removeEventListener() {}, + }), + }); + vi.stubGlobal('document', { + addEventListener() {}, + removeEventListener() {}, + body: {}, + }); + vi.stubGlobal('navigator', {}); +}); + +afterEach(() => { + harness.unmount(); + vi.unstubAllGlobals(); +}); + +test('restores the global live-notifications switch when saving fails', () => { + const button = settingSwitch(setting()); + (button.props.onClick as () => void)(); + + assert.equal(settingSwitch(setting()).props['aria-checked'], true); + + puts.at(-1)?.onError?.(); + assert.equal(settingSwitch(setting()).props['aria-checked'], false); + assert.equal(toasts.length, 1); +}); + +test('keeps the committed global switch after a successful save', () => { + const button = settingSwitch(setting()); + (button.props.onClick as () => void)(); + + puts.at(-1)?.onSuccess?.(); + assert.equal(settingSwitch(setting()).props['aria-checked'], true); + assert.equal(toasts.length, 0); +}); + +test('keeps the per-profile menu open when the live choice fails', () => { + liveEnabled = true; + const dropdown = menu( + harness.render(UserSafetyMenu, { + user: { id: 'target', handle: 'target' }, + isMuting: false, + isBlocking: false, + isFollowing: true, + isNotifyingLive: false, + }), + ); + (dropdown.props.onOpenChange as (open: boolean) => void)(true); + + const item = liveItem(menuView()); + (item.props.onSelect as () => void)(); + visits.at(-1)?.onStart?.(); + assert.ok( + React.Children.toArray( + liveItem(menuView()).props.children as ReactNode, + ).some( + (child) => + typeof child === 'string' && + child.includes('Turn off Live notify'), + ), + ); + + visits.at(-1)?.onError?.(); + assert.equal(menu(menuView()).props.open, true); +}); + +test('closes the per-profile menu only after the live choice succeeds', () => { + liveEnabled = true; + const dropdown = menu( + harness.render(UserSafetyMenu, { + user: { id: 'target', handle: 'target' }, + isMuting: false, + isBlocking: false, + isFollowing: true, + isNotifyingLive: false, + }), + ); + (dropdown.props.onOpenChange as (open: boolean) => void)(true); + + const item = liveItem(menuView()); + (item.props.onSelect as () => void)(); + visits.at(-1)?.onStart?.(); + assert.equal(menu(menuView()).props.open, true); + + visits.at(-1)?.onSuccess?.(); + assert.equal(menu(menuView()).props.open, false); +}); diff --git a/tests/Unit/LiveNotificationSound.test.tsx b/tests/Unit/LiveNotificationSound.test.tsx new file mode 100644 index 0000000000..7289870b81 --- /dev/null +++ b/tests/Unit/LiveNotificationSound.test.tsx @@ -0,0 +1,224 @@ +/// +import assert from 'node:assert/strict'; +import { afterEach, beforeEach, test, vi } from 'vite-plus/test'; +import { hookHarness } from './HookHarness'; + +const harness = hookHarness(); +const storage = new Map(); +const played: { src: string; muted: boolean }[] = []; +const listeners = new Map void>>(); +const lockNames: string[] = []; + +class FakeAudio { + static reject = false; + static last: FakeAudio | null = null; + + src = ''; + currentTime = 0; + muted = false; + + constructor() { + FakeAudio.last = this; + } + + play() { + played.push({ src: this.src, muted: this.muted }); + + return FakeAudio.reject + ? Promise.reject(new Error('autoplay blocked')) + : Promise.resolve(); + } + + pause() {} +} + +vi.doMock('react', () => harness.react); + +const { useLiveNotificationSound } = + await import('../../resources/js/hooks/use-live-notification-sound'); + +function Sound({ + latestNotificationId, + userId, + liveNotificationsEnabled = true, +}: { + latestNotificationId: string | null; + userId: string; + liveNotificationsEnabled?: boolean; +}) { + useLiveNotificationSound( + latestNotificationId, + userId, + liveNotificationsEnabled, + ); + + return null; +} + +const props = ( + latestNotificationId: string | null, + userId = 'viewer', + liveNotificationsEnabled = true, +) => ({ latestNotificationId, userId, liveNotificationsEnabled }); + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +beforeEach(() => { + storage.clear(); + storage.set('remote-alerts:viewer:sound', 'on'); + storage.set('remote-sound:viewer', 'icq'); + played.length = 0; + lockNames.length = 0; + listeners.clear(); + FakeAudio.reject = false; + FakeAudio.last = null; + vi.stubGlobal('window', { + localStorage: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key), + }, + addEventListener: (type: string, listener: () => void) => { + const set = listeners.get(type) ?? new Set<() => void>(); + set.add(listener); + listeners.set(type, set); + }, + removeEventListener: (type: string, listener: () => void) => { + listeners.get(type)?.delete(listener); + }, + }); + vi.stubGlobal('document', { + addEventListener() {}, + removeEventListener() {}, + }); + vi.stubGlobal('navigator', { + locks: { + request: async (name: string, callback: () => Promise) => { + lockNames.push(name); + await callback(); + }, + }, + }); + vi.stubGlobal('Audio', FakeAudio); +}); + +afterEach(() => { + harness.unmount(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +test('plays once for a new alert through a lock, without replaying the backlog', async () => { + void harness.render(Sound, props('first')); + await flush(); + assert.equal(played.length, 0); + + void harness.render(Sound, props('first')); + await flush(); + assert.equal(played.length, 0); + + void harness.render(Sound, props('second')); + await flush(); + + assert.deepEqual(played, [{ src: '/sounds/icq.mp3', muted: false }]); + assert.deepEqual(lockNames, ['live-alert-sound:viewer']); + assert.equal(storage.get('live-alert-played:viewer'), 'second'); + + void harness.render(Sound, props('second')); + await flush(); + assert.equal(played.length, 1); +}); + +test('keeps an alert pending after a blocked play and plays it after a gesture', async () => { + FakeAudio.reject = true; + void harness.render(Sound, props('first')); + await flush(); + void harness.render(Sound, props('second')); + await flush(); + + assert.equal(storage.has('live-alert-played:viewer'), false); + + FakeAudio.reject = false; + listeners.get('pointerdown')?.forEach((listener) => listener()); + await flush(); + + assert.deepEqual(played.at(-1), { + src: '/sounds/icq.mp3', + muted: false, + }); + assert.equal(storage.get('live-alert-played:viewer'), 'second'); +}); + +test('does not replay an alert another tab already claimed', async () => { + storage.set('live-alert-played:viewer', 'second'); + void harness.render(Sound, props('first')); + await flush(); + void harness.render(Sound, props('second')); + await flush(); + + assert.equal(played.length, 0); + assert.deepEqual( + [...storage.keys()].filter((key) => + key.startsWith('live-alert-played:'), + ), + ['live-alert-played:viewer'], + ); +}); + +test('stays silent while the live sound or live notifications are off', async () => { + storage.set('remote-alerts:viewer:live-sound', 'off'); + void harness.render(Sound, props('first')); + await flush(); + void harness.render(Sound, props('second')); + await flush(); + assert.equal(played.length, 0); + + storage.set('remote-alerts:viewer:live-sound', 'on'); + void harness.render(Sound, props('second')); + await flush(); + assert.equal( + played.length, + 0, + 'enabling sound does not replay the backlog', + ); + + void harness.render(Sound, props('third', 'viewer', false)); + await flush(); + void harness.render(Sound, props('fourth', 'viewer', false)); + await flush(); + assert.equal(played.length, 0); + + void harness.render(Sound, props('fourth')); + await flush(); + assert.equal( + played.length, + 0, + 'enabling alerts does not replay the backlog', + ); +}); + +test('does not replay an alert that comes back after live alerts were off', async () => { + void harness.render(Sound, props('first')); + await flush(); + void harness.render(Sound, props(null, 'viewer', false)); + await flush(); + void harness.render(Sound, props('first')); + await flush(); + + assert.equal(played.length, 0); + + void harness.render(Sound, props('second')); + await flush(); + + assert.deepEqual(played, [{ src: '/sounds/icq.mp3', muted: false }]); +}); + +test('plays for a signed-in reader regardless of remotes and uses the live sound choice', async () => { + storage.set('live-notification-sound:viewer', 'aim'); + void harness.render(Sound, props('first')); + await flush(); + void harness.render(Sound, props('second')); + await flush(); + + assert.deepEqual(played, [{ src: '/sounds/aim.mp3', muted: false }]); +}); diff --git a/tests/Unit/LiveNotificationUi.test.tsx b/tests/Unit/LiveNotificationUi.test.tsx new file mode 100644 index 0000000000..e9163399c0 --- /dev/null +++ b/tests/Unit/LiveNotificationUi.test.tsx @@ -0,0 +1,116 @@ +/// +import assert from 'node:assert/strict'; +import { createInertiaApp } from '@inertiajs/react'; +import { renderToString } from 'react-dom/server'; +import { test } from 'vite-plus/test'; +import { TooltipProvider } from '../../resources/js/components/ui/tooltip'; +import Index from '../../resources/js/pages/notification/index'; +import type { NotificationGroup, User } from '../../resources/js/types'; + +const timestamp = '2026-11-29T12:00:00Z'; +const actor: User = { + id: 'live-actor', + handle: 'octocat', + name: 'Octocat', + avatar_url: 'https://cdn.test/avatar.png', + bio: null, + location: null, + website: null, + company: null, + has_sponsors_listing: false, + has_github_account: true, + lane: 0, + timezone: null, + show_local_time: false, + live: { + url: 'https://www.twitch.tv/octocat', + thumbnail_url: 'https://cdn.test/preview.jpg', + ends_at: null, + }, + created_at: timestamp, + updated_at: timestamp, +}; + +const live: NotificationGroup = { + id: 'live', + recipient_id: 'viewer', + actor_id: actor.id, + commit_id: null, + subject_id: null, + reason: null, + group_id: 'live', + type: 'live_started', + actor: { ...actor, type: 'user', is_followed: false }, + organization: null, + actors: [{ ...actor, type: 'user', is_followed: false }], + actors_count: 1, + event_count: 1, + unread_count: 0, + read_at: timestamp, + created_at: timestamp, + updated_at: timestamp, + commit: null, +}; + +async function renderInbox(notifications: NotificationGroup[]) { + const result = await createInertiaApp({ + page: { + component: 'notification/index', + props: { + auth: { + user: { id: 'viewer', handle: 'viewer' }, + log: {}, + }, + errors: {}, + }, + url: '/notifications', + version: null, + clearHistory: false, + encryptHistory: false, + rescuedProps: [], + rememberedState: {}, + flash: {}, + }, + resolve: () => () => ( + + ), + render: renderToString, + setup: ({ App, props }) => ( + + + + ), + }); + + assert.ok(result); + return result.body.replaceAll('', ''); +} + +test('links a live notification to the stream with a stable marker and the actor avatar', async () => { + const html = await renderInbox([live]); + + assert.match(html, /went live/); + assert.match( + html, + /]*data-test="live-notification-link")(?=[^>]*href="https:\/\/www\.twitch\.tv\/octocat")[^>]*>/, + ); + assert.match(html, /target="_blank"/); + assert.match(html, /data-slot="avatar"/); + assert.match(html, /data-slot="avatar-fallback"[^>]*>O { + const html = await renderInbox([ + { ...live, event_count: 2, actors_count: 2 }, + ]); + + assert.match(html, /2 live alerts/); +}); From 81a28c26c74d1d003668028bccc073b55cb974c8 Mon Sep 17 00:00:00 2001 From: WilliamShakesGibson <343627761+WilliamShakesGibson@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:10:19 -0600 Subject: [PATCH 2/4] fix: address live notification review findings - release the global switch after a failed save or network error - stop non-following safety menus from overwriting shared live state - keep a newer alert pending when an older sound attempt finishes - treat only strictly newer notification IDs as new alerts - link expanded live members to the stream --- .../components/live-notifications-setting.tsx | 11 +-- resources/js/components/user-safety-menu.tsx | 12 +-- .../js/hooks/use-live-notification-sound.ts | 30 +++++-- resources/js/pages/notification/index.tsx | 51 ++++++++--- tests/Unit/LiveNotificationSettings.test.tsx | 68 ++++++++++++++- tests/Unit/LiveNotificationSound.test.tsx | 84 ++++++++++++++++++- tests/Unit/LiveNotificationUi.test.tsx | 49 ++++++++++- 7 files changed, 272 insertions(+), 33 deletions(-) diff --git a/resources/js/components/live-notifications-setting.tsx b/resources/js/components/live-notifications-setting.tsx index 6c861af76a..4b891487a0 100644 --- a/resources/js/components/live-notifications-setting.tsx +++ b/resources/js/components/live-notifications-setting.tsx @@ -17,6 +17,7 @@ export function LiveNotificationsSetting() { const next = !enabled; const finish = pick(next); + const failed = 'Could not save live notifications. Please try again.'; router.put( update.url(), @@ -25,16 +26,16 @@ export function LiveNotificationsSetting() { preserveScroll: true, only: ['auth'], onSuccess: () => { - finish(); router.flushAll(); }, onError: () => { - finish(); - toast.error( - 'Could not save live notifications. Please try again.', - ); + toast.error(failed); + }, + onNetworkError: () => { + toast.error(failed); }, onCancel: finish, + onFinish: finish, }, ); }; diff --git a/resources/js/components/user-safety-menu.tsx b/resources/js/components/user-safety-menu.tsx index 3609ed3dff..41afbf828b 100644 --- a/resources/js/components/user-safety-menu.tsx +++ b/resources/js/components/user-safety-menu.tsx @@ -77,11 +77,13 @@ export function UserSafetyMenu({ ); useEffect(() => { - refreshSharedState( - new Map([ - [notifyLiveKey, isFollowing ? initialIsNotifyingLive : true], - ]), - ); + // A preview may mount the menu without follow data; only a menu that + // knows the follow state is allowed to publish it. + if (!isFollowing) { + return; + } + + refreshSharedState(new Map([[notifyLiveKey, initialIsNotifyingLive]])); }, [initialIsNotifyingLive, isFollowing, notifyLiveKey]); const changeOpen = (menu: boolean, dialog: boolean) => { diff --git a/resources/js/hooks/use-live-notification-sound.ts b/resources/js/hooks/use-live-notification-sound.ts index f010971e2f..9afebeaf03 100644 --- a/resources/js/hooks/use-live-notification-sound.ts +++ b/resources/js/hooks/use-live-notification-sound.ts @@ -33,6 +33,7 @@ export function useLiveNotificationSound( const seen = useRef({ userId, notificationId: latestNotificationId, + observedId: latestNotificationId, armed: soundEnabled, }); const pending = useRef(null); @@ -70,7 +71,11 @@ export function useLiveNotificationSound( return; } - pending.current = null; + // A newer alert can take over while play() is pending; do not + // clear its slot when this older attempt finishes. + if (pending.current === id) { + pending.current = null; + } writeStorage(playedKey, id); }; @@ -90,18 +95,34 @@ export function useLiveNotificationSound( useEffect(() => { const previous = seen.current; - seen.current = { + const next = { userId, notificationId: latestNotificationId, + observedId: previous.observedId, armed: soundEnabled, }; if (userId === null || previous.userId !== userId) { + next.observedId = latestNotificationId; pending.current = null; + seen.current = next; return; } + // A filtered-out alert can make the query return an older ID. Only a + // strictly newer ID is a new stream; UUIDv7 IDs sort by time. + const isNewer = + latestNotificationId !== null && + (next.observedId === null || + latestNotificationId > next.observedId); + + if (isNewer) { + next.observedId = latestNotificationId; + } + + seen.current = next; + if (!soundEnabled || latestNotificationId === null) { pending.current = null; @@ -109,10 +130,7 @@ export function useLiveNotificationSound( } // A quiet browser, including one that lost the ID because live alerts were off, starts from this alert. - if ( - !previous.armed || - previous.notificationId === latestNotificationId - ) { + if (!previous.armed || !isNewer) { return; } diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index c45430b61f..1432a6bff2 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -1230,6 +1230,38 @@ export function NotificationContent({ : actor, commit: notification.commit, }); + // Expanded live-alert members use the same destination as the group row. + const activityLink = ( + children: ReactNode, + className?: string, + tabIndex?: number, + ) => + liveUrl === null ? ( + tabIndex === undefined ? ( + + {children} + + ) : ( + + {children} + + ) + ) : ( + + {children} + + ); const time = (
- - {excerpt} - + {activityLink(excerpt, 'block', -1)}
); diff --git a/tests/Unit/LiveNotificationSettings.test.tsx b/tests/Unit/LiveNotificationSettings.test.tsx index 0059f9b078..3015183d3e 100644 --- a/tests/Unit/LiveNotificationSettings.test.tsx +++ b/tests/Unit/LiveNotificationSettings.test.tsx @@ -18,6 +18,7 @@ type Callbacks = { const harness = hookHarness(); const puts: Callbacks[] = []; const visits: Callbacks[] = []; +const visitActions: unknown[] = []; const toasts: string[] = []; let liveEnabled = false; @@ -45,7 +46,10 @@ vi.doMock('@inertiajs/react', async () => ({ }, }); }, - visit: (_action: unknown, options: Callbacks) => visits.push(options), + visit: (action: unknown, options: Callbacks) => { + visitActions.push(action); + visits.push(options); + }, flushAll: () => {}, reload: () => {}, on: () => () => {}, @@ -102,6 +106,8 @@ const { LiveNotificationsSetting } = await import('../../resources/js/components/live-notifications-setting'); const { UserSafetyMenu } = await import('../../resources/js/components/user-safety-menu'); +const { sharedValue } = + await import('../../resources/js/hooks/use-shared-state'); const menuProps: Parameters[0] = { user: { id: 'target', handle: 'target' }, @@ -153,6 +159,7 @@ beforeEach(() => { liveEnabled = false; puts.length = 0; visits.length = 0; + visitActions.length = 0; toasts.length = 0; vi.stubGlobal('window', { addEventListener() {}, @@ -183,19 +190,78 @@ test('restores the global live-notifications switch when saving fails', () => { assert.equal(settingSwitch(setting()).props['aria-checked'], true); puts.at(-1)?.onError?.(); + puts.at(-1)?.onFinish?.(); assert.equal(settingSwitch(setting()).props['aria-checked'], false); assert.equal(toasts.length, 1); }); +test('releases the global switch after a network error so it can be retried', () => { + const button = settingSwitch(setting()); + (button.props.onClick as () => void)(); + + puts.at(-1)?.onNetworkError?.(); + puts.at(-1)?.onFinish?.(); + + const released = settingSwitch(setting()); + assert.equal(released.props['aria-checked'], false); + assert.equal(released.props['aria-disabled'], false); + assert.equal(toasts.length, 1); + + (released.props.onClick as () => void)(); + assert.equal(puts.length, 2); +}); + test('keeps the committed global switch after a successful save', () => { const button = settingSwitch(setting()); (button.props.onClick as () => void)(); puts.at(-1)?.onSuccess?.(); + puts.at(-1)?.onFinish?.(); assert.equal(settingSwitch(setting()).props['aria-checked'], true); assert.equal(toasts.length, 0); }); +test('does not let a non-following menu overwrite an authoritative live choice', () => { + liveEnabled = true; + const id = 'authoritative-target'; + const authoritative: Parameters[0] = { + user: { id, handle: id }, + isMuting: false, + isBlocking: false, + isFollowing: true, + isNotifyingLive: false, + }; + const view = () => harness.render(UserSafetyMenu, authoritative); + const key = `is_notifying_live:${id}`; + + void view(); + assert.equal(sharedValue(key), false); + + void harness.render(UserSafetyMenu, { + user: { id, handle: id }, + isMuting: false, + isBlocking: false, + }); + assert.equal(sharedValue(key), false); + + const dropdown = menu(view()); + (dropdown.props.onOpenChange as (open: boolean) => void)(true); + + const item = liveItem(view()); + assert.ok( + React.Children.toArray(item.props.children as ReactNode).some( + (child) => + typeof child === 'string' && child.includes('Notify when Live'), + ), + ); + + (item.props.onSelect as () => void)(); + assert.equal( + (visitActions.at(-1) as { method?: string } | undefined)?.method, + 'post', + ); +}); + test('keeps the per-profile menu open when the live choice fails', () => { liveEnabled = true; const dropdown = menu( diff --git a/tests/Unit/LiveNotificationSound.test.tsx b/tests/Unit/LiveNotificationSound.test.tsx index 7289870b81..15e0edd2ac 100644 --- a/tests/Unit/LiveNotificationSound.test.tsx +++ b/tests/Unit/LiveNotificationSound.test.tsx @@ -12,6 +12,7 @@ const lockNames: string[] = []; class FakeAudio { static reject = false; static last: FakeAudio | null = null; + static gate: ((resolve: () => void) => void) | null = null; src = ''; currentTime = 0; @@ -24,9 +25,18 @@ class FakeAudio { play() { played.push({ src: this.src, muted: this.muted }); - return FakeAudio.reject - ? Promise.reject(new Error('autoplay blocked')) - : Promise.resolve(); + if (FakeAudio.reject) { + return Promise.reject(new Error('autoplay blocked')); + } + + const gate = FakeAudio.gate; + if (gate) { + FakeAudio.gate = null; + + return new Promise((resolve) => gate(resolve)); + } + + return Promise.resolve(); } pause() {} @@ -72,6 +82,7 @@ beforeEach(() => { listeners.clear(); FakeAudio.reject = false; FakeAudio.last = null; + FakeAudio.gate = null; vi.stubGlobal('window', { localStorage: { getItem: (key: string) => storage.get(key) ?? null, @@ -91,11 +102,32 @@ beforeEach(() => { addEventListener() {}, removeEventListener() {}, }); + // Serialize lock callbacks so a newer alert really queues behind an older + // one, matching navigator.locks in the browser. + const lockQueue: Array<() => Promise> = []; + let draining = false; + + const drain = async (): Promise => { + if (draining) { + return; + } + + draining = true; + try { + while (lockQueue.length > 0) { + await lockQueue.shift()?.(); + } + } finally { + draining = false; + } + }; + vi.stubGlobal('navigator', { locks: { request: async (name: string, callback: () => Promise) => { lockNames.push(name); - await callback(); + lockQueue.push(callback); + await drain(); }, }, }); @@ -222,3 +254,47 @@ test('plays for a signed-in reader regardless of remotes and uses the live sound assert.deepEqual(played, [{ src: '/sounds/aim.mp3', muted: false }]); }); + +test('lets a newer alert play when an older play finishes after replacement', async () => { + void harness.render(Sound, props('first')); + await flush(); + + let release: (() => void) | null = null; + FakeAudio.gate = (resolve) => { + release = resolve; + }; + + void harness.render(Sound, props('second')); + await flush(); + assert.ok(release, 'the second alert started playing'); + + void harness.render(Sound, props('third')); + await flush(); + + (release as () => void)(); + await flush(); + await flush(); + + assert.equal(played.length, 2); + assert.equal(storage.get('live-alert-played:viewer'), 'third'); +}); + +test('does not play an older alert that becomes newest after filtering', async () => { + void harness.render(Sound, props('second')); + await flush(); + assert.equal(played.length, 0); + + void harness.render(Sound, props('first')); + await flush(); + assert.equal(played.length, 0); + + void harness.render(Sound, props('second')); + await flush(); + assert.equal(played.length, 0); + + void harness.render(Sound, props('third')); + await flush(); + + assert.equal(played.length, 1); + assert.equal(storage.get('live-alert-played:viewer'), 'third'); +}); diff --git a/tests/Unit/LiveNotificationUi.test.tsx b/tests/Unit/LiveNotificationUi.test.tsx index e9163399c0..90ec062b7a 100644 --- a/tests/Unit/LiveNotificationUi.test.tsx +++ b/tests/Unit/LiveNotificationUi.test.tsx @@ -4,7 +4,9 @@ import { createInertiaApp } from '@inertiajs/react'; import { renderToString } from 'react-dom/server'; import { test } from 'vite-plus/test'; import { TooltipProvider } from '../../resources/js/components/ui/tooltip'; -import Index from '../../resources/js/pages/notification/index'; +import Index, { + NotificationContent, +} from '../../resources/js/pages/notification/index'; import type { NotificationGroup, User } from '../../resources/js/types'; const timestamp = '2026-11-29T12:00:00Z'; @@ -94,6 +96,40 @@ async function renderInbox(notifications: NotificationGroup[]) { return result.body.replaceAll('', ''); } +async function renderMember(notification: NotificationGroup) { + const result = await createInertiaApp({ + page: { + component: 'notification/index', + props: { + auth: { + user: { id: 'viewer', handle: 'viewer' }, + log: {}, + }, + errors: {}, + }, + url: '/notifications', + version: null, + clearHistory: false, + encryptHistory: false, + rescuedProps: [], + rememberedState: {}, + flash: {}, + }, + resolve: () => () => ( + + ), + render: renderToString, + setup: ({ App, props }) => ( + + + + ), + }); + + assert.ok(result); + return result.body.replaceAll('', ''); +} + test('links a live notification to the stream with a stable marker and the actor avatar', async () => { const html = await renderInbox([live]); @@ -114,3 +150,14 @@ test('names live alerts in the group noun', async () => { assert.match(html, /2 live alerts/); }); + +test('links expanded live members to the stream and keeps the actor name on the profile', async () => { + const html = await renderMember(live); + + assert.equal( + html.match(/href="https:\/\/www\.twitch\.tv\/octocat"/g)?.length, + 2, + ); + assert.match(html, /target="_blank"/); + assert.match(html, /href="\/@octocat"/); +}); From 7e21391e06e623bdf9dd8e099e3abb614ab65d9b Mon Sep 17 00:00:00 2001 From: WilliamShakesGibson <343627761+WilliamShakesGibson@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:32:24 -0600 Subject: [PATCH 3/4] fix: clear remaining live notification review findings - use a per-start key so streams ending in the same second both notify - stop leaking notify_live in the followers response - skip the empty excerpt anchor for live members --- app/Actions/UpdateUserLive.php | 3 ++- app/Models/User.php | 2 +- database/factories/NotificationFactory.php | 3 ++- resources/js/pages/notification/index.tsx | 2 +- .../UserFollowersControllerTest.php | 3 ++- tests/Feature/LiveNotificationsTest.php | 20 ++++++++++++++++++- tests/Unit/LiveNotificationQueriesTest.php | 2 +- tests/Unit/LiveNotificationUi.test.tsx | 3 ++- 8 files changed, 30 insertions(+), 8 deletions(-) diff --git a/app/Actions/UpdateUserLive.php b/app/Actions/UpdateUserLive.php index d139a12522..49dab88134 100644 --- a/app/Actions/UpdateUserLive.php +++ b/app/Actions/UpdateUserLive.php @@ -61,7 +61,8 @@ private function notifyFollowers(User $user, CarbonInterface $endsAt): void } $now = now(); - $key = 'live_started:'.$user->id.':'.$endsAt->getTimestamp(); + // One key per start; the unique index then dedupes only repeated inserts for that same start. + $key = 'live_started:'.$user->id.':'.$endsAt->getTimestamp().':'.Str::uuid7()->toString(); $notifications = array_map(fn (string $followerId): array => [ 'id' => Str::uuid7()->toString(), diff --git a/app/Models/User.php b/app/Models/User.php index a6d58157a2..a0d7965e7c 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -425,7 +425,7 @@ public function following(): BelongsToMany */ public function followers(): BelongsToMany { - return $this->belongsToMany(self::class, 'follows', 'followed_id', 'follower_id')->withPivot('notify_live')->withTimestamps(); + return $this->belongsToMany(self::class, 'follows', 'followed_id', 'follower_id')->withTimestamps(); } /** diff --git a/database/factories/NotificationFactory.php b/database/factories/NotificationFactory.php index 2d57006c8d..a543c22d04 100644 --- a/database/factories/NotificationFactory.php +++ b/database/factories/NotificationFactory.php @@ -11,6 +11,7 @@ use App\Models\UserTimeout; use Carbon\CarbonInterface; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Str; /** * @extends Factory @@ -92,7 +93,7 @@ public function liveStarted(User $streamer, ?CarbonInterface $endsAt = null): se 'actor_id' => $streamer->id, 'type' => NotificationType::LiveStarted, 'commit_id' => null, - 'key' => 'live_started:'.$streamer->id.':'.$endsAt->getTimestamp(), + 'key' => 'live_started:'.$streamer->id.':'.$endsAt->getTimestamp().':'.Str::uuid7()->toString(), ]); } diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index 1432a6bff2..ae3d4b7a65 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -1387,7 +1387,7 @@ export function NotificationContent({ 'ml-auto flex shrink-0 items-center gap-2 rounded-md pl-2 outline-offset-4 focus-visible:outline-2 focus-visible:outline-ring', )}
- {activityLink(excerpt, 'block', -1)} + {excerpt !== null && activityLink(excerpt, 'block', -1)} ); diff --git a/tests/Feature/Controllers/UserFollowersControllerTest.php b/tests/Feature/Controllers/UserFollowersControllerTest.php index 9c759d67e7..804b3ddb58 100644 --- a/tests/Feature/Controllers/UserFollowersControllerTest.php +++ b/tests/Feature/Controllers/UserFollowersControllerTest.php @@ -19,7 +19,8 @@ ->where('type', 'followers') ->has('users.data', 1) ->where('users.data.0.id', $follower->id) - ->missing('users.data.0.email')); + ->missing('users.data.0.email') + ->missing('users.data.0.pivot.notify_live')); }); it('marks the users the viewer follows', function (): void { diff --git a/tests/Feature/LiveNotificationsTest.php b/tests/Feature/LiveNotificationsTest.php index f234b76498..74a7b4d8c9 100644 --- a/tests/Feature/LiveNotificationsTest.php +++ b/tests/Feature/LiveNotificationsTest.php @@ -31,7 +31,25 @@ resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 3); expect($follower->notifications()->where('type', NotificationType::LiveStarted)->count())->toBe(1) - ->and($follower->notifications()->sole()->key)->toBe('live_started:'.$streamer->id.':'.now()->addHours(2)->getTimestamp()); + ->and($follower->notifications()->sole()->key)->toStartWith('live_started:'.$streamer->id.':'.now()->addHours(2)->getTimestamp()); +}); + +it('keeps both alerts when two separate streams end in the same second', function (): void { + $this->freezeTime(); + $streamer = User::factory()->create(); + $follower = User::factory()->create(); + $follower->following()->attach($streamer); + + resolve(UpdateUserLive::class)->handle($streamer, LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 2); + resolve(DeleteUserLive::class)->handle($streamer->refresh()); + + $this->travel(1)->hour(); + resolve(UpdateUserLive::class)->handle($streamer->refresh(), LivePlatform::Twitch, 'https://www.twitch.tv/octocat', 1); + + $keys = $follower->notifications()->where('type', NotificationType::LiveStarted)->pluck('key')->all(); + + expect($keys)->toHaveCount(2) + ->and($keys[0])->not->toBe($keys[1]); }); it('only tells followers who still want to hear about this stream', function (): void { diff --git a/tests/Unit/LiveNotificationQueriesTest.php b/tests/Unit/LiveNotificationQueriesTest.php index 648c21a128..bb01202ae9 100644 --- a/tests/Unit/LiveNotificationQueriesTest.php +++ b/tests/Unit/LiveNotificationQueriesTest.php @@ -16,7 +16,7 @@ $notification = Notification::factory()->for($recipient, 'recipient')->liveStarted($streamer, $endsAt)->create(); expect($notification->type)->toBe(NotificationType::LiveStarted) - ->and($notification->key)->toBe('live_started:'.$streamer->id.':'.$endsAt->getTimestamp()) + ->and($notification->key)->toStartWith('live_started:'.$streamer->id.':'.$endsAt->getTimestamp().':') ->and(Notification::query()->whereKey($notification->id)->relevant()->exists())->toBeTrue(); }); diff --git a/tests/Unit/LiveNotificationUi.test.tsx b/tests/Unit/LiveNotificationUi.test.tsx index 90ec062b7a..70514a3a76 100644 --- a/tests/Unit/LiveNotificationUi.test.tsx +++ b/tests/Unit/LiveNotificationUi.test.tsx @@ -156,8 +156,9 @@ test('links expanded live members to the stream and keeps the actor name on the assert.equal( html.match(/href="https:\/\/www\.twitch\.tv\/octocat"/g)?.length, - 2, + 1, ); assert.match(html, /target="_blank"/); + assert.doesNotMatch(html, /]*tabindex="-1"[^>]*><\/a>/); assert.match(html, /href="\/@octocat"/); }); From a5b9d9fa88c9ac567aa6807e4c78326b3f17c571 Mon Sep 17 00:00:00 2001 From: WilliamShakesGibson <343627761+WilliamShakesGibson@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:44:51 -0600 Subject: [PATCH 4/4] fix: keep notify_live out of following lists --- app/Models/User.php | 2 +- tests/Feature/Controllers/UserFollowingControllerTest.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/Models/User.php b/app/Models/User.php index a0d7965e7c..b0bab54dc2 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -417,7 +417,7 @@ public function hasStarred(Commit $commit): bool */ public function following(): BelongsToMany { - return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withPivot('notify_live')->withTimestamps(); + return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withTimestamps(); } /** diff --git a/tests/Feature/Controllers/UserFollowingControllerTest.php b/tests/Feature/Controllers/UserFollowingControllerTest.php index 18e5b5a047..a327be7643 100644 --- a/tests/Feature/Controllers/UserFollowingControllerTest.php +++ b/tests/Feature/Controllers/UserFollowingControllerTest.php @@ -20,7 +20,8 @@ ->where('type', 'following') ->where('user.handle', 'octocat') ->has('users.data', 1) - ->where('users.data.0.id', $followed->id)); + ->where('users.data.0.id', $followed->id) + ->missing('users.data.0.pivot.notify_live')); }); it('lists the organizations a user follows apart, newest follow first, marking those the viewer follows', function (): void {